ngram
listlengths
0
82k
[ "extension classes.\"\"\" from typing import Dict, List, Optional from lxml", "Parameters ---------- atom_feed : Element The feed's root element. Returns", "\"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom", "for doi in self.__arxiv_doi: doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" )", "if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element", "of the entry's author nodes for entry_child in entry: if", "etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" )", "in self.__arxiv_authors: if first: first = False else: description +=", "entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry,", "\" name = ( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" ) description", "type attributes. \"\"\" self.__arxiv_media.append(media) def comment(self, text: str) -> None:", "-> None: \"\"\"Assign the comment value to this entry. Parameters", "text def journal_ref(self, text: str) -> None: \"\"\"Assign the journal_ref", "the Feedgen class to allow us to change its behavior.\"\"\"", "\"\"\"Assign the journal_ref value to this entry. Parameters ---------- text", "affiliations = self.__arxiv_affiliations.get(name, []) for affiliation in affiliations: element =", "Element) -> Element: \"\"\"Allow the extension to modify the initial", "None: \"\"\"Add an author value to this entry. Parameters ----------", "the extension to modify the entry element for Atom serialization.", "modify the entry element for RSS. Parameters ---------- entry :", "return atom_feed def extend_rss(self: BaseExtension, rss_feed: Element) -> Element: \"\"\"Allow", "None: \"\"\"Add a media item. Parameters ---------- media: Dict[str, str]", "Parameters ---------- full_name : str An author's full name. affiliations", "affiliation dictionary, # add Elements for all of its affiliations.", "Element: \"\"\" Allow the extension to modify the entry element", "doi_list: Dict[str, str]) -> None: \"\"\"Assign the set of DOI", ") description += ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description +=", "\"\"\" self.__arxiv_doi = doi_list def affiliation(self, full_name: str, affiliations: List[str])", "the author's name is in the affiliation dictionary, # add", "text : str The new primary_category name. \"\"\" self.__arxiv_primary_category =", "an author value to this entry. Parameters ---------- author :", "Media class ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen class to allow", "\"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type}, ) def extend_atom(self, entry: Element)", "feed's root element. \"\"\" return atom_feed def extend_rss(self: BaseExtension, rss_feed:", "for entry_child in entry: if entry_child.tag == \"author\": author =", "The feed's root element. Returns ------- atom_feed : Element The", "Element: \"\"\"Allow the extension to modify the entry element for", "( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\" entry_child.text =", "for one author of this entry. Parameters ---------- full_name :", "str) -> None: \"\"\"Assign the comment value to this entry.", "set of DOI definitions for this entry. Parameters ---------- doi_list", "Dict[str, str]) -> None: \"\"\"Assign the set of DOI definitions", "\"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\":", "affiliation(self, full_name: str, affiliations: List[str]) -> None: \"\"\"Assign an affiliation", "def author(self, author: Author) -> None: \"\"\"Add an author value", "Paper author. \"\"\" self.__arxiv_authors.append(author) def media(self, media: Media) -> None:", "value to this entry. Parameters ---------- author : Author Paper", "None: \"\"\"Assign an affiliation for one author of this entry.", "flask import current_app from feedgen.ext.base import BaseEntryExtension, BaseExtension from feed.domain", "\"name\": name = author_child.text affiliations = self.__arxiv_affiliations.get(name, []) for affiliation", "= entry_child for author_child in author: # If the author's", "all of its affiliations. if author_child.tag == \"name\": name =", ") def extend_atom(self, entry: Element) -> Element: \"\"\" Allow the", "media in self.__arxiv_media: group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title", "List[Author] = [] self.__arxiv_media: List[Media] = [] self.__arxiv_comment: Optional[str] =", "to modify the initial feed tree for Atom. Parameters ----------", "comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment if", "\"\"\"Initialize the member values to all be empty.\"\"\" self.__arxiv_authors: List[Author]", "Dict = {} def __add_media(self, entry: Element) -> None: for", "element. Returns ------- rss_feed : Element The feed's root element.", "self.__add_media(entry=entry) return entry def extend_rss(self, entry: Element) -> Element: \"\"\"Allow", "name = ( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" ) description +=", "comment text. \"\"\" self.__arxiv_comment = text def primary_category(self, text: str)", "this entry. Parameters ---------- full_name : str An author's full", "---------- media: Dict[str, str] Dictionary with url and type attributes.", "\"\"\" Allow the extension to modify the entry element for", "self.__arxiv_doi = doi_list def affiliation(self, full_name: str, affiliations: List[str]) ->", "self.__add_media(entry=entry) return entry def author(self, author: Author) -> None: \"\"\"Add", "The modified entry. \"\"\" if self.__arxiv_comment: comment_element = etree.SubElement( entry,", "rss_feed def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define the", "+= ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\" entry_child.text", "its behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed: Element) -> Element: \"\"\"Allow", "if author_child.tag == \"name\": name = author_child.text affiliations = self.__arxiv_affiliations.get(name,", "modify the initial feed tree for RSS. Parameters ---------- rss_feed", "= current_app.config[\"BASE_SERVER\"] for entry_child in entry: if entry_child.tag == \"description\":", "to this entry. Parameters ---------- author : Author Paper author.", "namespaces. Returns ------- namespaces : Dict[str, str] Definitions of the", "is in the affiliation dictionary, # add Elements for all", "def affiliation(self, full_name: str, affiliations: List[str]) -> None: \"\"\"Assign an", "text: str) -> None: \"\"\"Assign the journal_ref value to this", "nodes for entry_child in entry: if entry_child.tag == \"author\": author", "Returns ------- namespaces : Dict[str, str] Definitions of the \"arxiv\"", "etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi # Check each", "Returns ------- entry : Element The modified entry. \"\"\" if", "the entry's author nodes for entry_child in entry: if entry_child.tag", ": Element The feed's root element. Returns ------- rss_feed :", "the primary_category value to this entry. Parameters ---------- text :", ": Element The feed's root element. Returns ------- atom_feed :", "The new primary_category name. \"\"\" self.__arxiv_primary_category = text def journal_ref(self,", "= etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi:", "feed's root element. \"\"\" return rss_feed def extend_ns(self: BaseExtension) ->", "self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref", "List[str]) -> None: \"\"\"Assign an affiliation for one author of", "modify the entry element for Atom serialization. Parameters ---------- entry", "media.url, \"type\": media.type}, ) def extend_atom(self, entry: Element) -> Element:", "author_child.text affiliations = self.__arxiv_affiliations.get(name, []) for affiliation in affiliations: element", "author in self.__arxiv_authors: if first: first = False else: description", ": Author Paper author. \"\"\" self.__arxiv_authors.append(author) def media(self, media: Media)", "None: \"\"\"Assign the comment value to this entry. Parameters ----------", "\"\"\"Extension of the Feedgen class to allow us to change", "this entry. Parameters ---------- text : str The new primary_category", ": Element The feed's root element. \"\"\" return rss_feed def", "\"\"\"Assign the primary_category value to this entry. Parameters ---------- text", "code for the author's affiliated institution. \"\"\" self.__arxiv_affiliations[full_name] = affiliations", "self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation: Optional[str]", ": List[str] The code for the author's affiliated institution. \"\"\"", "---------- full_name : str An author's full name. affiliations :", "values to all be empty.\"\"\" self.__arxiv_authors: List[Author] = [] self.__arxiv_media:", "for author_child in author: # If the author's name is", "entry_child in entry: if entry_child.tag == \"author\": author = entry_child", "extend_atom(self: BaseExtension, atom_feed: Element) -> Element: \"\"\"Allow the extension to", "\"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension):", "feed's root element. Returns ------- rss_feed : Element The feed's", "= None self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations: Dict = {}", "to modify the initial feed tree for RSS. Parameters ----------", "str, affiliations: List[str]) -> None: \"\"\"Assign an affiliation for one", "== \"author\": author = entry_child for author_child in author: #", "if self.__arxiv_comment: comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text =", "self.__arxiv_journal_ref if self.__arxiv_doi: for doi in self.__arxiv_doi: doi_element = etree.SubElement(", "= None self.__arxiv_affiliations: Dict = {} def __add_media(self, entry: Element)", "Dict[str, str] A dictionary of DOI assignments. \"\"\" self.__arxiv_doi =", "an affiliation for one author of this entry. Parameters ----------", "-> None: \"\"\"Add an author value to this entry. Parameters", "= etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text = media.title etree.SubElement( group,", "journal_ref value. \"\"\" self.__arxiv_journal_ref = text def doi(self, doi_list: Dict[str,", "element. Returns ------- atom_feed : Element The feed's root element.", "self.__arxiv_media: group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement(", "entry_child.text = description self.__add_media(entry=entry) return entry def author(self, author: Author)", "def extend_atom(self, entry: Element) -> Element: \"\"\" Allow the extension", "journal_ref(self, text: str) -> None: \"\"\"Assign the journal_ref value to", "feedgen.ext.base import BaseEntryExtension, BaseExtension from feed.domain import Author, Media class", "Element) -> Element: \"\"\" Allow the extension to modify the", "-> Element: \"\"\"Allow the extension to modify the initial feed", "return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\",", "doi(self, doi_list: Dict[str, str]) -> None: \"\"\"Assign the set of", "from lxml.etree import Element from flask import current_app from feedgen.ext.base", "primary_category(self, text: str) -> None: \"\"\"Assign the primary_category value to", "name. affiliations : List[str] The code for the author's affiliated", "-> None: for media in self.__arxiv_media: group = etree.SubElement( entry,", "author value to this entry. Parameters ---------- author : Author", "text def primary_category(self, text: str) -> None: \"\"\"Assign the primary_category", "element.text = affiliation self.__add_media(entry=entry) return entry def extend_rss(self, entry: Element)", "first = False else: description += \", \" name =", "behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize the member values to all", "to change its behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed: Element) ->", "<reponame>cul-it/arxiv-rss \"\"\"Classes derived from the Feedgen extension classes.\"\"\" from typing", "------- atom_feed : Element The feed's root element. \"\"\" return", "entry : Element The modified entry. \"\"\" base_server: str =", "first: first = False else: description += \", \" name", "element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation self.__add_media(entry=entry)", "---------- author : Author Paper author. \"\"\" self.__arxiv_authors.append(author) def media(self,", "Entry class to allow us to change its behavior.\"\"\" def", "and type attributes. \"\"\" self.__arxiv_media.append(media) def comment(self, text: str) ->", "self.__arxiv_comment: comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment", "doi_list def affiliation(self, full_name: str, affiliations: List[str]) -> None: \"\"\"Assign", "{ \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\":", "Dictionary with url and type attributes. \"\"\" self.__arxiv_media.append(media) def comment(self,", "\"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", }", "serialization. Parameters ---------- entry : Element The FeedEntry to modify.", "this entry. Parameters ---------- author : Author Paper author. \"\"\"", "return entry def author(self, author: Author) -> None: \"\"\"Add an", "\"\"\"Allow the extension to modify the initial feed tree for", "feed's namespaces. Returns ------- namespaces : Dict[str, str] Definitions of", "-> None: \"\"\"Assign the journal_ref value to this entry. Parameters", "the initial feed tree for RSS. Parameters ---------- rss_feed :", "extension to modify the initial feed tree for RSS. Parameters", "Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen class to", "for RSS. Parameters ---------- rss_feed : Element The feed's root", "the extension to modify the initial feed tree for Atom.", "Parameters ---------- rss_feed : Element The feed's root element. Returns", "= [] self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category: Optional[str] = None", "full_name: str, affiliations: List[str]) -> None: \"\"\"Assign an affiliation for", "group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement( group,", "Optional[str] = None self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations: Dict =", "tree for Atom. Parameters ---------- atom_feed : Element The feed's", ") element.text = affiliation self.__add_media(entry=entry) return entry def extend_rss(self, entry:", "in entry: if entry_child.tag == \"description\": description = \"<p>Authors: \"", "\"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def extend_ns(self: BaseExtension)", "if entry_child.tag == \"author\": author = entry_child for author_child in", "affiliation for one author of this entry. Parameters ---------- full_name", "str The new comment text. \"\"\" self.__arxiv_comment = text def", "BaseExtension, atom_feed: Element) -> Element: \"\"\"Allow the extension to modify", "affiliation self.__add_media(entry=entry) return entry def extend_rss(self, entry: Element) -> Element:", "\"\"\" if self.__arxiv_comment: comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text", "The modified entry. \"\"\" base_server: str = current_app.config[\"BASE_SERVER\"] for entry_child", "str) -> None: \"\"\"Assign the primary_category value to this entry.", "new primary_category name. \"\"\" self.__arxiv_primary_category = text def journal_ref(self, text:", "str] A dictionary of DOI assignments. \"\"\" self.__arxiv_doi = doi_list", "{} def __add_media(self, entry: Element) -> None: for media in", "extension to modify the initial feed tree for Atom. Parameters", "entry_child.tag == \"author\": author = entry_child for author_child in author:", "= affiliation self.__add_media(entry=entry) return entry def extend_rss(self, entry: Element) ->", "\"\"\" return atom_feed def extend_rss(self: BaseExtension, rss_feed: Element) -> Element:", "\"\"\" base_server: str = current_app.config[\"BASE_SERVER\"] for entry_child in entry: if", "[] self.__arxiv_media: List[Media] = [] self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category:", "Atom serialization. Parameters ---------- entry : Element The FeedEntry to", "to modify. Returns ------- entry : Element The modified entry.", "author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation self.__add_media(entry=entry) return entry def", "description = \"<p>Authors: \" first = True for author in", "etree from lxml.etree import Element from flask import current_app from", "\"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\",", "def extend_rss(self, entry: Element) -> Element: \"\"\"Allow the extension to", "media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type}, ) def", "Definitions of the \"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\",", "namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\",", "------- entry : Element The modified entry. \"\"\" if self.__arxiv_comment:", "entry_child in entry: if entry_child.tag == \"description\": description = \"<p>Authors:", "the journal_ref value to this entry. Parameters ---------- text :", "comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, )", "------- namespaces : Dict[str, str] Definitions of the \"arxiv\" namespaces.", "add Elements for all of its affiliations. if author_child.tag ==", "-> Dict[str, str]: \"\"\" Define the feed's namespaces. Returns -------", "{ \"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry", "affiliation in affiliations: element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text", "extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define the feed's namespaces.", "\"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\"", "ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen class to allow us to", "this entry. Parameters ---------- doi_list : Dict[str, str] A dictionary", "for this entry. Parameters ---------- doi_list : Dict[str, str] A", "entry. Parameters ---------- full_name : str An author's full name.", "to change its behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize the member", "None self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref:", "True for author in self.__arxiv_authors: if first: first = False", "Dict[str, str]: \"\"\" Define the feed's namespaces. Returns ------- namespaces", "for affiliation in affiliations: element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", )", "RSS. Parameters ---------- entry : Element The FeedEntry to modify.", "Element The feed's root element. \"\"\" return rss_feed def extend_ns(self:", "author of this entry. Parameters ---------- full_name : str An", "to this entry. Parameters ---------- text : str The new", "element. \"\"\" return rss_feed def extend_ns(self: BaseExtension) -> Dict[str, str]:", "---------- text : str The new comment text. \"\"\" self.__arxiv_comment", ") journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi: for doi in self.__arxiv_doi:", "if entry_child.tag == \"description\": description = \"<p>Authors: \" first =", "of the \"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\":", "Author) -> None: \"\"\"Add an author value to this entry.", "name = author_child.text affiliations = self.__arxiv_affiliations.get(name, []) for affiliation in", "of this entry. Parameters ---------- full_name : str An author's", "\"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\",", "= None self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi: Optional[dict] = None", "None: \"\"\"Assign the set of DOI definitions for this entry.", "self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi: Optional[dict]", "doi # Check each of the entry's author nodes for", "namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension", "# Check each of the entry's author nodes for entry_child", "Parameters ---------- doi_list : Dict[str, str] A dictionary of DOI", "journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi: for doi in self.__arxiv_doi: doi_element", "Returns ------- atom_feed : Element The feed's root element. \"\"\"", "lxml.etree import Element from flask import current_app from feedgen.ext.base import", "Element The feed's root element. Returns ------- atom_feed : Element", "def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define the feed's", "\"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi: for doi in", "for all of its affiliations. if author_child.tag == \"name\": name", "media item. Parameters ---------- media: Dict[str, str] Dictionary with url", "of the Feedgen class to allow us to change its", "element for RSS. Parameters ---------- entry : Element The FeedEntry", "us to change its behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed: Element)", "primary_category name. \"\"\" self.__arxiv_primary_category = text def journal_ref(self, text: str)", "str]) -> None: \"\"\"Assign the set of DOI definitions for", "\"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class", "The feed's root element. \"\"\" return rss_feed def extend_ns(self: BaseExtension)", "\"type\": media.type}, ) def extend_atom(self, entry: Element) -> Element: \"\"\"", "DOI definitions for this entry. Parameters ---------- doi_list : Dict[str,", "= [] self.__arxiv_media: List[Media] = [] self.__arxiv_comment: Optional[str] = None", "\"<p>Authors: \" first = True for author in self.__arxiv_authors: if", "extend_atom(self, entry: Element) -> Element: \"\"\" Allow the extension to", "List, Optional from lxml import etree from lxml.etree import Element", "doi_element.text = doi # Check each of the entry's author", "author's full name. affiliations : List[str] The code for the", "the comment value to this entry. Parameters ---------- text :", "us to change its behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize the", "entry. \"\"\" base_server: str = current_app.config[\"BASE_SERVER\"] for entry_child in entry:", "\"\"\"Assign the comment value to this entry. Parameters ---------- text", "the Entry class to allow us to change its behavior.\"\"\"", "import Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen class", "entry def extend_rss(self, entry: Element) -> Element: \"\"\"Allow the extension", "namespaces : Dict[str, str] Definitions of the \"arxiv\" namespaces. \"\"\"", "BaseExtension from feed.domain import Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension of", "group, \"{http://search.yahoo.com/mrss}title\" ) title.text = media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\":", "Element) -> Element: \"\"\"Allow the extension to modify the entry", "Element The feed's root element. \"\"\" return atom_feed def extend_rss(self:", "initial feed tree for RSS. Parameters ---------- rss_feed : Element", "str An author's full name. affiliations : List[str] The code", "\"\"\" self.__arxiv_primary_category = text def journal_ref(self, text: str) -> None:", "author nodes for entry_child in entry: if entry_child.tag == \"author\":", "feed's root element. Returns ------- atom_feed : Element The feed's", "allow us to change its behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed:", "entry. Parameters ---------- text : str The new primary_category name.", "modified entry. \"\"\" base_server: str = current_app.config[\"BASE_SERVER\"] for entry_child in", "etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation self.__add_media(entry=entry) return entry", "full name. affiliations : List[str] The code for the author's", "dictionary of DOI assignments. \"\"\" self.__arxiv_doi = doi_list def affiliation(self,", "BaseExtension, rss_feed: Element) -> Element: \"\"\"Allow the extension to modify", ": str The new comment text. \"\"\" self.__arxiv_comment = text", "import Dict, List, Optional from lxml import etree from lxml.etree", "self.__arxiv_comment = text def primary_category(self, text: str) -> None: \"\"\"Assign", "\"\"\"Atom only extension.\"\"\" def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\"", "\"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def", "Author Paper author. \"\"\" self.__arxiv_authors.append(author) def media(self, media: Media) ->", "def extend_atom(self: BaseExtension, atom_feed: Element) -> Element: \"\"\"Allow the extension", "f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" ) description += ( f'<a href=\"http://{base_server}/search/?query={name}&'", "entry: Element) -> Element: \"\"\"Allow the extension to modify the", "member values to all be empty.\"\"\" self.__arxiv_authors: List[Author] = []", "self.__arxiv_doi: for doi in self.__arxiv_doi: doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\"", "= self.__arxiv_affiliations.get(name, []) for affiliation in affiliations: element = etree.SubElement(", "\"\"\"Allow the extension to modify the entry element for RSS.", "media(self, media: Media) -> None: \"\"\"Add a media item. Parameters", ": str The new primary_category name. \"\"\" self.__arxiv_primary_category = text", "author = entry_child for author_child in author: # If the", "entry : Element The modified entry. \"\"\" if self.__arxiv_comment: comment_element", "Parameters ---------- entry : Element The FeedEntry to modify. Returns", "etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement(", "Optional[dict] = None self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref: Optional[str] =", "class ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen class to allow us", "= self.__arxiv_journal_ref if self.__arxiv_doi: for doi in self.__arxiv_doi: doi_element =", ") title.text = media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\":", "assignments. \"\"\" self.__arxiv_doi = doi_list def affiliation(self, full_name: str, affiliations:", "feed.domain import Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension of the Feedgen", "= self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if", "first = True for author in self.__arxiv_authors: if first: first", "from lxml import etree from lxml.etree import Element from flask", ": str An author's full name. affiliations : List[str] The", "\"\"\" self.__arxiv_media.append(media) def comment(self, text: str) -> None: \"\"\"Assign the", ") comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category,", "description += ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\"", "\"\"\"Assign an affiliation for one author of this entry. Parameters", "The new comment text. \"\"\" self.__arxiv_comment = text def primary_category(self,", "= None self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation: Optional[str] = None", "entry: Element) -> Element: \"\"\" Allow the extension to modify", "the initial feed tree for Atom. Parameters ---------- atom_feed :", ": Dict[str, str] A dictionary of DOI assignments. \"\"\" self.__arxiv_doi", ": Dict[str, str] Definitions of the \"arxiv\" namespaces. \"\"\" return", "extension to modify the entry element for Atom serialization. Parameters", "of DOI definitions for this entry. Parameters ---------- doi_list :", "= \"<p>Authors: \" first = True for author in self.__arxiv_authors:", "root element. Returns ------- rss_feed : Element The feed's root", "in self.__arxiv_doi: doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text =", "entry. \"\"\" if self.__arxiv_comment: comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" )", "-> None: \"\"\"Assign the set of DOI definitions for this", "entry. Parameters ---------- text : str The new journal_ref value.", "BaseExtension) -> Dict[str, str]: \"\"\" Define the feed's namespaces. Returns", "ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def extend_ns(self: BaseExtension) -> Dict[str, str]:", "The feed's root element. \"\"\" return atom_feed def extend_rss(self: BaseExtension,", "---------- entry : Element The FeedEntry to modify. Returns -------", "with url and type attributes. \"\"\" self.__arxiv_media.append(media) def comment(self, text:", "Element from flask import current_app from feedgen.ext.base import BaseEntryExtension, BaseExtension", "text : str The new journal_ref value. \"\"\" self.__arxiv_journal_ref =", "comment(self, text: str) -> None: \"\"\"Assign the comment value to", "entry. Parameters ---------- text : str The new comment text.", "feed tree for RSS. Parameters ---------- rss_feed : Element The", "one author of this entry. Parameters ---------- full_name : str", "Returns ------- rss_feed : Element The feed's root element. \"\"\"", "href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry)", "Allow the extension to modify the entry element for Atom", "affiliations : List[str] The code for the author's affiliated institution.", "of the Entry class to allow us to change its", "\"{http://search.yahoo.com/mrss}title\" ) title.text = media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url,", "comment value to this entry. Parameters ---------- text : str", "author: Author) -> None: \"\"\"Add an author value to this", "\"\"\"Add an author value to this entry. Parameters ---------- author", "the member values to all be empty.\"\"\" self.__arxiv_authors: List[Author] =", "item. Parameters ---------- media: Dict[str, str] Dictionary with url and", "f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry) return entry def author(self, author:", "each of the entry's author nodes for entry_child in entry:", "title.text = media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type},", "-> Element: \"\"\" Allow the extension to modify the entry", "the affiliation dictionary, # add Elements for all of its", "for media in self.__arxiv_media: group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" )", "Dict[str, str] Dictionary with url and type attributes. \"\"\" self.__arxiv_media.append(media)", "modified entry. \"\"\" if self.__arxiv_comment: comment_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\"", "for Atom. Parameters ---------- atom_feed : Element The feed's root", "author's name is in the affiliation dictionary, # add Elements", "text : str The new comment text. \"\"\" self.__arxiv_comment =", "entry element for Atom serialization. Parameters ---------- entry : Element", "return { \"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the", "RSS. Parameters ---------- rss_feed : Element The feed's root element.", ") description += f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry) return entry", "author(self, author: Author) -> None: \"\"\"Add an author value to", "class to allow us to change its behavior.\"\"\" def extend_atom(self:", "to allow us to change its behavior.\"\"\" def __init__(self: BaseEntryExtension):", "a media item. Parameters ---------- media: Dict[str, str] Dictionary with", "', '+')}\" ) description += ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' )", "self.__arxiv_media: List[Media] = [] self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category: Optional[str]", "None self.__arxiv_affiliations: Dict = {} def __add_media(self, entry: Element) ->", "in the affiliation dictionary, # add Elements for all of", "entry. Parameters ---------- doi_list : Dict[str, str] A dictionary of", "\"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry class", "Element The modified entry. \"\"\" if self.__arxiv_comment: comment_element = etree.SubElement(", "new comment text. \"\"\" self.__arxiv_comment = text def primary_category(self, text:", "Media) -> None: \"\"\"Add a media item. Parameters ---------- media:", "etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text = media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\",", "Check each of the entry's author nodes for entry_child in", "self.__arxiv_authors.append(author) def media(self, media: Media) -> None: \"\"\"Add a media", "the extension to modify the initial feed tree for RSS.", "------- entry : Element The modified entry. \"\"\" base_server: str", "An author's full name. affiliations : List[str] The code for", ": Element The modified entry. \"\"\" base_server: str = current_app.config[\"BASE_SERVER\"]", "str The new primary_category name. \"\"\" self.__arxiv_primary_category = text def", "str = current_app.config[\"BASE_SERVER\"] for entry_child in entry: if entry_child.tag ==", "root element. \"\"\" return rss_feed def extend_ns(self: BaseExtension) -> Dict[str,", "\"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\"", "self.__arxiv_authors: if first: first = False else: description += \",", "\"\"\" self.__arxiv_comment = text def primary_category(self, text: str) -> None:", "import current_app from feedgen.ext.base import BaseEntryExtension, BaseExtension from feed.domain import", "to modify the entry element for RSS. Parameters ---------- entry", "---------- text : str The new primary_category name. \"\"\" self.__arxiv_primary_category", "group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type}, ) def extend_atom(self, entry:", "lxml import etree from lxml.etree import Element from flask import", "import etree from lxml.etree import Element from flask import current_app", "f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry) return", "self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element =", "__add_media(self, entry: Element) -> None: for media in self.__arxiv_media: group", "\"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation self.__add_media(entry=entry) return entry def extend_rss(self,", "None: \"\"\"Assign the primary_category value to this entry. Parameters ----------", "-> Element: \"\"\"Allow the extension to modify the entry element", "self.__arxiv_primary_category = text def journal_ref(self, text: str) -> None: \"\"\"Assign", "this entry. Parameters ---------- text : str The new comment", "Atom. Parameters ---------- atom_feed : Element The feed's root element.", "to modify the entry element for Atom serialization. Parameters ----------", "this entry. Parameters ---------- text : str The new journal_ref", "journal_ref value to this entry. Parameters ---------- text : str", "text: str) -> None: \"\"\"Assign the primary_category value to this", "definitions for this entry. Parameters ---------- doi_list : Dict[str, str]", "from typing import Dict, List, Optional from lxml import etree", "affiliations: element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation", "List[str] The code for the author's affiliated institution. \"\"\" self.__arxiv_affiliations[full_name]", "empty.\"\"\" self.__arxiv_authors: List[Author] = [] self.__arxiv_media: List[Media] = [] self.__arxiv_comment:", "entry, \"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text", "= etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category:", "f\"+{author.initials.replace(' ', '+')}\" ) description += ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>'", "= etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi # Check", "self.__arxiv_authors: List[Author] = [] self.__arxiv_media: List[Media] = [] self.__arxiv_comment: Optional[str]", "url and type attributes. \"\"\" self.__arxiv_media.append(media) def comment(self, text: str)", "Parameters ---------- media: Dict[str, str] Dictionary with url and type", "return entry def extend_rss(self, entry: Element) -> Element: \"\"\"Allow the", "the Feedgen extension classes.\"\"\" from typing import Dict, List, Optional", "element for Atom serialization. Parameters ---------- entry : Element The", "rss_feed: Element) -> Element: \"\"\"Allow the extension to modify the", "affiliations. if author_child.tag == \"name\": name = author_child.text affiliations =", "extend_rss(self, entry: Element) -> Element: \"\"\"Allow the extension to modify", "self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations: Dict", "of the \"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", }", "Element The FeedEntry to modify. Returns ------- entry : Element", "doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi #", "Optional[str] = None self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation: Optional[str] =", "} class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry class to allow", "= text def journal_ref(self, text: str) -> None: \"\"\"Assign the", "= {} def __add_media(self, entry: Element) -> None: for media", "change its behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed: Element) -> Element:", "extend_rss(self: BaseExtension, rss_feed: Element) -> Element: \"\"\"Allow the extension to", "in entry: if entry_child.tag == \"author\": author = entry_child for", "self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref: Optional[str]", "value. \"\"\" self.__arxiv_journal_ref = text def doi(self, doi_list: Dict[str, str])", "def journal_ref(self, text: str) -> None: \"\"\"Assign the journal_ref value", "Feedgen class to allow us to change its behavior.\"\"\" def", "---------- rss_feed : Element The feed's root element. Returns -------", "\"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\": \"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\":", "modify the initial feed tree for Atom. Parameters ---------- atom_feed", "atom_feed : Element The feed's root element. \"\"\" return atom_feed", ") title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text = media.title", "\"\"\"Assign the set of DOI definitions for this entry. Parameters", "\"\"\" Define the feed's namespaces. Returns ------- namespaces : Dict[str,", "---------- doi_list : Dict[str, str] A dictionary of DOI assignments.", "__init__(self: BaseEntryExtension): \"\"\"Initialize the member values to all be empty.\"\"\"", ") doi_element.text = doi # Check each of the entry's", "= description self.__add_media(entry=entry) return entry def author(self, author: Author) ->", "\"\"\"Add a media item. Parameters ---------- media: Dict[str, str] Dictionary", "self.__arxiv_affiliations.get(name, []) for affiliation in affiliations: element = etree.SubElement( author,", "from flask import current_app from feedgen.ext.base import BaseEntryExtension, BaseExtension from", "def extend_rss(self: BaseExtension, rss_feed: Element) -> Element: \"\"\"Allow the extension", "If the author's name is in the affiliation dictionary, #", "BaseEntryExtension, BaseExtension from feed.domain import Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension", "root element. Returns ------- atom_feed : Element The feed's root", "class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry class to allow us", "of its affiliations. if author_child.tag == \"name\": name = author_child.text", "== \"description\": description = \"<p>Authors: \" first = True for", "DOI assignments. \"\"\" self.__arxiv_doi = doi_list def affiliation(self, full_name: str,", "\"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi # Check each of the", "( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" ) description += ( f'<a", "List[Media] = [] self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category: Optional[str] =", "the entry element for Atom serialization. Parameters ---------- entry :", "only extension.\"\"\" def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define", "for entry_child in entry: if entry_child.tag == \"description\": description =", "+= f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry) return entry def author(self,", "\" first = True for author in self.__arxiv_authors: if first:", "Optional from lxml import etree from lxml.etree import Element from", "the \"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\",", "self.__arxiv_media.append(media) def comment(self, text: str) -> None: \"\"\"Assign the comment", "ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry class to allow us to", "None: \"\"\"Assign the journal_ref value to this entry. Parameters ----------", "str The new journal_ref value. \"\"\" self.__arxiv_journal_ref = text def", "Element: \"\"\"Allow the extension to modify the initial feed tree", "Optional[str] = None self.__arxiv_affiliations: Dict = {} def __add_media(self, entry:", "in self.__arxiv_media: group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title =", "entry def author(self, author: Author) -> None: \"\"\"Add an author", ": Element The modified entry. \"\"\" if self.__arxiv_comment: comment_element =", "False else: description += \", \" name = ( f\"{author.last_name},\"", "= doi_list def affiliation(self, full_name: str, affiliations: List[str]) -> None:", "etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement(", "if first: first = False else: description += \", \"", "Element The modified entry. \"\"\" base_server: str = current_app.config[\"BASE_SERVER\"] for", "def comment(self, text: str) -> None: \"\"\"Assign the comment value", "\"\"\" self.__arxiv_authors.append(author) def media(self, media: Media) -> None: \"\"\"Add a", "atom_feed: Element) -> Element: \"\"\"Allow the extension to modify the", "its affiliations. if author_child.tag == \"name\": name = author_child.text affiliations", "entry_child.tag == \"description\": description = \"<p>Authors: \" first = True", "rss_feed : Element The feed's root element. \"\"\" return rss_feed", "# If the author's name is in the affiliation dictionary,", "value to this entry. Parameters ---------- text : str The", "The code for the author's affiliated institution. \"\"\" self.__arxiv_affiliations[full_name] =", "the set of DOI definitions for this entry. Parameters ----------", "None self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations:", "tree for RSS. Parameters ---------- rss_feed : Element The feed's", "description += f\"</p><p>{entry_child.text}</p>\" entry_child.text = description self.__add_media(entry=entry) return entry def", "description += \", \" name = ( f\"{author.last_name},\" f\"+{author.initials.replace(' ',", "rss_feed : Element The feed's root element. Returns ------- rss_feed", "typing import Dict, List, Optional from lxml import etree from", "= etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\"", "self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\", attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref:", ": Element The FeedEntry to modify. Returns ------- entry :", "entry_child for author_child in author: # If the author's name", "Returns ------- entry : Element The modified entry. \"\"\" base_server:", "for author in self.__arxiv_authors: if first: first = False else:", "in author: # If the author's name is in the", "Dict[str, str] Definitions of the \"arxiv\" namespaces. \"\"\" return {", "self.__arxiv_journal_ref = text def doi(self, doi_list: Dict[str, str]) -> None:", "return rss_feed def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define", "author. \"\"\" self.__arxiv_authors.append(author) def media(self, media: Media) -> None: \"\"\"Add", "all be empty.\"\"\" self.__arxiv_authors: List[Author] = [] self.__arxiv_media: List[Media] =", "its behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize the member values to", "None self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi: Optional[dict] = None self.__arxiv_affiliation:", "entry element for RSS. Parameters ---------- entry : Element The", "else: description += \", \" name = ( f\"{author.last_name},\" f\"+{author.initials.replace('", "derived from the Feedgen extension classes.\"\"\" from typing import Dict,", "def doi(self, doi_list: Dict[str, str]) -> None: \"\"\"Assign the set", "for Atom serialization. Parameters ---------- entry : Element The FeedEntry", "class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def extend_ns(self: BaseExtension) -> Dict[str,", "\"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def extend_ns(self:", "\"description\": description = \"<p>Authors: \" first = True for author", "Dict, List, Optional from lxml import etree from lxml.etree import", "affiliations: List[str]) -> None: \"\"\"Assign an affiliation for one author", "'+')}\" ) description += ( f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description", "-> None: \"\"\"Assign the primary_category value to this entry. Parameters", "doi_list : Dict[str, str] A dictionary of DOI assignments. \"\"\"", "author_child.tag == \"name\": name = author_child.text affiliations = self.__arxiv_affiliations.get(name, [])", "The feed's root element. Returns ------- rss_feed : Element The", "entry : Element The FeedEntry to modify. Returns ------- entry", "= doi # Check each of the entry's author nodes", "def media(self, media: Media) -> None: \"\"\"Add a media item.", "text def doi(self, doi_list: Dict[str, str]) -> None: \"\"\"Assign the", "None: for media in self.__arxiv_media: group = etree.SubElement( entry, \"{http://search.yahoo.com/mrss}group\"", "= media.title etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type}, )", "etree.SubElement( group, \"{http://search.yahoo.com/mrss}content\", attrib={\"url\": media.url, \"type\": media.type}, ) def extend_atom(self,", "self.__arxiv_affiliations: Dict = {} def __add_media(self, entry: Element) -> None:", "\"author\": author = entry_child for author_child in author: # If", "str] Definitions of the \"arxiv\" namespaces. \"\"\" return { \"arxiv\":", "\"http://purl.org/rss/1.0/modules/taxonomy/\", \"syn\": \"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension):", "\"\"\"Extension of the Entry class to allow us to change", "---------- text : str The new journal_ref value. \"\"\" self.__arxiv_journal_ref", "\"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}primary_category\",", "title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text = media.title etree.SubElement(", "-> None: \"\"\"Assign an affiliation for one author of this", "Elements for all of its affiliations. if author_child.tag == \"name\":", "change its behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize the member values", "author: # If the author's name is in the affiliation", "author_child in author: # If the author's name is in", "of DOI assignments. \"\"\" self.__arxiv_doi = doi_list def affiliation(self, full_name:", "str) -> None: \"\"\"Assign the journal_ref value to this entry.", "to all be empty.\"\"\" self.__arxiv_authors: List[Author] = [] self.__arxiv_media: List[Media]", "atom_feed : Element The feed's root element. Returns ------- atom_feed", "\"{http://search.yahoo.com/mrss}group\" ) title = etree.SubElement( group, \"{http://search.yahoo.com/mrss}title\" ) title.text =", "the entry element for RSS. Parameters ---------- entry : Element", "current_app from feedgen.ext.base import BaseEntryExtension, BaseExtension from feed.domain import Author,", "Parameters ---------- text : str The new primary_category name. \"\"\"", "from feedgen.ext.base import BaseEntryExtension, BaseExtension from feed.domain import Author, Media", "extension.\"\"\" def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\" Define the", "entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi: for doi", "initial feed tree for Atom. Parameters ---------- atom_feed : Element", "name. \"\"\" self.__arxiv_primary_category = text def journal_ref(self, text: str) ->", "The new journal_ref value. \"\"\" self.__arxiv_journal_ref = text def doi(self,", "= text def doi(self, doi_list: Dict[str, str]) -> None: \"\"\"Assign", "\", \" name = ( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" )", "entry, \"{http://arxiv.org/schemas/atom}comment\" ) comment_element.text = self.__arxiv_comment if self.__arxiv_primary_category: etree.SubElement( entry,", "\"\"\"Classes derived from the Feedgen extension classes.\"\"\" from typing import", "journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref if", "classes.\"\"\" from typing import Dict, List, Optional from lxml import", "from feed.domain import Author, Media class ArxivExtension(BaseExtension): \"\"\"Extension of the", "primary_category value to this entry. Parameters ---------- text : str", "from the Feedgen extension classes.\"\"\" from typing import Dict, List,", "The FeedEntry to modify. Returns ------- entry : Element The", ": str The new journal_ref value. \"\"\" self.__arxiv_journal_ref = text", "[]) for affiliation in affiliations: element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\",", "f'<a href=\"http://{base_server}/search/?query={name}&' f'searchtype=author\">{author.full_name}</a>' ) description += f\"</p><p>{entry_child.text}</p>\" entry_child.text = description", "description self.__add_media(entry=entry) return entry def author(self, author: Author) -> None:", "extension to modify the entry element for RSS. Parameters ----------", "attributes. \"\"\" self.__arxiv_media.append(media) def comment(self, text: str) -> None: \"\"\"Assign", "\"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", \"content\": \"http://purl.org/rss/1.0/modules/content/\", \"taxo\":", "in affiliations: element = etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text =", "Parameters ---------- author : Author Paper author. \"\"\" self.__arxiv_authors.append(author) def", "Feedgen extension classes.\"\"\" from typing import Dict, List, Optional from", "to allow us to change its behavior.\"\"\" def extend_atom(self: BaseExtension,", "BaseEntryExtension): \"\"\"Initialize the member values to all be empty.\"\"\" self.__arxiv_authors:", "FeedEntry to modify. Returns ------- entry : Element The modified", "} class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only extension.\"\"\" def extend_ns(self: BaseExtension) ->", "def __add_media(self, entry: Element) -> None: for media in self.__arxiv_media:", "import BaseEntryExtension, BaseExtension from feed.domain import Author, Media class ArxivExtension(BaseExtension):", "dictionary, # add Elements for all of its affiliations. if", "[] self.__arxiv_comment: Optional[str] = None self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi:", "allow us to change its behavior.\"\"\" def __init__(self: BaseEntryExtension): \"\"\"Initialize", "root element. \"\"\" return atom_feed def extend_rss(self: BaseExtension, rss_feed: Element)", "str]: \"\"\" Define the feed's namespaces. Returns ------- namespaces :", "self.__arxiv_doi: doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi", "class to allow us to change its behavior.\"\"\" def __init__(self:", "# add Elements for all of its affiliations. if author_child.tag", "name is in the affiliation dictionary, # add Elements for", "new journal_ref value. \"\"\" self.__arxiv_journal_ref = text def doi(self, doi_list:", "= ( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\" ) description += (", "A dictionary of DOI assignments. \"\"\" self.__arxiv_doi = doi_list def", "Parameters ---------- text : str The new comment text. \"\"\"", "entry. Parameters ---------- author : Author Paper author. \"\"\" self.__arxiv_authors.append(author)", "str] Dictionary with url and type attributes. \"\"\" self.__arxiv_media.append(media) def", "None self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations: Dict = {} def", "if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text =", "full_name : str An author's full name. affiliations : List[str]", "be empty.\"\"\" self.__arxiv_authors: List[Author] = [] self.__arxiv_media: List[Media] = []", "= author_child.text affiliations = self.__arxiv_affiliations.get(name, []) for affiliation in affiliations:", ": Element The feed's root element. \"\"\" return atom_feed def", "Element) -> None: for media in self.__arxiv_media: group = etree.SubElement(", "base_server: str = current_app.config[\"BASE_SERVER\"] for entry_child in entry: if entry_child.tag", "attrib={\"url\": media.url, \"type\": media.type}, ) def extend_atom(self, entry: Element) ->", "= text def primary_category(self, text: str) -> None: \"\"\"Assign the", "= True for author in self.__arxiv_authors: if first: first =", "element. \"\"\" return atom_feed def extend_rss(self: BaseExtension, rss_feed: Element) ->", "\"http://purl.org/rss/1.0/modules/syndication/\", \"admin\": \"http://webns.net/mvcb/\", \"media\": \"http://search.yahoo.com/mrss\", } class ArxivAtomExtension(BaseEntryExtension): \"\"\"Atom only", "\"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of the Entry class to", "modify. Returns ------- entry : Element The modified entry. \"\"\"", "self.__arxiv_journal_ref: Optional[str] = None self.__arxiv_affiliations: Dict = {} def __add_media(self,", "== \"name\": name = author_child.text affiliations = self.__arxiv_affiliations.get(name, []) for", "Optional[str] = None self.__arxiv_primary_category: Optional[str] = None self.__arxiv_doi: Optional[dict] =", "attrib=self.__arxiv_primary_category, ) if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" )", "Parameters ---------- text : str The new journal_ref value. \"\"\"", "atom_feed def extend_rss(self: BaseExtension, rss_feed: Element) -> Element: \"\"\"Allow the", "import Element from flask import current_app from feedgen.ext.base import BaseEntryExtension,", "feed tree for Atom. Parameters ---------- atom_feed : Element The", "------- rss_feed : Element The feed's root element. \"\"\" return", "\"\"\" return rss_feed def extend_ns(self: BaseExtension) -> Dict[str, str]: \"\"\"", "def primary_category(self, text: str) -> None: \"\"\"Assign the primary_category value", "= None self.__arxiv_affiliation: Optional[str] = None self.__arxiv_journal_ref: Optional[str] = None", "entry: Element) -> None: for media in self.__arxiv_media: group =", "-> None: \"\"\"Add a media item. Parameters ---------- media: Dict[str,", "\"\"\" self.__arxiv_journal_ref = text def doi(self, doi_list: Dict[str, str]) ->", "= etree.SubElement( author, \"{http://arxiv.org/schemas/atom}affiliation\", ) element.text = affiliation self.__add_media(entry=entry) return", "media: Dict[str, str] Dictionary with url and type attributes. \"\"\"", "if self.__arxiv_doi: for doi in self.__arxiv_doi: doi_element = etree.SubElement( entry,", "---------- atom_feed : Element The feed's root element. Returns -------", "Define the feed's namespaces. Returns ------- namespaces : Dict[str, str]", "author : Author Paper author. \"\"\" self.__arxiv_authors.append(author) def media(self, media:", "entry: if entry_child.tag == \"author\": author = entry_child for author_child", "= False else: description += \", \" name = (", ") if self.__arxiv_journal_ref: journal_ref_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text", "+= \", \" name = ( f\"{author.last_name},\" f\"+{author.initials.replace(' ', '+')}\"", "text: str) -> None: \"\"\"Assign the comment value to this", "media.type}, ) def extend_atom(self, entry: Element) -> Element: \"\"\" Allow", "Element The feed's root element. Returns ------- rss_feed : Element", "the \"arxiv\" namespaces. \"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", } class", "etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}journal_ref\" ) journal_ref_element.text = self.__arxiv_journal_ref if self.__arxiv_doi: for", "media: Media) -> None: \"\"\"Add a media item. Parameters ----------", "current_app.config[\"BASE_SERVER\"] for entry_child in entry: if entry_child.tag == \"description\": description", "text. \"\"\" self.__arxiv_comment = text def primary_category(self, text: str) ->", "doi in self.__arxiv_doi: doi_element = etree.SubElement( entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text", "the extension to modify the entry element for RSS. Parameters", "\"\"\" return { \"arxiv\": \"http://arxiv.org/schemas/atom\", } class ArxivEntryExtension(BaseEntryExtension): \"\"\"Extension of", "entry's author nodes for entry_child in entry: if entry_child.tag ==", "entry, \"{http://arxiv.org/schemas/atom}doi\" ) doi_element.text = doi # Check each of", "def __init__(self: BaseEntryExtension): \"\"\"Initialize the member values to all be", "for RSS. Parameters ---------- entry : Element The FeedEntry to", "entry: if entry_child.tag == \"description\": description = \"<p>Authors: \" first", "the feed's namespaces. Returns ------- namespaces : Dict[str, str] Definitions", "behavior.\"\"\" def extend_atom(self: BaseExtension, atom_feed: Element) -> Element: \"\"\"Allow the" ]
[ "int = None master_cpu_mode: str = None master_disk: int =", "# number of disks to create worker_memory: int = None", "= None private_ssh_key_path: Path = None working_dir: str = consts.WORKING_DIR", "from .base_config import _BaseConfig global_variables = GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig,", "Any from dataclasses import dataclass from test_infra import consts from", "abc import ABC from pathlib import Path from typing import", "= None master_cpu_mode: str = None master_disk: int = None", "_BaseConfig global_variables = GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC): platform: str", "int = None nodes_count: int = None master_cpu_mode: str =", "= None @staticmethod def get_default(key, default=None) -> Any: return getattr(global_variables,", "to create worker_memory: int = None worker_vcpu: int = None", "None worker_disk: int = None worker_disk_count: int = None network_mtu:", "None nodes_count: int = None master_cpu_mode: str = None master_disk:", "network_mtu: int = None @staticmethod def get_default(key, default=None) -> Any:", "int = None network_mtu: int = None @staticmethod def get_default(key,", "# disk size in MB. master_disk_size_gib: str = None #", "int = None workers_count: int = None worker_cpu_mode: str =", "= None # disk size in MB. master_disk_size_gib: str =", "master_memory: int = None master_vcpu: int = None masters_count: int", "str = None is_ipv6: bool = None bootstrap_in_place: bool =", "nodes_count: int = None master_cpu_mode: str = None master_disk: int", "test_infra import consts from test_infra.utils.global_variables import GlobalVariables from .base_config import", "None master_cpu_mode: str = None master_disk: int = None #", "GlobalVariables from .base_config import _BaseConfig global_variables = GlobalVariables() @dataclass class", "None worker_disk_count: int = None network_mtu: int = None @staticmethod", "str = None worker_disk: int = None worker_disk_count: int =", "str = consts.WORKING_DIR master_memory: int = None master_vcpu: int =", "= None # number of disks to create worker_memory: int", "None working_dir: str = consts.WORKING_DIR master_memory: int = None master_vcpu:", "worker_cpu_mode: str = None worker_disk: int = None worker_disk_count: int", "None worker_vcpu: int = None workers_count: int = None worker_cpu_mode:", "from dataclasses import dataclass from test_infra import consts from test_infra.utils.global_variables", "bootstrap_in_place: bool = None private_ssh_key_path: Path = None working_dir: str", "disk size in GB. master_disk_count: int = None # number", "None # number of disks to create worker_memory: int =", "None bootstrap_in_place: bool = None private_ssh_key_path: Path = None working_dir:", "master_vcpu: int = None masters_count: int = None nodes_count: int", "= None workers_count: int = None worker_cpu_mode: str = None", "= None master_disk: int = None # disk size in", "= None masters_count: int = None nodes_count: int = None", "workers_count: int = None worker_cpu_mode: str = None worker_disk: int", "int = None master_vcpu: int = None masters_count: int =", "None @staticmethod def get_default(key, default=None) -> Any: return getattr(global_variables, key)", "from pathlib import Path from typing import Any from dataclasses", "in MB. master_disk_size_gib: str = None # disk size in", "dataclass from test_infra import consts from test_infra.utils.global_variables import GlobalVariables from", "None master_disk: int = None # disk size in MB.", "None worker_cpu_mode: str = None worker_disk: int = None worker_disk_count:", "None masters_count: int = None nodes_count: int = None master_cpu_mode:", "None # disk size in GB. master_disk_count: int = None", "int = None worker_vcpu: int = None workers_count: int =", "platform: str = None is_ipv6: bool = None bootstrap_in_place: bool", "int = None # number of disks to create worker_memory:", "pathlib import Path from typing import Any from dataclasses import", "import Any from dataclasses import dataclass from test_infra import consts", "from test_infra import consts from test_infra.utils.global_variables import GlobalVariables from .base_config", "None network_mtu: int = None @staticmethod def get_default(key, default=None) ->", "disks to create worker_memory: int = None worker_vcpu: int =", "Path from typing import Any from dataclasses import dataclass from", "import consts from test_infra.utils.global_variables import GlobalVariables from .base_config import _BaseConfig", "master_cpu_mode: str = None master_disk: int = None # disk", "<reponame>lranjbar/assisted-test-infra from abc import ABC from pathlib import Path from", "from abc import ABC from pathlib import Path from typing", "= None network_mtu: int = None @staticmethod def get_default(key, default=None)", "test_infra.utils.global_variables import GlobalVariables from .base_config import _BaseConfig global_variables = GlobalVariables()", "private_ssh_key_path: Path = None working_dir: str = consts.WORKING_DIR master_memory: int", "consts.WORKING_DIR master_memory: int = None master_vcpu: int = None masters_count:", "int = None worker_disk_count: int = None network_mtu: int =", "= None nodes_count: int = None master_cpu_mode: str = None", "= None # disk size in GB. master_disk_count: int =", "is_ipv6: bool = None bootstrap_in_place: bool = None private_ssh_key_path: Path", "GB. master_disk_count: int = None # number of disks to", "size in GB. master_disk_count: int = None # number of", "masters_count: int = None nodes_count: int = None master_cpu_mode: str", "import ABC from pathlib import Path from typing import Any", "disk size in MB. master_disk_size_gib: str = None # disk", "import GlobalVariables from .base_config import _BaseConfig global_variables = GlobalVariables() @dataclass", "dataclasses import dataclass from test_infra import consts from test_infra.utils.global_variables import", "worker_disk_count: int = None network_mtu: int = None @staticmethod def", "None private_ssh_key_path: Path = None working_dir: str = consts.WORKING_DIR master_memory:", "= None working_dir: str = consts.WORKING_DIR master_memory: int = None", "= None master_vcpu: int = None masters_count: int = None", "int = None @staticmethod def get_default(key, default=None) -> Any: return", "= None bootstrap_in_place: bool = None private_ssh_key_path: Path = None", "ABC from pathlib import Path from typing import Any from", "class BaseNodeConfig(_BaseConfig, ABC): platform: str = None is_ipv6: bool =", "# disk size in GB. master_disk_count: int = None #", "from test_infra.utils.global_variables import GlobalVariables from .base_config import _BaseConfig global_variables =", "in GB. master_disk_count: int = None # number of disks", "create worker_memory: int = None worker_vcpu: int = None workers_count:", "= GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC): platform: str = None", "BaseNodeConfig(_BaseConfig, ABC): platform: str = None is_ipv6: bool = None", "worker_vcpu: int = None workers_count: int = None worker_cpu_mode: str", "consts from test_infra.utils.global_variables import GlobalVariables from .base_config import _BaseConfig global_variables", "= None is_ipv6: bool = None bootstrap_in_place: bool = None", "of disks to create worker_memory: int = None worker_vcpu: int", "working_dir: str = consts.WORKING_DIR master_memory: int = None master_vcpu: int", "@dataclass class BaseNodeConfig(_BaseConfig, ABC): platform: str = None is_ipv6: bool", ".base_config import _BaseConfig global_variables = GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC):", "worker_memory: int = None worker_vcpu: int = None workers_count: int", "= None worker_vcpu: int = None workers_count: int = None", "= None worker_cpu_mode: str = None worker_disk: int = None", "Path = None working_dir: str = consts.WORKING_DIR master_memory: int =", "master_disk: int = None # disk size in MB. master_disk_size_gib:", "number of disks to create worker_memory: int = None worker_vcpu:", "int = None worker_cpu_mode: str = None worker_disk: int =", "master_disk_size_gib: str = None # disk size in GB. master_disk_count:", "master_disk_count: int = None # number of disks to create", "= None worker_disk_count: int = None network_mtu: int = None", "None workers_count: int = None worker_cpu_mode: str = None worker_disk:", "global_variables = GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC): platform: str =", "import _BaseConfig global_variables = GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC): platform:", "GlobalVariables() @dataclass class BaseNodeConfig(_BaseConfig, ABC): platform: str = None is_ipv6:", "ABC): platform: str = None is_ipv6: bool = None bootstrap_in_place:", "bool = None bootstrap_in_place: bool = None private_ssh_key_path: Path =", "int = None # disk size in MB. master_disk_size_gib: str", "str = None # disk size in GB. master_disk_count: int", "worker_disk: int = None worker_disk_count: int = None network_mtu: int", "import Path from typing import Any from dataclasses import dataclass", "int = None masters_count: int = None nodes_count: int =", "import dataclass from test_infra import consts from test_infra.utils.global_variables import GlobalVariables", "MB. master_disk_size_gib: str = None # disk size in GB.", "typing import Any from dataclasses import dataclass from test_infra import", "None is_ipv6: bool = None bootstrap_in_place: bool = None private_ssh_key_path:", "None # disk size in MB. master_disk_size_gib: str = None", "= None worker_disk: int = None worker_disk_count: int = None", "from typing import Any from dataclasses import dataclass from test_infra", "None master_vcpu: int = None masters_count: int = None nodes_count:", "size in MB. master_disk_size_gib: str = None # disk size", "= consts.WORKING_DIR master_memory: int = None master_vcpu: int = None", "bool = None private_ssh_key_path: Path = None working_dir: str =", "str = None master_disk: int = None # disk size" ]
[ "self.pool: return False del self.pool[hash] return True def size(self): return", "remove(self, hash): if hash not in self.pool: return False del", "in self.pool: self.log.write(\"MemPool.add(%s): already known\" % (hashstr,)) return False if", "tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr, )) return False self.pool[hash]", "the MIT/X11 software license, see the accompanying # file COPYING", "def remove(self, hash): if hash not in self.pool: return False", "logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash", "hashstr = uint256_to_shortstr(hash) if hash in self.pool: self.log.write(\"MemPool.add(%s): already known\"", "accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize", "# Distributed under the MIT/X11 software license, see the accompanying", "tx): tx.calc_sha256() hash = tx.sha256 hashstr = uint256_to_shortstr(hash) if hash", "http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import uint256_to_shortstr class MemPool(object): def", "return False self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr,", "tx self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr, len(self.pool))) return True def", "logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash = tx.sha256 hashstr =", "def add(self, tx): tx.calc_sha256() hash = tx.sha256 hashstr = uint256_to_shortstr(hash)", "= uint256_to_shortstr(hash) if hash in self.pool: self.log.write(\"MemPool.add(%s): already known\" %", "# file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import", "= tx.sha256 hashstr = uint256_to_shortstr(hash) if hash in self.pool: self.log.write(\"MemPool.add(%s):", "MemPool.py # # Distributed under the MIT/X11 software license, see", "# setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self, tx):", "% (hashstr,)) return False if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\"", "if hash in self.pool: self.log.write(\"MemPool.add(%s): already known\" % (hashstr,)) return", "len(self.pool))) return True def remove(self, hash): if hash not in", "under the MIT/X11 software license, see the accompanying # file", "hash): if hash not in self.pool: return False del self.pool[hash]", "from lib.serialize import uint256_to_shortstr class MemPool(object): def __init__(self): self.pool =", "uint256_to_shortstr class MemPool(object): def __init__(self): self.pool = {} # setup", "% (hashstr, )) return False self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz", "poolsz %d\" % (hashstr, len(self.pool))) return True def remove(self, hash):", "uint256_to_shortstr(hash) if hash in self.pool: self.log.write(\"MemPool.add(%s): already known\" % (hashstr,))", "(hashstr,)) return False if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" %", "or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import uint256_to_shortstr class MemPool(object):", "= logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash = tx.sha256 hashstr", "hash = tx.sha256 hashstr = uint256_to_shortstr(hash) if hash in self.pool:", "if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr, )) return", "if hash not in self.pool: return False del self.pool[hash] return", "self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr, len(self.pool))) return True def remove(self,", "def __init__(self): self.pool = {} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger", "lib.serialize import uint256_to_shortstr class MemPool(object): def __init__(self): self.pool = {}", "tx.sha256 hashstr = uint256_to_shortstr(hash) if hash in self.pool: self.log.write(\"MemPool.add(%s): already", "tx.calc_sha256() hash = tx.sha256 hashstr = uint256_to_shortstr(hash) if hash in", "known\" % (hashstr,)) return False if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid", "= {} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def", "# # Distributed under the MIT/X11 software license, see the", "class MemPool(object): def __init__(self): self.pool = {} # setup logging", "__init__(self): self.pool = {} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger =", "invalid TX\" % (hashstr, )) return False self.pool[hash] = tx", "MIT/X11 software license, see the accompanying # file COPYING or", "software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php.", "False self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr, len(self.pool)))", "# MemPool.py # # Distributed under the MIT/X11 software license,", "file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import uint256_to_shortstr", "Distributed under the MIT/X11 software license, see the accompanying #", "COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from lib.serialize import uint256_to_shortstr class", ")) return False self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz %d\" %", "in self.pool: return False del self.pool[hash] return True def size(self):", "license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import", "return True def remove(self, hash): if hash not in self.pool:", "the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging from", "TX\" % (hashstr, )) return False self.pool[hash] = tx self.log.write(\"MemPool.add(%s),", "import logging from lib.serialize import uint256_to_shortstr class MemPool(object): def __init__(self):", "%d\" % (hashstr, len(self.pool))) return True def remove(self, hash): if", "not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr, )) return False", "logging from lib.serialize import uint256_to_shortstr class MemPool(object): def __init__(self): self.pool", "MemPool(object): def __init__(self): self.pool = {} # setup logging logging.basicConfig(level=logging.DEBUG)", "not in self.pool: return False del self.pool[hash] return True def", "self.pool: self.log.write(\"MemPool.add(%s): already known\" % (hashstr,)) return False if not", "import uint256_to_shortstr class MemPool(object): def __init__(self): self.pool = {} #", "(hashstr, )) return False self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz %d\"", "hash in self.pool: self.log.write(\"MemPool.add(%s): already known\" % (hashstr,)) return False", "self.logger = logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash = tx.sha256", "hash not in self.pool: return False del self.pool[hash] return True", "return False if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr,", "= tx self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr, len(self.pool))) return True", "see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import logging", "{} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self,", "True def remove(self, hash): if hash not in self.pool: return", "setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self, tx): tx.calc_sha256()", "% (hashstr, len(self.pool))) return True def remove(self, hash): if hash", "self.pool = {} # setup logging logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__)", "self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr, )) return False self.pool[hash] =", "already known\" % (hashstr,)) return False if not tx.is_valid(): self.log.write(\"MemPool.add(%s):", "False if not tx.is_valid(): self.log.write(\"MemPool.add(%s): invalid TX\" % (hashstr, ))", "(hashstr, len(self.pool))) return True def remove(self, hash): if hash not", "return False del self.pool[hash] return True def size(self): return len(self.pool)", "self.log.write(\"MemPool.add(%s): already known\" % (hashstr,)) return False if not tx.is_valid():", "add(self, tx): tx.calc_sha256() hash = tx.sha256 hashstr = uint256_to_shortstr(hash) if", "logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger(__name__) def add(self, tx): tx.calc_sha256() hash =", "self.pool[hash] = tx self.log.write(\"MemPool.add(%s), poolsz %d\" % (hashstr, len(self.pool))) return" ]
[ "%s %s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination: return '%s %s'%(self.combination, self.rightexpr)", "= '()' return getattr(p, 'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command", "def __init__(self, test, rightvalue, leftvalue=None): self.test = test self.leftvalue =", "test_expressions(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif", "RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION'", "Jun 13, 2019 @author: sarvi ''' from sly import Parser", "p.assignments return cmd @_('redirect', 'redirect redirects') def redirects(self, p): return", "p): return None @_('NEWLINE', 'CMDSEP') def end_command(self, p): return None", "test self.leftvalue = leftvalue self.rightvalue = rightvalue def __repr__(self): if", "value', 'ID assignop') def assignment(self, p): # print('assignment(%s)' % (list(p)))", "test_command(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif", "boolean_combination compound_command', # # 'command_pipe boolean_combination compound_command' # ) #", "(self.option or self.value) class ASTRedirection: __slots__ = ('redirect', 'file') def", "else_commands=None): self.test_commands = test_commands self.then_commands = then_commands self.else_commands = else_commands", "if self.leftexpr: return '%s %s %s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination:", "base_command', 'base_command redirects', 'assignments base_command redirects') def simple_command(self, p): #", "assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable = executable self.assignments = assignments", "end_pipe list_commands', 'pipe_command boolean_combination list_commands') def list_commands(self, p): if getattr(p,", "= ('variable', 'assignop', 'value') def __init__(self, variable, assignop, value=None): self.variable", "end_command', 'compound_command end_command compound_commands' ) def compound_commands(self, p): # print('simple_command(%s)'", "ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p):", "'pipe_command boolean_combination list_commands') def list_commands(self, p): if getattr(p, 'boolean_combination', None):", "'boolean_combination', None): # return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else: #", "self.test_command = test_command self.group = group def __repr__(self): if self.leftexpr:", "'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN compound_commands RPAREN',", "# return p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT", "print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None)) @_('ASSIGN',", "return '\\n'.join(x) class ASTCommand: __slots__ = ('assignments', 'executable', 'arguments', 'redirections',", "('left', BOOL_COMPARISON), ('right', BOOL_NOT), # ('right', END_LINE) ) # Grammar", "class ASTCommand: __slots__ = ('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd') def", "THEN NEWLINE compound_commands ELSE NEWLINE compound_commands FI') def if_command(self, p):", "p.pipe_command) return p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def", "'%s' % (self.rightvalue) class ASTIfCommand: __slots__ = ('test_commands', 'then_commands', 'else_commands')", "return 'if %s; then\\n%s\\nfi' % (self.test_commands, self.then_commands) class BashParser(Parser): #", "# 'command_pipe boolean_combination compound_command' # ) # def compound_command(self, p):", "@_('echo_command', 'exec_command', 'test_command') def base_command(self, p): if len(p)==2: p[1].assignments =", "in self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd else '')).strip() else: return", "# return list(p) @_('ECHO ECHO_STRING') def echo_command(self, p): return ASTCommand(p[0],", "FI', 'IF list_commands THEN compound_commands ELSE compound_commands FI', 'IF list_commands", "# def compound_command(self, p): # if getattr(p, 'boolean_combination', None): #", "# 'subshell', # 'group_command', # 'arith_command' # 'cond_command', # 'arith_for_command'", ") # def compound_command(self, p): # if getattr(p, 'boolean_combination', None):", "self.else_commands) else: return 'if %s; then\\n%s\\nfi' % (self.test_commands, self.then_commands) class", "cmd @_('TIME', 'TIME TIME_OPTP') def time_command(self, p): cmd = ASTCommand(p.TIME)", "in self.arguments]), ' '.join([str(i) for i in self.redirections]), '| %s'%self.pipetocmd", "%s'%(self.test, self.rightvalue) else: return '%s' % (self.rightvalue) class ASTIfCommand: __slots__", "= ( # ('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ,", "compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands ELSE NEWLINE compound_commands", "arguments') def arguments(self, p): return [p.argument] if len(p)==1 else [p.argument]", "@_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p): return", "boolean_combination(self, p): return p[0] @_('value boolean_comparison value %prec BOOL_COMPARISON', 'OPTION", "= option self.value = value def __repr__(self): return '%s=%s'%(self.option, self.value)", "RBRACK', 'LDBRACK test_expressions RDBRACK') def test_command(self, p): if getattr(p, 'BOOL_NOT',", "p): # print('value(%s)' % (list(p))) return p[0] @_('assignment', 'assignment assignments')", "cmd.redirections = p.redirects if getattr(p, 'assignments', None): cmd.assignments = p.assignments", "cmd.arguments = [p.TIME_OPTP] return cmd @_('simple_command', 'simple_command PIPE pipe_commands') def", "for i in self] if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return", "@author: sarvi ''' from sly import Parser from .lexer import", "return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands) # @_(", "# ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative operators ('left',", "return cmd @_('TIME', 'TIME TIME_OPTP') def time_command(self, p): cmd =", "@_('value', 'WORD') def arg_value(self, p): # print('value(%s)' % (list(p))) return", "RPAREN', ) def group_command(self, p): if getattr(p, 'LBRACE', None): p.compound_commands.grouping", "NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT), # ('right', END_LINE)", "def time_command(self, p): cmd = ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None):", "self.redirections = redirections or list() self.pipetocmd = pipetocmd def __repr__(self):", "cmd @_('redirect', 'redirect redirects') def redirects(self, p): return [p.redirect] if", "__repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value or '') class ASTArgument: __slots__", "p.assignop, getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p): return", "def redirects(self, p): return [p.redirect] if len(p)==1 else [p.redirect] +", "p[0] @_('value boolean_comparison value %prec BOOL_COMPARISON', 'OPTION value') def test_expression(self,", "('leftexpr', 'combination', 'rightexpr', 'test_command', 'group') def __init__(self, combination, rightexpr, leftexpr=None,", "'arguments', None), getattr(p, 'redirects', None)) @_('argument', 'argument arguments') def arguments(self,", "# 'test_command boolean_combination compound_command', # # 'command_pipe boolean_combination compound_command' #", "value(self, p): # print('value(%s)' % (list(p))) return p[0] if __name__", "LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right',", "if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination',", "# 'if_command', # 'subshell', # 'group_command', # 'arith_command' # 'cond_command',", "command, grouping=None): self.append(command) self.grouping = grouping def __repr__(self): x=[str(i) for", "if len(p)==2: p[1].assignments = p.assignments.assignments return p[1] else: return p[0]", "p.redirects if getattr(p, 'assignments', None): cmd.assignments = p.assignments return cmd", "def if_command(self, p): if getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0,", "def __repr__(self): return '%s=%s'%(self.option, self.value) if self.option and self.value else", "elif self.test_command: return '[ %s ]'%(self.rightexpr) elif self.group: return '(", "'[ %s ]'%(self.rightexpr) elif self.group: return '( %s )'%(self.rightexpr) else:", "%s %s %s %s' % (' '.join([str(i) for i in", "def test_expression(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression)", "None): return ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p, 'OPTION', None): return", "pipetocmd def __repr__(self): if self.executable: return ('%s %s %s %s", "p.simple_command.pipetocmd = p.pipe_commands return p.simple_command @_('assignments', 'base_command', 'assignments base_command', 'base_command", "(required) debugfile = 'parser.out' tokens = BashLexer.tokens precedence = (", "redirect(self, p): # print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD',", "__repr__(self): return '%s%s'%(self.redirect, self.file) if self.file else '%s'%(self.redirect) class ASTTestCombination:", "redirects') def simple_command(self, p): # print('simple_command(%s)' % (list(p))) cmd =", "'ASSIGN') def boolean_comparison(self, p): return p[0] # @_( # 'for_command',", "while True: try: text = input('Command:>') result = parser.parse(lexer.tokenize(text)) print(result)", "rightexpr, leftexpr=None, test_command=False, group=False): self.combination = combination self.rightexpr = rightexpr", "getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN',", "arguments(self, p): return [p.argument] if len(p)==1 else [p.argument] + p.arguments", "def assignop(self, p): return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING',", "getattr(p, 'LPAREN', None): p.compound_commands.grouping = '()' return getattr(p, 'compound_commands', None)", "self.then_commands) class BashParser(Parser): # Get the token list from the", "= rightexpr self.leftexpr = leftexpr self.test_command = test_command self.group =", "ASTIfCommand: __slots__ = ('test_commands', 'then_commands', 'else_commands') def __init__(self, test_commands, then_commands,", "print('simple_command(%s)' % (list(p))) cmd = p.base_command if getattr(p, 'base_command', None)", "% (p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command end_command compound_commands'", "BOOL_EQ, BOOL_NEQ), # Nonassociative operators ('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP,", "@_('assignment', 'assignment assignments') def assignments(self, p): return [p.assignment] if len(p)", "('right', END_LINE) ) # Grammar rules and actions @_('compound_commands') def", "('test_commands', 'then_commands', 'else_commands') def __init__(self, test_commands, then_commands, else_commands=None): self.test_commands =", "self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands) else:", "ASTCommand() if getattr(p, 'redirects', None): cmd.redirections = p.redirects if getattr(p,", "def end_command(self, p): return None @_('IF list_commands THEN compound_commands FI',", "# print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command',", "'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination test_expressions", "test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION' ) def", "p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS',", "'arith_for_command' # ) # def shell_command(self, p): # print('assignments(%s)' %", "@_('IF list_commands THEN compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands", "('right', BOOL_NOT), # ('right', END_LINE) ) # Grammar rules and", "Grammar rules and actions @_('compound_commands') def program(self, p): print('program(%s)' %", "p): return p[0] @_( 'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE compound_commands", "@_('LET ID assignop value', 'ID assignop value', 'ID assignop') def", "% (self.test_commands, self.then_commands, self.else_commands) else: return 'if %s; then\\n%s\\nfi' %", "None, getattr(p, 'arguments', None), getattr(p, 'redirects', None)) @_('argument', 'argument arguments')", "self.assignments = assignments or list() self.arguments = arguments or list()", "ASTTestCombination(None, p.test_expressions, group=True) else: return p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self,", "the lexer (required) debugfile = 'parser.out' tokens = BashLexer.tokens precedence", "'command_pipe', # # 'test_command boolean_combination compound_command', # # 'command_pipe boolean_combination", "% (list(p))) # return list(p) @_('ECHO ECHO_STRING') def echo_command(self, p):", "# def shell_command(self, p): # print('assignments(%s)' % (list(p))) # return", "@_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK') def test_command(self, p): if", "return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else: # return p.test_command @_('time_command", "self.rightvalue = rightvalue def __repr__(self): if self.test: return '%s %s", "self.test_commands = test_commands self.then_commands = then_commands self.else_commands = else_commands def", "'assignments base_command redirects') def simple_command(self, p): # print('simple_command(%s)' % (list(p)))", "redirect, file): self.redirect = redirect self.file = file def __repr__(self):", "= ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME', 'TIME TIME_OPTP') def time_command(self,", "'%s'%(self.rightexpr) class ASTTestCondition: __slots__ = ('leftvalue', 'test', 'rightvalue') def __init__(self,", "test, rightvalue, leftvalue=None): self.test = test self.leftvalue = leftvalue self.rightvalue", "# print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value',", "% (list(p))) return ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value', None)) @_('value',", "getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe', None):", "ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command) return", "''' from sly import Parser from .lexer import BashLexer class", "== '__main__': lexer = BashLexer() parser = BashParser() while True:", "@_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p): return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED',", "print('simple_command(%s)' % (list(p))) if getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return", "p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT',", "FI', 'IF list_commands THEN NEWLINE compound_commands FI', 'IF list_commands THEN", "pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self, p): # print('simple_command(%s)' %", "ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe', None): return ASTTestCombination(None, p.command_pipe) else:", "operators ('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left',", "(list(p))) return ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value', None)) @_('value', 'WORD')", "p.list_commands.insert(0, p.pipe_command) return p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND')", "else: # return p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands',", "__init__(self, executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable = executable self.assignments", "p): # print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p, 'value',", "compound_commands RBRACE', 'LPAREN compound_commands RPAREN', ) def group_command(self, p): if", "'assignment assignments') def assignments(self, p): return [p.assignment] if len(p) ==", "% (list(p))) return p[0] if __name__ == '__main__': lexer =", "boolean_combination test_expressions %prec BOOL_COMBINATION' ) def test_expressions(self, p): if getattr(p,", "__name__ == '__main__': lexer = BashLexer() parser = BashParser() while", "BashLexer class ASTCommands(list): __slots__ = ('grouping') def __init__(self, command, grouping=None):", "'WORD arguments') def exec_command(self, p): return ASTCommand(p[0], None, getattr(p, 'arguments',", "'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self, p): #", "p.redirects @_('REDIRECT', 'REDIRECT WORD') def redirect(self, p): # print('assignment(%s)' %", "%s ]'%(self.rightexpr) elif self.group: return '( %s )'%(self.rightexpr) else: return", "else (self.option or self.value) class ASTRedirection: __slots__ = ('redirect', 'file')", "getattr(p, 'boolean_combination', None): # return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else:", "'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self, p): #", "x=[str(i) for i in self] if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1])", "list_commands', 'pipe_command boolean_combination list_commands') def list_commands(self, p): if getattr(p, 'boolean_combination',", "@_('redirect', 'redirect redirects') def redirects(self, p): return [p.redirect] if len(p)==1", "'%s %s'%(self.combination, self.rightexpr) elif self.test_command: return '[ %s ]'%(self.rightexpr) elif", "__repr__(self): if self.test: return '%s %s %s'%(self.leftvalue, self.test, self.rightvalue) if", "# 'case_command', # 'WHILE compound_list DO compound_list DONE', # 'UNTIL", "%s %s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue else '%s %s'%(self.test, self.rightvalue)", "'TIME TIME_OPTP') def time_command(self, p): cmd = ASTCommand(p.TIME) if getattr(p,", "def shell_command(self, p): # print('assignments(%s)' % (list(p))) # return list(p)", "p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self,", "redirects', 'assignments base_command redirects') def simple_command(self, p): # print('simple_command(%s)' %", "2019 @author: sarvi ''' from sly import Parser from .lexer", "THEN NEWLINE compound_commands FI', 'IF list_commands THEN compound_commands ELSE compound_commands", "test_expressions RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec", "'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands return p.simple_command @_('assignments', 'base_command', 'assignments", "' '.join([str(i) for i in self.arguments]), ' '.join([str(i) for i", "@_('WORD', 'WORD arguments') def exec_command(self, p): return ASTCommand(p[0], None, getattr(p,", "'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self, p): # print('value(%s)' %", "FI') def if_command(self, p): if getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands,", "p.list_commands, p.pipe_command) elif getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command) return p.list_commands", "% (list(p))) return p[0] @_('assignment', 'assignment assignments') def assignments(self, p):", "'OPTION', 'arg_value') def argument(self, p): # print('assignment(%s)' % (list(p))) return", "__init__(self, test, rightvalue, leftvalue=None): self.test = test self.leftvalue = leftvalue", "ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True)", "BOOL_NEQ), # Nonassociative operators ('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE),", "'redirections', 'pipetocmd') def __init__(self, executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable", "def __init__(self, test_commands, then_commands, else_commands=None): self.test_commands = test_commands self.then_commands =", "' '.join([str(i) for i in self.assignments]) class ASTAssignment: __slots__ =", "1 else [p.assignment] + p.assignments @_('LET ID assignop value', 'ID", "[p.argument] + p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value') def argument(self, p):", "self.variable = variable self.assignop = assignop self.value = value def", "return cmd @_('simple_command', 'simple_command PIPE pipe_commands') def pipe_commands(self, p): #", "return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self, p): return None", "ASTAssignment: __slots__ = ('variable', 'assignop', 'value') def __init__(self, variable, assignop,", "self.then_commands = then_commands self.else_commands = else_commands def __repr__(self): if self.else_commands:", "== 1 else [p.assignment] + p.assignments @_('LET ID assignop value',", "= combination self.rightexpr = rightexpr self.leftexpr = leftexpr self.test_command =", "(self.rightvalue) class ASTIfCommand: __slots__ = ('test_commands', 'then_commands', 'else_commands') def __init__(self,", "ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command', 'exec_command', 'test_command') def base_command(self, p):", "return p[1] else: return p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions", "print('simple_command(%s)' % (list(p))) cmd = p.pipe_commands if getattr(p, 'BOOL_NOT', None):", ") # Grammar rules and actions @_('compound_commands') def program(self, p):", "(list(p))) if getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands else:", "p): # if getattr(p, 'boolean_combination', None): # return ASTTestCombination(p.boolean_combination, p.test_commands,", "getattr(p, 'arg_value', None)) @_('value', 'WORD') def arg_value(self, p): # print('value(%s)'", "= ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP] return", "else: return p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK') def", "self.value else (self.option or self.value) class ASTRedirection: __slots__ = ('redirect',", "if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe',", "return [p.redirect] if len(p)==1 else [p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT", "# @_( # 'for_command', # 'case_command', # 'WHILE compound_list DO", "None, [p[1]]) @_('WORD', 'WORD arguments') def exec_command(self, p): return ASTCommand(p[0],", "% (list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN')", "x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand: __slots__ = ('assignments', 'executable', 'arguments',", "list() self.redirections = redirections or list() self.pipetocmd = pipetocmd def", "return None @_('NEWLINE', 'CMDSEP') def end_command(self, p): return None @_('IF", "'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p): return p[0] # @_( #", "print('assignments(%s)' % (list(p))) # return list(p) @_('ECHO ECHO_STRING') def echo_command(self,", "getattr(p, 'arguments', None), getattr(p, 'redirects', None)) @_('argument', 'argument arguments') def", "('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative operators ('left', LIST_COMMANDS),", "'simple_command PIPE pipe_commands') def pipe_commands(self, p): # print('simple_command(%s)' % (list(p)))", "[p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT WORD') def redirect(self, p): #", "# 'UNTIL compound_list DO compound_list DONE', # 'select_command', # 'if_command',", "ASTCommand: __slots__ = ('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd') def __init__(self,", "Created on Jun 13, 2019 @author: sarvi ''' from sly", "# Grammar rules and actions @_('compound_commands') def program(self, p): print('program(%s)'", "'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION' )", "= ('option', 'value') def __init__(self, option=None, value=None): self.option = option", "arguments') def exec_command(self, p): return ASTCommand(p[0], None, getattr(p, 'arguments', None),", "None): cmd.arguments = [p.TIME_OPTP] return cmd @_('simple_command', 'simple_command PIPE pipe_commands')", "'pipetocmd') def __init__(self, executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable =", "# 'group_command', # 'arith_command' # 'cond_command', # 'arith_for_command' # )", "self.assignments]) class ASTAssignment: __slots__ = ('variable', 'assignop', 'value') def __init__(self,", "getattr(p, 'assignments', None): cmd.assignments = p.assignments return cmd @_('redirect', 'redirect", "# 'arith_for_command' # ) # def shell_command(self, p): # print('assignments(%s)'", "'then_commands', 'else_commands') def __init__(self, test_commands, then_commands, else_commands=None): self.test_commands = test_commands", "None): return ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression',", "None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination,", "value def __repr__(self): return '%s=%s'%(self.option, self.value) if self.option and self.value", "def argument(self, p): # print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p, 'OPTION',", "ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP] return cmd", "= p.assignments.assignments return p[1] else: return p[0] @_('LBRACK test_expressions RBRACK',", "__slots__ = ('leftexpr', 'combination', 'rightexpr', 'test_command', 'group') def __init__(self, combination,", "p.test_expressions, group=True) elif getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value) else:", "getattr(p, 'redirects', None): cmd.redirections = p.redirects if getattr(p, 'assignments', None):", "DONE', # 'select_command', # 'if_command', # 'subshell', # 'group_command', #", "'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self, p): # print('value(%s)' % (list(p)))", "None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands) #", "cmd = p.pipe_commands if getattr(p, 'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT,", "class ASTCommands(list): __slots__ = ('grouping') def __init__(self, command, grouping=None): self.append(command)", "None)) @_('value', 'WORD') def arg_value(self, p): # print('value(%s)' % (list(p)))", "%s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination: return '%s %s'%(self.combination, self.rightexpr) elif", "cmd = p.base_command if getattr(p, 'base_command', None) else ASTCommand() if", "= ('leftvalue', 'test', 'rightvalue') def __init__(self, test, rightvalue, leftvalue=None): self.test", "ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME', 'TIME TIME_OPTP') def time_command(self, p):", "= leftvalue self.rightvalue = rightvalue def __repr__(self): if self.test: return", "self.leftexpr: return '%s %s %s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination: return", "p): # print('simple_command(%s)' % (list(p))) cmd = p.pipe_commands if getattr(p,", "compound_commands RPAREN', ) def group_command(self, p): if getattr(p, 'LBRACE', None):", "return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe', None): return ASTTestCombination(None, p.command_pipe)", "self.value) if self.option and self.value else (self.option or self.value) class", ") def group_command(self, p): if getattr(p, 'LBRACE', None): p.compound_commands.grouping =", "value=None): self.option = option self.value = value def __repr__(self): return", "'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p): return p[0] @_('QSTRING',", "= value def __repr__(self): return '%s=%s'%(self.option, self.value) if self.option and", "= ('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd') def __init__(self, executable=None, assignments=None,", "end_command(self, p): return None @_('IF list_commands THEN compound_commands FI', 'IF", "'IF list_commands THEN NEWLINE compound_commands ELSE NEWLINE compound_commands FI') def", "self.group = group def __repr__(self): if self.leftexpr: return '%s %s", "p.pipe_commands) return cmd @_('TIME', 'TIME TIME_OPTP') def time_command(self, p): cmd", "if getattr(p, 'LBRACE', None): p.compound_commands.grouping = '{}' elif getattr(p, 'LPAREN',", "'compound_command end_command compound_commands' ) def compound_commands(self, p): # print('simple_command(%s)' %", "'CMDSEP') def end_command(self, p): return None @_('IF list_commands THEN compound_commands", "= assignments or list() self.arguments = arguments or list() self.redirections", "if self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands)", "(list(p))) cmd = p.base_command if getattr(p, 'base_command', None) else ASTCommand()", "return None @_('IF list_commands THEN compound_commands FI', 'IF list_commands THEN", "def __repr__(self): if self.test: return '%s %s %s'%(self.leftvalue, self.test, self.rightvalue)", "argument(self, p): # print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p, 'OPTION', None),", "(list(p))) return p[0] @_('assignment', 'assignment assignments') def assignments(self, p): return", "END_LINE) ) # Grammar rules and actions @_('compound_commands') def program(self,", "@_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p): return p[0] @_('value boolean_comparison value", "compound_commands FI') def if_command(self, p): if getattr(p, 'ELSE', None): return", "else: return '%s'%(self.rightexpr) class ASTTestCondition: __slots__ = ('leftvalue', 'test', 'rightvalue')", "return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def", "(list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def", "= test_commands self.then_commands = then_commands self.else_commands = else_commands def __repr__(self):", "BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative operators ('left', LIST_COMMANDS), ('left', AMPERSAND,", "ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ',", "self.append(command) self.grouping = grouping def __repr__(self): x=[str(i) for i in", "'%s %s %s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination: return '%s %s'%(self.combination,", "return p.simple_command @_('assignments', 'base_command', 'assignments base_command', 'base_command redirects', 'assignments base_command", "None): p.compound_commands.grouping = '{}' elif getattr(p, 'LPAREN', None): p.compound_commands.grouping =", "compound_list DONE', # 'select_command', # 'if_command', # 'subshell', # 'group_command',", "variable, assignop, value=None): self.variable = variable self.assignop = assignop self.value", "list_commands THEN NEWLINE compound_commands ELSE NEWLINE compound_commands FI') def if_command(self,", "'BOOL_AND') def boolean_combination(self, p): return p[0] @_('value boolean_comparison value %prec", "__slots__ = ('test_commands', 'then_commands', 'else_commands') def __init__(self, test_commands, then_commands, else_commands=None):", "__init__(self, variable, assignop, value=None): self.variable = variable self.assignop = assignop", "pipe_commands') def pipe_command(self, p): # print('simple_command(%s)' % (list(p))) cmd =", "@_('compound_commands') def program(self, p): print('program(%s)' % (p.compound_commands)) return p.compound_commands @_('compound_command',", "self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd else '')).strip() else: return '", "def __repr__(self): return '%s%s'%(self.redirect, self.file) if self.file else '%s'%(self.redirect) class", "= value def __repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value or '')", "def list_commands(self, p): if getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands,", "CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT), # ('right',", "None): p.list_commands.insert(0, p.pipe_command) return p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP',", "'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME', 'TIME", "elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) else: return", "'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p): return p[0]", "'for_command', # 'case_command', # 'WHILE compound_list DO compound_list DONE', #", "DONE', # 'UNTIL compound_list DO compound_list DONE', # 'select_command', #", "return ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self,", "redirects') def redirects(self, p): return [p.redirect] if len(p)==1 else [p.redirect]", "p.pipe_command) elif getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command) return p.list_commands else:", "'base_command', 'assignments base_command', 'base_command redirects', 'assignments base_command redirects') def simple_command(self,", "value %prec BOOL_COMPARISON', 'OPTION value') def test_expression(self, p): if getattr(p,", "BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION' ) def test_expressions(self, p):", "= BashLexer() parser = BashParser() while True: try: text =", "compound_commands ELSE NEWLINE compound_commands FI') def if_command(self, p): if getattr(p,", "assignment(self, p): # print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p,", "if self.file else '%s'%(self.redirect) class ASTTestCombination: __slots__ = ('leftexpr', 'combination',", "then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands) else: return 'if %s; then\\n%s\\nfi'", "len(p)==2: p[1].assignments = p.assignments.assignments return p[1] else: return p[0] @_('LBRACK", "if self.pipetocmd else '')).strip() else: return ' '.join([str(i) for i", "= BashLexer.tokens precedence = ( # ('nonassoc', BOOL_NOT), # ('nonassoc',", "ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0)", "= [p.TIME_OPTP] return cmd @_('simple_command', 'simple_command PIPE pipe_commands') def pipe_commands(self,", "class ASTTestCondition: __slots__ = ('leftvalue', 'test', 'rightvalue') def __init__(self, test,", "'%s%s'%(self.redirect, self.file) if self.file else '%s'%(self.redirect) class ASTTestCombination: __slots__ =", "ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions,", "self.then_commands, self.else_commands) else: return 'if %s; then\\n%s\\nfi' % (self.test_commands, self.then_commands)", "p.compound_commands.grouping = '()' return getattr(p, 'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS',", "%s; then\\n%s\\nfi' % (self.test_commands, self.then_commands) class BashParser(Parser): # Get the", "getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p, 'list_commands',", "if getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return", "'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination', None): return", "pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self, p):", "# Nonassociative operators ('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE), ('left',", "self.rightvalue) else: return '%s' % (self.rightvalue) class ASTIfCommand: __slots__ =", "assignments(self, p): return [p.assignment] if len(p) == 1 else [p.assignment]", "end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command boolean_combination list_commands') def list_commands(self, p):", "return [p.argument] if len(p)==1 else [p.argument] + p.arguments @_('OPTION ASSIGN',", "self] if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand:", "'command_pipe', None): return ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None, p.test_expressions, test_command=True)", "p[0] @_('assignment', 'assignment assignments') def assignments(self, p): return [p.assignment] if", "self.assignop = assignop self.value = value def __repr__(self): return '%s%s%s'%(self.variable,", "None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands else: return ASTCommands(p.compound_command) @_( 'group_command',", "'pipe_command end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command boolean_combination list_commands') def list_commands(self,", "pipe_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'PIPE', None):", "'assignments', None): cmd.assignments = p.assignments return cmd @_('redirect', 'redirect redirects')", "test_expressions %prec BOOL_COMBINATION' ) def test_expressions(self, p): if getattr(p, 'BOOL_NOT',", "def __init__(self, combination, rightexpr, leftexpr=None, test_command=False, group=False): self.combination = combination", "# ('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), #", "value=None): self.variable = variable self.assignop = assignop self.value = value", "def end_pipe(self, p): return None @_('NEWLINE', 'CMDSEP') def end_command(self, p):", "(list(p))) cmd = p.pipe_commands if getattr(p, 'BOOL_NOT', None): cmd =", "= p.pipe_commands if getattr(p, 'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands)", "('option', 'value') def __init__(self, option=None, value=None): self.option = option self.value", "test_command=False, group=False): self.combination = combination self.rightexpr = rightexpr self.leftexpr =", "leftexpr self.test_command = test_command self.group = group def __repr__(self): if", "actions @_('compound_commands') def program(self, p): print('program(%s)' % (p.compound_commands)) return p.compound_commands", "BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self, p): # print('simple_command(%s)'", "'redirects', None)) @_('argument', 'argument arguments') def arguments(self, p): return [p.argument]", "# # 'command_pipe boolean_combination compound_command' # ) # def compound_command(self,", "(list(p))) # return list(p) @_('ECHO ECHO_STRING') def echo_command(self, p): return", "'group_command', # 'arith_command' # 'cond_command', # 'arith_for_command' # ) #", "'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands)", "def program(self, p): print('program(%s)' % (p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command", "'WORD', None)) @_('echo_command', 'exec_command', 'test_command') def base_command(self, p): if len(p)==2:", "else: return ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command', # 'command_pipe', #", "@_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self, p): return None @_('NEWLINE', 'CMDSEP')", "echo_command(self, p): return ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD arguments') def", "= ('redirect', 'file') def __init__(self, redirect, file): self.redirect = redirect", "getattr(p, 'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME',", "BOOL_COMPARISON', 'OPTION value') def test_expression(self, p): if getattr(p, 'BOOL_NOT', None):", "if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand: __slots__", "test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK') def test_command(self, p): if getattr(p,", "ASTTestCombination: __slots__ = ('leftexpr', 'combination', 'rightexpr', 'test_command', 'group') def __init__(self,", "# @_( #'test_command', # 'command_pipe', # # 'test_command boolean_combination compound_command',", "class ASTTestCombination: __slots__ = ('leftexpr', 'combination', 'rightexpr', 'test_command', 'group') def", "return p[0] @_( 'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE compound_commands RBRACE',", "def boolean_comparison(self, p): return p[0] # @_( # 'for_command', #", "else '%s %s'%(self.test, self.rightvalue) else: return '%s' % (self.rightvalue) class", "'AMPERSAND') def end_pipe(self, p): return None @_('NEWLINE', 'CMDSEP') def end_command(self,", "combination self.rightexpr = rightexpr self.leftexpr = leftexpr self.test_command = test_command", "'%s=%s'%(self.option, self.value) if self.option and self.value else (self.option or self.value)", "exec_command(self, p): return ASTCommand(p[0], None, getattr(p, 'arguments', None), getattr(p, 'redirects',", "= grouping def __repr__(self): x=[str(i) for i in self] if", "def __init__(self, redirect, file): self.redirect = redirect self.file = file", "or list() self.pipetocmd = pipetocmd def __repr__(self): if self.executable: return", "p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command', # 'command_pipe',", "# print('simple_command(%s)' % (list(p))) cmd = p.base_command if getattr(p, 'base_command',", "combination, rightexpr, leftexpr=None, test_command=False, group=False): self.combination = combination self.rightexpr =", "@_( 'group_command', 'list_commands', 'if_command', ) def compound_command(self, p): return p[0]", "THEN compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands FI', 'IF", "'parser.out' tokens = BashLexer.tokens precedence = ( # ('nonassoc', BOOL_NOT),", "# if getattr(p, 'boolean_combination', None): # return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command)", "RBRACE', 'LPAREN compound_commands RPAREN', ) def group_command(self, p): if getattr(p,", "return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1,", "elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p,", "boolean_combination compound_command' # ) # def compound_command(self, p): # if", "def __repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value or '') class ASTArgument:", "p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command end_command compound_commands' ) def compound_commands(self,", "+ p.redirects @_('REDIRECT', 'REDIRECT WORD') def redirect(self, p): # print('assignment(%s)'", "p.assignments.assignments return p[1] else: return p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK", "'subshell', # 'group_command', # 'arith_command' # 'cond_command', # 'arith_for_command' #", "= p.base_command if getattr(p, 'base_command', None) else ASTCommand() if getattr(p,", "]'%(self.rightexpr) elif self.group: return '( %s )'%(self.rightexpr) else: return '%s'%(self.rightexpr)", "self.arguments = arguments or list() self.redirections = redirections or list()", "assignments or list() self.arguments = arguments or list() self.redirections =", "for i in self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd else '')).strip()", "assignop') def assignment(self, p): # print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID,", "file): self.redirect = redirect self.file = file def __repr__(self): return", "p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True)", "__repr__(self): x=[str(i) for i in self] if self.grouping: x.insert(0, self.grouping[0])", "self.leftexpr = leftexpr self.test_command = test_command self.group = group def", "def assignment(self, p): # print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID, p.assignop,", "p): return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE')", "# print('simple_command(%s)' % (list(p))) if getattr(p, 'PIPE', None): p.simple_command.pipetocmd =", "or self.value) class ASTRedirection: __slots__ = ('redirect', 'file') def __init__(self,", "'%s%s%s'%(self.variable, self.assignop, self.value or '') class ASTArgument: __slots__ = ('option',", "'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION' ) def test_expressions(self, p): if", "list() self.pipetocmd = pipetocmd def __repr__(self): if self.executable: return ('%s", "value') def test_expression(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT,", "None): p.simple_command.pipetocmd = p.pipe_commands return p.simple_command @_('assignments', 'base_command', 'assignments base_command',", "p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p): return p[0] @_('value boolean_comparison", "assignop, value=None): self.variable = variable self.assignop = assignop self.value =", "'arith_command' # 'cond_command', # 'arith_for_command' # ) # def shell_command(self,", "p): # print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p, 'OPTION', None), getattr(p,", "self.redirect = redirect self.file = file def __repr__(self): return '%s%s'%(self.redirect,", "# 'command_pipe', # # 'test_command boolean_combination compound_command', # # 'command_pipe", "if getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands else: return", "@_( #'test_command', # 'command_pipe', # # 'test_command boolean_combination compound_command', #", "'test_command boolean_combination compound_command', # # 'command_pipe boolean_combination compound_command' # )", "def base_command(self, p): if len(p)==2: p[1].assignments = p.assignments.assignments return p[1]", "elif getattr(p, 'command_pipe', None): return ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None,", "= leftexpr self.test_command = test_command self.group = group def __repr__(self):", "= redirections or list() self.pipetocmd = pipetocmd def __repr__(self): if", "'()' return getattr(p, 'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe',", "p): return ASTCommand(p[0], None, getattr(p, 'arguments', None), getattr(p, 'redirects', None))", "def redirect(self, p): # print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT, getattr(p,", "redirect self.file = file def __repr__(self): return '%s%s'%(self.redirect, self.file) if", "option=None, value=None): self.option = option self.value = value def __repr__(self):", "__slots__ = ('leftvalue', 'test', 'rightvalue') def __init__(self, test, rightvalue, leftvalue=None):", "then_commands self.else_commands = else_commands def __repr__(self): if self.else_commands: return 'if", "x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand: __slots__ = ('assignments',", "BashLexer.tokens precedence = ( # ('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS,", "simple_command(self, p): # print('simple_command(%s)' % (list(p))) cmd = p.base_command if", "the token list from the lexer (required) debugfile = 'parser.out'", "BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative operators", "'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self, p): # print('simple_command(%s)' % (list(p)))", "rightvalue def __repr__(self): if self.test: return '%s %s %s'%(self.leftvalue, self.test,", "p.test_expressions) elif getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif", "self.executable = executable self.assignments = assignments or list() self.arguments =", "leftvalue self.rightvalue = rightvalue def __repr__(self): if self.test: return '%s", "__repr__(self): if self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands,", "__init__(self, combination, rightexpr, leftexpr=None, test_command=False, group=False): self.combination = combination self.rightexpr", "= rightvalue def __repr__(self): if self.test: return '%s %s %s'%(self.leftvalue,", ") def compound_command(self, p): return p[0] @_( 'LBRACE NEWLINE compound_commands", "compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands FI', 'IF list_commands", "i in self.assignments]) class ASTAssignment: __slots__ = ('variable', 'assignop', 'value')", "NEWLINE compound_commands FI') def if_command(self, p): if getattr(p, 'ELSE', None):", "getattr(p, 'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe", "try: text = input('Command:>') result = parser.parse(lexer.tokenize(text)) print(result) except EOFError:", "= ('grouping') def __init__(self, command, grouping=None): self.append(command) self.grouping = grouping", "'value') def __init__(self, variable, assignop, value=None): self.variable = variable self.assignop", "else_commands def __repr__(self): if self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi' %", "then_commands, else_commands=None): self.test_commands = test_commands self.then_commands = then_commands self.else_commands =", "13, 2019 @author: sarvi ''' from sly import Parser from", "self.value = value def __repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value or", "self.file else '%s'%(self.redirect) class ASTTestCombination: __slots__ = ('leftexpr', 'combination', 'rightexpr',", "= BashParser() while True: try: text = input('Command:>') result =", "from .lexer import BashLexer class ASTCommands(list): __slots__ = ('grouping') def", "('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd') def __init__(self, executable=None, assignments=None, arguments=None,", "= else_commands def __repr__(self): if self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi'", ") def test_expressions(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT,", "# Get the token list from the lexer (required) debugfile", "'assignments base_command', 'base_command redirects', 'assignments base_command redirects') def simple_command(self, p):", "program(self, p): print('program(%s)' % (p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command end_command',", "p.command_pipe) elif getattr(p, 'command_pipe', None): return ASTTestCombination(None, p.command_pipe) else: return", "if getattr(p, 'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands return p.simple_command @_('assignments',", "'LPAREN', None): p.compound_commands.grouping = '()' return getattr(p, 'compound_commands', None) @_('pipe_command", "value', 'ID assignop value', 'ID assignop') def assignment(self, p): #", "def simple_command(self, p): # print('simple_command(%s)' % (list(p))) cmd = p.base_command", "(' '.join([str(i) for i in self.assignments]), self.executable, ' '.join([str(i) for", "BashParser(Parser): # Get the token list from the lexer (required)", "rules and actions @_('compound_commands') def program(self, p): print('program(%s)' % (p.compound_commands))", "' '.join([str(i) for i in self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd", "None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command", "ELSE NEWLINE compound_commands FI') def if_command(self, p): if getattr(p, 'ELSE',", "else: return '%s' % (self.rightvalue) class ASTIfCommand: __slots__ = ('test_commands',", "= p.pipe_commands return p.simple_command @_('assignments', 'base_command', 'assignments base_command', 'base_command redirects',", "executable self.assignments = assignments or list() self.arguments = arguments or", "test_expressions RDBRACK') def test_command(self, p): if getattr(p, 'BOOL_NOT', None): return", "p): if len(p)==2: p[1].assignments = p.assignments.assignments return p[1] else: return", "def __repr__(self): if self.leftexpr: return '%s %s %s'%(self.leftexpr, self.combination, self.rightexpr)", "ASTRedirection: __slots__ = ('redirect', 'file') def __init__(self, redirect, file): self.redirect", "elif getattr(p, 'LPAREN', None): p.compound_commands.grouping = '()' return getattr(p, 'compound_commands',", "compound_list DO compound_list DONE', # 'select_command', # 'if_command', # 'subshell',", "return ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ',", "p.compound_commands else: return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command', ) def", "compound_commands ELSE compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands ELSE", "compound_commands' ) def compound_commands(self, p): # print('simple_command(%s)' % (list(p))) if", "elif getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p,", "ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def", "@_('argument', 'argument arguments') def arguments(self, p): return [p.argument] if len(p)==1", "debugfile = 'parser.out' tokens = BashLexer.tokens precedence = ( #", "NEWLINE compound_commands FI', 'IF list_commands THEN compound_commands ELSE compound_commands FI',", "% (list(p))) cmd = p.pipe_commands if getattr(p, 'BOOL_NOT', None): cmd", "(list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command', 'exec_command', 'test_command') def", "test_expression(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif", "__slots__ = ('grouping') def __init__(self, command, grouping=None): self.append(command) self.grouping =", "= test_command self.group = group def __repr__(self): if self.leftexpr: return", "self.option = option self.value = value def __repr__(self): return '%s=%s'%(self.option,", "('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT), # ('right', END_LINE) )", "ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions %prec", "self.combination: return '%s %s'%(self.combination, self.rightexpr) elif self.test_command: return '[ %s", "base_command redirects') def simple_command(self, p): # print('simple_command(%s)' % (list(p))) cmd", "'OPTION', None), getattr(p, 'arg_value', None)) @_('value', 'WORD') def arg_value(self, p):", "return p[0] if __name__ == '__main__': lexer = BashLexer() parser", "LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command boolean_combination list_commands') def", "self.test_command: return '[ %s ]'%(self.rightexpr) elif self.group: return '( %s", "None): p.compound_commands.grouping = '()' return getattr(p, 'compound_commands', None) @_('pipe_command %prec", "leftexpr=None, test_command=False, group=False): self.combination = combination self.rightexpr = rightexpr self.leftexpr", "return [p.assignment] if len(p) == 1 else [p.assignment] + p.assignments", "return '%s %s %s'%(self.leftexpr, self.combination, self.rightexpr) elif self.combination: return '%s", "test_command self.group = group def __repr__(self): if self.leftexpr: return '%s", "# ('right', END_LINE) ) # Grammar rules and actions @_('compound_commands')", "p.compound_commands) # @_( #'test_command', # 'command_pipe', # # 'test_command boolean_combination", "def assignments(self, p): return [p.assignment] if len(p) == 1 else", "[p.assignment] if len(p) == 1 else [p.assignment] + p.assignments @_('LET", "return p[0] @_('assignment', 'assignment assignments') def assignments(self, p): return [p.assignment]", "'VAR_SUBST', 'VARIABLE') def value(self, p): # print('value(%s)' % (list(p))) return", "return getattr(p, 'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command", "(p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command end_command compound_commands' )", "getattr(p, 'WORD', None)) @_('echo_command', 'exec_command', 'test_command') def base_command(self, p): if", "return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN')", "'ID assignop') def assignment(self, p): # print('assignment(%s)' % (list(p))) return", "'redirects', None): cmd.redirections = p.redirects if getattr(p, 'assignments', None): cmd.assignments", "assignop value', 'ID assignop') def assignment(self, p): # print('assignment(%s)' %", "'compound_commands', None) @_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe list_commands',", "[p.argument] if len(p)==1 else [p.argument] + p.arguments @_('OPTION ASSIGN', 'OPTION',", "return ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN", "# ) # def compound_command(self, p): # if getattr(p, 'boolean_combination',", "'OPTION value') def test_expression(self, p): if getattr(p, 'BOOL_NOT', None): return", "# print('simple_command(%s)' % (list(p))) cmd = p.pipe_commands if getattr(p, 'BOOL_NOT',", "'UNTIL compound_list DO compound_list DONE', # 'select_command', # 'if_command', #", "grouping def __repr__(self): x=[str(i) for i in self] if self.grouping:", "'LBRACE compound_commands RBRACE', 'LPAREN compound_commands RPAREN', ) def group_command(self, p):", "[p.TIME_OPTP] return cmd @_('simple_command', 'simple_command PIPE pipe_commands') def pipe_commands(self, p):", "self.option and self.value else (self.option or self.value) class ASTRedirection: __slots__", "'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p): return p[0] #", "@_( # 'for_command', # 'case_command', # 'WHILE compound_list DO compound_list", "self.grouping = grouping def __repr__(self): x=[str(i) for i in self]", "p.pipe_commands return p.simple_command @_('assignments', 'base_command', 'assignments base_command', 'base_command redirects', 'assignments", "tokens = BashLexer.tokens precedence = ( # ('nonassoc', BOOL_NOT), #", "# else: # return p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands',", "'rightexpr', 'test_command', 'group') def __init__(self, combination, rightexpr, leftexpr=None, test_command=False, group=False):", "getattr(p, 'LBRACE', None): p.compound_commands.grouping = '{}' elif getattr(p, 'LPAREN', None):", "in self.assignments]), self.executable, ' '.join([str(i) for i in self.arguments]), '", "'LDBRACK test_expressions RDBRACK') def test_command(self, p): if getattr(p, 'BOOL_NOT', None):", "return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None,", "getattr(p, 'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP] return cmd @_('simple_command', 'simple_command", "'VARIABLE') def value(self, p): # print('value(%s)' % (list(p))) return p[0]", "@_('ECHO ECHO_STRING') def echo_command(self, p): return ASTCommand(p[0], None, [p[1]]) @_('WORD',", "p): return ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD arguments') def exec_command(self,", "elif getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison,", "self.file) if self.file else '%s'%(self.redirect) class ASTTestCombination: __slots__ = ('leftexpr',", "# return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else: # return p.test_command", "len(p) == 1 else [p.assignment] + p.assignments @_('LET ID assignop", "%s' % (' '.join([str(i) for i in self.assignments]), self.executable, '", "BOOL_NOT), # ('right', END_LINE) ) # Grammar rules and actions", "return p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command end_command compound_commands' ) def", "'compound_command end_command', 'compound_command end_command compound_commands' ) def compound_commands(self, p): #", "None) else ASTCommand() if getattr(p, 'redirects', None): cmd.redirections = p.redirects", "group=True) else: return p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p): return", "'( %s )'%(self.rightexpr) else: return '%s'%(self.rightexpr) class ASTTestCondition: __slots__ =", "p): # print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None))", "p.compound_command) return p.compound_commands else: return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command',", "ECHO_STRING') def echo_command(self, p): return ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD", "NEWLINE compound_commands ELSE NEWLINE compound_commands FI') def if_command(self, p): if", "def echo_command(self, p): return ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD arguments')", "'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP] return cmd @_('simple_command', 'simple_command PIPE", "'case_command', # 'WHILE compound_list DO compound_list DONE', # 'UNTIL compound_list", "Get the token list from the lexer (required) debugfile =", "'IF list_commands THEN NEWLINE compound_commands FI', 'IF list_commands THEN compound_commands", "# print('assignments(%s)' % (list(p))) # return list(p) @_('ECHO ECHO_STRING') def", "% (self.rightvalue) class ASTIfCommand: __slots__ = ('test_commands', 'then_commands', 'else_commands') def", "self.executable, ' '.join([str(i) for i in self.arguments]), ' '.join([str(i) for", "= p.redirects if getattr(p, 'assignments', None): cmd.assignments = p.assignments return", "return ('%s %s %s %s %s' % (' '.join([str(i) for", "'cond_command', # 'arith_for_command' # ) # def shell_command(self, p): #", "def arguments(self, p): return [p.argument] if len(p)==1 else [p.argument] +", "@_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self, p):", "assignments') def assignments(self, p): return [p.assignment] if len(p) == 1", "print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command', 'exec_command',", "in self] if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class", "%s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue else '%s %s'%(self.test, self.rightvalue) else:", "else '%s'%(self.redirect) class ASTTestCombination: __slots__ = ('leftexpr', 'combination', 'rightexpr', 'test_command',", "''' Created on Jun 13, 2019 @author: sarvi ''' from", "i in self] if self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x)", "'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p, 'OPTION', None):", "ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self, p): return None @_('NEWLINE',", "i in self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd else '')).strip() else:", "p): # print('simple_command(%s)' % (list(p))) cmd = p.base_command if getattr(p,", "# # 'test_command boolean_combination compound_command', # # 'command_pipe boolean_combination compound_command'", "= test self.leftvalue = leftvalue self.rightvalue = rightvalue def __repr__(self):", "p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p,", "text = input('Command:>') result = parser.parse(lexer.tokenize(text)) print(result) except EOFError: break", "p.command_pipe) else: return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN',", "[p[1]]) @_('WORD', 'WORD arguments') def exec_command(self, p): return ASTCommand(p[0], None,", "p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p,", "self.grouping: x.insert(0, self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand: __slots__ =", "in self.assignments]) class ASTAssignment: __slots__ = ('variable', 'assignop', 'value') def", "p.test_expressions0) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) else:", "compound_command', # # 'command_pipe boolean_combination compound_command' # ) # def", "__slots__ = ('variable', 'assignop', 'value') def __init__(self, variable, assignop, value=None):", "return '%s'%(self.rightexpr) class ASTTestCondition: __slots__ = ('leftvalue', 'test', 'rightvalue') def", "p): return [p.redirect] if len(p)==1 else [p.redirect] + p.redirects @_('REDIRECT',", "print('value(%s)' % (list(p))) return p[0] @_('assignment', 'assignment assignments') def assignments(self,", "if len(p) == 1 else [p.assignment] + p.assignments @_('LET ID", "rightexpr self.leftexpr = leftexpr self.test_command = test_command self.group = group", "getattr(p, 'command_pipe', None): return ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None, p.test_expressions,", "class ASTRedirection: __slots__ = ('redirect', 'file') def __init__(self, redirect, file):", "then\\n%s\\nfi' % (self.test_commands, self.then_commands) class BashParser(Parser): # Get the token", "'if %s; then\\n%s\\nfi' % (self.test_commands, self.then_commands) class BashParser(Parser): # Get", "None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None,", "'test_command', 'group') def __init__(self, combination, rightexpr, leftexpr=None, test_command=False, group=False): self.combination", "%s %s %s' % (' '.join([str(i) for i in self.assignments]),", "'%s %s %s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue else '%s %s'%(self.test,", "'file') def __init__(self, redirect, file): self.redirect = redirect self.file =", "(list(p))) if getattr(p, 'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands return p.simple_command", "p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'PIPE', None): p.simple_command.pipetocmd", "THEN compound_commands ELSE compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands", "'WORD') def arg_value(self, p): # print('value(%s)' % (list(p))) return p[0]", "p.assignments @_('LET ID assignop value', 'ID assignop value', 'ID assignop')", "None)) @_('argument', 'argument arguments') def arguments(self, p): return [p.argument] if", "def __repr__(self): if self.else_commands: return 'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands,", "ASSIGN', 'OPTION', 'arg_value') def argument(self, p): # print('assignment(%s)' % (list(p)))", "ID assignop value', 'ID assignop value', 'ID assignop') def assignment(self,", "list_commands THEN NEWLINE compound_commands FI', 'IF list_commands THEN compound_commands ELSE", "compound_command' # ) # def compound_command(self, p): # if getattr(p,", "p[0] # @_( # 'for_command', # 'case_command', # 'WHILE compound_list", "p): return None @_('IF list_commands THEN compound_commands FI', 'IF list_commands", "%s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands) else: return 'if %s;", "PIPE pipe_commands') def pipe_commands(self, p): # print('simple_command(%s)' % (list(p))) if", "group=True) elif getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value) else: return", "return ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD arguments') def exec_command(self, p):", "return p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p): return p[0] @_('value", "self.grouping[0]) x.append(self.grouping[1]) return '\\n'.join(x) class ASTCommand: __slots__ = ('assignments', 'executable',", "'ARITH_ASSIGN') def assignop(self, p): return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP',", "or '') class ASTArgument: __slots__ = ('option', 'value') def __init__(self,", "None): # return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else: # return", "else ASTCommand() if getattr(p, 'redirects', None): cmd.redirections = p.redirects if", "'combination', 'rightexpr', 'test_command', 'group') def __init__(self, combination, rightexpr, leftexpr=None, test_command=False,", "if self.executable: return ('%s %s %s %s %s' % ('", "variable self.assignop = assignop self.value = value def __repr__(self): return", "AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT), #", "%prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command boolean_combination list_commands')", "p[1].assignments = p.assignments.assignments return p[1] else: return p[0] @_('LBRACK test_expressions", "return p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK') def test_command(self,", "else: return p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p): return p[0]", "p.test_expression) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) elif", "return '%s%s%s'%(self.variable, self.assignop, self.value or '') class ASTArgument: __slots__ =", "('%s %s %s %s %s' % (' '.join([str(i) for i", "from the lexer (required) debugfile = 'parser.out' tokens = BashLexer.tokens", "None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME', 'TIME TIME_OPTP')", "assignop self.value = value def __repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value", "return '%s %s'%(self.combination, self.rightexpr) elif self.test_command: return '[ %s ]'%(self.rightexpr)", "def pipe_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'PIPE',", "+ p.assignments @_('LET ID assignop value', 'ID assignop value', 'ID", "self.rightexpr) elif self.combination: return '%s %s'%(self.combination, self.rightexpr) elif self.test_command: return", "TIME_OPTP') def time_command(self, p): cmd = ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP',", "self.value) class ASTRedirection: __slots__ = ('redirect', 'file') def __init__(self, redirect,", "or list() self.arguments = arguments or list() self.redirections = redirections", "Nonassociative operators ('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION),", "__init__(self, option=None, value=None): self.option = option self.value = value def", "return p[0] # @_( # 'for_command', # 'case_command', # 'WHILE", "@_('simple_command', 'simple_command PIPE pipe_commands') def pipe_commands(self, p): # print('simple_command(%s)' %", "boolean_comparison(self, p): return p[0] # @_( # 'for_command', # 'case_command',", "'list_commands', None): p.list_commands.insert(0, p.pipe_command) return p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE',", "else: return 'if %s; then\\n%s\\nfi' % (self.test_commands, self.then_commands) class BashParser(Parser):", "= 'parser.out' tokens = BashLexer.tokens precedence = ( # ('nonassoc',", "p.compound_commands.grouping = '{}' elif getattr(p, 'LPAREN', None): p.compound_commands.grouping = '()'", "i in self.assignments]), self.executable, ' '.join([str(i) for i in self.arguments]),", "print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value', None))", "self.leftvalue = leftvalue self.rightvalue = rightvalue def __repr__(self): if self.test:", "return ' '.join([str(i) for i in self.assignments]) class ASTAssignment: __slots__", "test_commands self.then_commands = then_commands self.else_commands = else_commands def __repr__(self): if", "assignop value', 'ID assignop value', 'ID assignop') def assignment(self, p):", "leftvalue=None): self.test = test self.leftvalue = leftvalue self.rightvalue = rightvalue", "'ID assignop value', 'ID assignop') def assignment(self, p): # print('assignment(%s)'", "return '%s=%s'%(self.option, self.value) if self.option and self.value else (self.option or", "return p.compound_commands else: return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command', )", "None): cmd.redirections = p.redirects if getattr(p, 'assignments', None): cmd.assignments =", "'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN', None): return", "if self.leftvalue else '%s %s'%(self.test, self.rightvalue) else: return '%s' %", "cmd.assignments = p.assignments return cmd @_('redirect', 'redirect redirects') def redirects(self,", "if getattr(p, 'base_command', None) else ASTCommand() if getattr(p, 'redirects', None):", "'__main__': lexer = BashLexer() parser = BashParser() while True: try:", "compound_commands FI', 'IF list_commands THEN compound_commands ELSE compound_commands FI', 'IF", "time_command(self, p): cmd = ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None): cmd.arguments", "if getattr(p, 'redirects', None): cmd.redirections = p.redirects if getattr(p, 'assignments',", "% (self.test_commands, self.then_commands) class BashParser(Parser): # Get the token list", ")'%(self.rightexpr) else: return '%s'%(self.rightexpr) class ASTTestCondition: __slots__ = ('leftvalue', 'test',", "'.join([str(i) for i in self.assignments]) class ASTAssignment: __slots__ = ('variable',", "elif self.group: return '( %s )'%(self.rightexpr) else: return '%s'%(self.rightexpr) class", "class ASTIfCommand: __slots__ = ('test_commands', 'then_commands', 'else_commands') def __init__(self, test_commands,", "end_command compound_commands' ) def compound_commands(self, p): # print('simple_command(%s)' % (list(p)))", "return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command)", "p): if getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else:", "ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value', None)) @_('value', 'WORD') def arg_value(self,", "else: return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command', ) def compound_command(self,", "NEWLINE compound_commands RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN compound_commands RPAREN', )", "return '%s' % (self.rightvalue) class ASTIfCommand: __slots__ = ('test_commands', 'then_commands',", "def test_expressions(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions)", "__repr__(self): return '%s=%s'%(self.option, self.value) if self.option and self.value else (self.option", "('left', LIST_COMMANDS), ('left', AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON),", "BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT), # ('right', END_LINE) ) #", "def test_command(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe)", "getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands,", "'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p): return p[0] # @_(", "__init__(self, test_commands, then_commands, else_commands=None): self.test_commands = test_commands self.then_commands = then_commands", "= redirect self.file = file def __repr__(self): return '%s%s'%(self.redirect, self.file)", "ASTCommands(list): __slots__ = ('grouping') def __init__(self, command, grouping=None): self.append(command) self.grouping", "p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command', #", "cmd = ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP]", ") def compound_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p,", "% (' '.join([str(i) for i in self.assignments]), self.executable, ' '.join([str(i)", "and self.value else (self.option or self.value) class ASTRedirection: __slots__ =", "'WHILE compound_list DO compound_list DONE', # 'UNTIL compound_list DO compound_list", "'select_command', # 'if_command', # 'subshell', # 'group_command', # 'arith_command' #", "def __repr__(self): x=[str(i) for i in self] if self.grouping: x.insert(0,", "'if_command', # 'subshell', # 'group_command', # 'arith_command' # 'cond_command', #", "rightvalue, leftvalue=None): self.test = test self.leftvalue = leftvalue self.rightvalue =", "'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self, p): # print('value(%s)'", "if getattr(p, 'boolean_combination', None): # return ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) #", "self.pipetocmd = pipetocmd def __repr__(self): if self.executable: return ('%s %s", "p.test_commands, p.test_command) # else: # return p.test_command @_('time_command pipe_commands', 'time_command", "sly import Parser from .lexer import BashLexer class ASTCommands(list): __slots__", "= pipetocmd def __repr__(self): if self.executable: return ('%s %s %s", "def __init__(self, option=None, value=None): self.option = option self.value = value", "% (list(p))) return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command', 'exec_command', 'test_command')", "[p.assignment] + p.assignments @_('LET ID assignop value', 'ID assignop value',", "arguments=None, redirections=None, pipetocmd=None): self.executable = executable self.assignments = assignments or", "cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd @_('TIME', 'TIME TIME_OPTP') def", "# 'select_command', # 'if_command', # 'subshell', # 'group_command', # 'arith_command'", "boolean_combination list_commands') def list_commands(self, p): if getattr(p, 'boolean_combination', None): return", "option self.value = value def __repr__(self): return '%s=%s'%(self.option, self.value) if", "p): # print('value(%s)' % (list(p))) return p[0] if __name__ ==", "BOOL_COMPARISON), ('right', BOOL_NOT), # ('right', END_LINE) ) # Grammar rules", "'IF list_commands THEN compound_commands ELSE compound_commands FI', 'IF list_commands THEN", "def __init__(self, command, grouping=None): self.append(command) self.grouping = grouping def __repr__(self):", "ASTTestCondition: __slots__ = ('leftvalue', 'test', 'rightvalue') def __init__(self, test, rightvalue,", "if getattr(p, 'TIME_OPTP', None): cmd.arguments = [p.TIME_OPTP] return cmd @_('simple_command',", "return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command', ) def compound_command(self, p):", "@_('NEWLINE', 'CMDSEP') def end_command(self, p): return None @_('IF list_commands THEN", "self.test = test self.leftvalue = leftvalue self.rightvalue = rightvalue def", "compound_command(self, p): return p[0] @_( 'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE", "None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe', None): return ASTTestCombination(None,", "'BOOL_NOT pipe_commands') def pipe_command(self, p): # print('simple_command(%s)' % (list(p))) cmd", "ASTCommand(p[0], None, [p[1]]) @_('WORD', 'WORD arguments') def exec_command(self, p): return", "BashParser() while True: try: text = input('Command:>') result = parser.parse(lexer.tokenize(text))", "'if_command', ) def compound_command(self, p): return p[0] @_( 'LBRACE NEWLINE", "'.join([str(i) for i in self.assignments]), self.executable, ' '.join([str(i) for i", "redirections or list() self.pipetocmd = pipetocmd def __repr__(self): if self.executable:", "p): if getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif", "return '%s%s'%(self.redirect, self.file) if self.file else '%s'%(self.redirect) class ASTTestCombination: __slots__", "DO compound_list DONE', # 'UNTIL compound_list DO compound_list DONE', #", "%s )'%(self.rightexpr) else: return '%s'%(self.rightexpr) class ASTTestCondition: __slots__ = ('leftvalue',", "('leftvalue', 'test', 'rightvalue') def __init__(self, test, rightvalue, leftvalue=None): self.test =", "None): return ASTTestCombination(None, p.test_expressions, group=True) else: return p.test_expression @_('BOOL_OR', 'BOOL_AND')", "return '[ %s ]'%(self.rightexpr) elif self.group: return '( %s )'%(self.rightexpr)", "'exec_command', 'test_command') def base_command(self, p): if len(p)==2: p[1].assignments = p.assignments.assignments", "assignop(self, p): return p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST',", "end_pipe(self, p): return None @_('NEWLINE', 'CMDSEP') def end_command(self, p): return", "None): cmd.assignments = p.assignments return cmd @_('redirect', 'redirect redirects') def", "%s'%(self.combination, self.rightexpr) elif self.test_command: return '[ %s ]'%(self.rightexpr) elif self.group:", "compound_commands RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN compound_commands RPAREN', ) def", "+ p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value') def argument(self, p): #", "FI', 'IF list_commands THEN NEWLINE compound_commands ELSE NEWLINE compound_commands FI')", "def value(self, p): # print('value(%s)' % (list(p))) return p[0] if", "('redirect', 'file') def __init__(self, redirect, file): self.redirect = redirect self.file", "'test_command') def base_command(self, p): if len(p)==2: p[1].assignments = p.assignments.assignments return", "@_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions boolean_combination", "for i in self.arguments]), ' '.join([str(i) for i in self.redirections]),", "= group def __repr__(self): if self.leftexpr: return '%s %s %s'%(self.leftexpr,", "getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN', None):", "p): return [p.argument] if len(p)==1 else [p.argument] + p.arguments @_('OPTION", "'.join([str(i) for i in self.arguments]), ' '.join([str(i) for i in", "ELSE compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands ELSE NEWLINE", "if len(p)==1 else [p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT WORD') def", "@_('value boolean_comparison value %prec BOOL_COMPARISON', 'OPTION value') def test_expression(self, p):", "p.compound_commands.insert(0, p.compound_command) return p.compound_commands else: return ASTCommands(p.compound_command) @_( 'group_command', 'list_commands',", "self.combination = combination self.rightexpr = rightexpr self.leftexpr = leftexpr self.test_command", "'') class ASTArgument: __slots__ = ('option', 'value') def __init__(self, option=None,", "self.leftvalue else '%s %s'%(self.test, self.rightvalue) else: return '%s' % (self.rightvalue)", "getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expressions) elif getattr(p, 'boolean_combination', None):", "# print('assignment(%s)' % (list(p))) return ASTAssignment(p.ID, p.assignop, getattr(p, 'value', None))", "# print('value(%s)' % (list(p))) return p[0] if __name__ == '__main__':", "if self.test: return '%s %s %s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue", "shell_command(self, p): # print('assignments(%s)' % (list(p))) # return list(p) @_('ECHO", "list_commands THEN compound_commands ELSE compound_commands FI', 'IF list_commands THEN NEWLINE", "None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p): return p[0] @_('QSTRING', 'DQSTRING',", "self.else_commands = else_commands def __repr__(self): if self.else_commands: return 'if %s;", "class ASTAssignment: __slots__ = ('variable', 'assignop', 'value') def __init__(self, variable,", "'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands) else: return 'if", "= p.assignments return cmd @_('redirect', 'redirect redirects') def redirects(self, p):", "return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions,", "def __init__(self, variable, assignop, value=None): self.variable = variable self.assignop =", "'executable', 'arguments', 'redirections', 'pipetocmd') def __init__(self, executable=None, assignments=None, arguments=None, redirections=None,", "len(p)==1 else [p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT WORD') def redirect(self,", "# 'WHILE compound_list DO compound_list DONE', # 'UNTIL compound_list DO", "elif self.combination: return '%s %s'%(self.combination, self.rightexpr) elif self.test_command: return '[", "'CMDSEP', 'AMPERSAND') def end_pipe(self, p): return None @_('NEWLINE', 'CMDSEP') def", "self.rightvalue) if self.leftvalue else '%s %s'%(self.test, self.rightvalue) else: return '%s'", "else [p.argument] + p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value') def argument(self,", "return cmd @_('redirect', 'redirect redirects') def redirects(self, p): return [p.redirect]", "p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value') def argument(self, p): # print('assignment(%s)'", "BOOL_COMBINATION' ) def test_expressions(self, p): if getattr(p, 'BOOL_NOT', None): return", "'base_command', None) else ASTCommand() if getattr(p, 'redirects', None): cmd.redirections =", "self.test, self.rightvalue) if self.leftvalue else '%s %s'%(self.test, self.rightvalue) else: return", "% (list(p))) cmd = p.base_command if getattr(p, 'base_command', None) else", "[p.redirect] if len(p)==1 else [p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT WORD')", "'LBRACE', None): p.compound_commands.grouping = '{}' elif getattr(p, 'LPAREN', None): p.compound_commands.grouping", "def compound_command(self, p): # if getattr(p, 'boolean_combination', None): # return", "'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p, 'list_commands', None):", "self.arguments]), ' '.join([str(i) for i in self.redirections]), '| %s'%self.pipetocmd if", "self.group: return '( %s )'%(self.rightexpr) else: return '%s'%(self.rightexpr) class ASTTestCondition:", "return ASTArgument(getattr(p, 'OPTION', None), getattr(p, 'arg_value', None)) @_('value', 'WORD') def", "(list(p))) return p[0] if __name__ == '__main__': lexer = BashLexer()", "@_('compound_command', 'compound_command end_command', 'compound_command end_command compound_commands' ) def compound_commands(self, p):", "if __name__ == '__main__': lexer = BashLexer() parser = BashParser()", "if getattr(p, 'assignments', None): cmd.assignments = p.assignments return cmd @_('redirect',", "print('value(%s)' % (list(p))) return p[0] if __name__ == '__main__': lexer", "None), getattr(p, 'redirects', None)) @_('argument', 'argument arguments') def arguments(self, p):", "= variable self.assignop = assignop self.value = value def __repr__(self):", "%s'%self.pipetocmd if self.pipetocmd else '')).strip() else: return ' '.join([str(i) for", "token list from the lexer (required) debugfile = 'parser.out' tokens", "'LPAREN compound_commands RPAREN', ) def group_command(self, p): if getattr(p, 'LBRACE',", "redirections=None, pipetocmd=None): self.executable = executable self.assignments = assignments or list()", "ASTTestCombination(p.boolean_combination, p.test_commands, p.test_command) # else: # return p.test_command @_('time_command pipe_commands',", "'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0)", "('left', AMPERSAND, CMDSEP, NEWLINE), ('left', BOOL_COMBINATION), ('left', BOOL_COMPARISON), ('right', BOOL_NOT),", "@_('TIME', 'TIME TIME_OPTP') def time_command(self, p): cmd = ASTCommand(p.TIME) if", "p): print('program(%s)' % (p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command", "executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable = executable self.assignments =", "ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1) else: return ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command',", "('variable', 'assignop', 'value') def __init__(self, variable, assignop, value=None): self.variable =", "return p[0] @_('value boolean_comparison value %prec BOOL_COMPARISON', 'OPTION value') def", "pipe_command(self, p): # print('simple_command(%s)' % (list(p))) cmd = p.pipe_commands if", "self.test: return '%s %s %s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue else", "class BashParser(Parser): # Get the token list from the lexer", "getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands else: return ASTCommands(p.compound_command)", "p): # print('assignments(%s)' % (list(p))) # return list(p) @_('ECHO ECHO_STRING')", "list(p) @_('ECHO ECHO_STRING') def echo_command(self, p): return ASTCommand(p[0], None, [p[1]])", "ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command', # 'command_pipe', # # 'test_command", "list_commands') def list_commands(self, p): if getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination,", "lexer = BashLexer() parser = BashParser() while True: try: text", "compound_list DO compound_list DONE', # 'UNTIL compound_list DO compound_list DONE',", "p[0] @_( 'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN", "= arguments or list() self.redirections = redirections or list() self.pipetocmd", "# print('simple_command(%s)' % (list(p))) if getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command)", "getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command) return p.list_commands else: return ASTCommands(p.pipe_command)", "p): return p[0] # @_( # 'for_command', # 'case_command', #", "'%s'%(self.redirect) class ASTTestCombination: __slots__ = ('leftexpr', 'combination', 'rightexpr', 'test_command', 'group')", "None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN', None): return", "def pipe_command(self, p): # print('simple_command(%s)' % (list(p))) cmd = p.pipe_commands", "'rightvalue') def __init__(self, test, rightvalue, leftvalue=None): self.test = test self.leftvalue", "__repr__(self): if self.executable: return ('%s %s %s %s %s' %", "def boolean_combination(self, p): return p[0] @_('value boolean_comparison value %prec BOOL_COMPARISON',", "ASTTestCombination(None, p.command_pipe) else: return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions", "getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1,", "True: try: text = input('Command:>') result = parser.parse(lexer.tokenize(text)) print(result) except", "#'test_command', # 'command_pipe', # # 'test_command boolean_combination compound_command', # #", "precedence = ( # ('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER,", ".lexer import BashLexer class ASTCommands(list): __slots__ = ('grouping') def __init__(self,", "__slots__ = ('redirect', 'file') def __init__(self, redirect, file): self.redirect =", "__init__(self, redirect, file): self.redirect = redirect self.file = file def", "@_('REDIRECT', 'REDIRECT WORD') def redirect(self, p): # print('assignment(%s)' % (list(p)))", "compound_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'compound_commands', None):", "return list(p) @_('ECHO ECHO_STRING') def echo_command(self, p): return ASTCommand(p[0], None,", "else '')).strip() else: return ' '.join([str(i) for i in self.assignments])", "__init__(self, command, grouping=None): self.append(command) self.grouping = grouping def __repr__(self): x=[str(i)", "BashLexer() parser = BashParser() while True: try: text = input('Command:>')", "'REDIRECT WORD') def redirect(self, p): # print('assignment(%s)' % (list(p))) return", "return p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self,", "p): return p[0] @_('value boolean_comparison value %prec BOOL_COMPARISON', 'OPTION value')", "( # ('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ),", "@_('pipe_command %prec LIST_COMMANDS', 'pipe_command end_pipe', 'pipe_command end_pipe list_commands', 'pipe_command boolean_combination", "p.simple_command @_('assignments', 'base_command', 'assignments base_command', 'base_command redirects', 'assignments base_command redirects')", "p.test_command) # else: # return p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT", "p): cmd = ASTCommand(p.TIME) if getattr(p, 'TIME_OPTP', None): cmd.arguments =", "%prec BOOL_NOT', 'test_expressions boolean_combination test_expressions %prec BOOL_COMBINATION' ) def test_expressions(self,", "# ) # def shell_command(self, p): # print('assignments(%s)' % (list(p)))", "@_('assignments', 'base_command', 'assignments base_command', 'base_command redirects', 'assignments base_command redirects') def", "def compound_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'compound_commands',", "getattr(p, 'base_command', None) else ASTCommand() if getattr(p, 'redirects', None): cmd.redirections", "None @_('NEWLINE', 'CMDSEP') def end_command(self, p): return None @_('IF list_commands", "return '%s %s %s'%(self.leftvalue, self.test, self.rightvalue) if self.leftvalue else '%s", "# 'arith_command' # 'cond_command', # 'arith_for_command' # ) # def", "and actions @_('compound_commands') def program(self, p): print('program(%s)' % (p.compound_commands)) return", "'assignop', 'value') def __init__(self, variable, assignop, value=None): self.variable = variable", "self.combination, self.rightexpr) elif self.combination: return '%s %s'%(self.combination, self.rightexpr) elif self.test_command:", "import BashLexer class ASTCommands(list): __slots__ = ('grouping') def __init__(self, command,", "self.file = file def __repr__(self): return '%s%s'%(self.redirect, self.file) if self.file", "print('simple_command(%s)' % (list(p))) if getattr(p, 'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands", "'argument arguments') def arguments(self, p): return [p.argument] if len(p)==1 else", "elif getattr(p, 'list_commands', None): p.list_commands.insert(0, p.pipe_command) return p.list_commands else: return", "'arg_value', None)) @_('value', 'WORD') def arg_value(self, p): # print('value(%s)' %", "grouping=None): self.append(command) self.grouping = grouping def __repr__(self): x=[str(i) for i", "= file def __repr__(self): return '%s%s'%(self.redirect, self.file) if self.file else", "import Parser from .lexer import BashLexer class ASTCommands(list): __slots__ =", "else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self, p): return", "return p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands')", "self.value or '') class ASTArgument: __slots__ = ('option', 'value') def", "'group') def __init__(self, combination, rightexpr, leftexpr=None, test_command=False, group=False): self.combination =", "'.join([str(i) for i in self.redirections]), '| %s'%self.pipetocmd if self.pipetocmd else", "p.base_command if getattr(p, 'base_command', None) else ASTCommand() if getattr(p, 'redirects',", "'arg_value') def argument(self, p): # print('assignment(%s)' % (list(p))) return ASTArgument(getattr(p,", "% (list(p))) if getattr(p, 'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands return", "self.rightexpr = rightexpr self.leftexpr = leftexpr self.test_command = test_command self.group", "p): return [p.assignment] if len(p) == 1 else [p.assignment] +", "None @_('IF list_commands THEN compound_commands FI', 'IF list_commands THEN NEWLINE", "%prec BOOL_COMBINATION' ) def test_expressions(self, p): if getattr(p, 'BOOL_NOT', None):", "def __init__(self, executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None): self.executable = executable", "'arguments', 'redirections', 'pipetocmd') def __init__(self, executable=None, assignments=None, arguments=None, redirections=None, pipetocmd=None):", "group=False): self.combination = combination self.rightexpr = rightexpr self.leftexpr = leftexpr", "self.assignop, self.value or '') class ASTArgument: __slots__ = ('option', 'value')", "'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands else: return ASTCommands(p.compound_command) @_(", "arg_value(self, p): # print('value(%s)' % (list(p))) return p[0] @_('assignment', 'assignment", "if_command(self, p): if getattr(p, 'ELSE', None): return ASTIfCommand(p.list_commands, p.compound_commands0, p.compound_commands1)", "p[0] @_('QSTRING', 'DQSTRING', 'BTQUOTED', 'CMD_EXP', 'VAL_STRING', 'VAR_SUBST', 'VARIABLE') def value(self,", "'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) else: return p.test_expression @_('BOOL_OR',", "'else_commands') def __init__(self, test_commands, then_commands, else_commands=None): self.test_commands = test_commands self.then_commands", "return '( %s )'%(self.rightexpr) else: return '%s'%(self.rightexpr) class ASTTestCondition: __slots__", "(self.test_commands, self.then_commands, self.else_commands) else: return 'if %s; then\\n%s\\nfi' % (self.test_commands,", "# print('value(%s)' % (list(p))) return p[0] @_('assignment', 'assignment assignments') def", "= '{}' elif getattr(p, 'LPAREN', None): p.compound_commands.grouping = '()' return", "p[1] else: return p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK')", "p.pipe_commands if getattr(p, 'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return", "parser = BashParser() while True: try: text = input('Command:>') result", "self.pipetocmd else '')).strip() else: return ' '.join([str(i) for i in", "i in self.arguments]), ' '.join([str(i) for i in self.redirections]), '|", "from sly import Parser from .lexer import BashLexer class ASTCommands(list):", "return ASTTestCombination(None, p.test_expressions, group=True) else: return p.test_expression @_('BOOL_OR', 'BOOL_AND') def", "('nonassoc', BOOL_NOT), # ('nonassoc', BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative", "'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.test_expressions1, p.test_expressions0) elif getattr(p, 'LPAREN', None):", "p.test_expressions, group=True) else: return p.test_expression @_('BOOL_OR', 'BOOL_AND') def boolean_combination(self, p):", "'')).strip() else: return ' '.join([str(i) for i in self.assignments]) class", "group def __repr__(self): if self.leftexpr: return '%s %s %s'%(self.leftexpr, self.combination,", "(self.test_commands, self.then_commands) class BashParser(Parser): # Get the token list from", "__repr__(self): if self.leftexpr: return '%s %s %s'%(self.leftexpr, self.combination, self.rightexpr) elif", "@_( 'LBRACE NEWLINE compound_commands RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN compound_commands", "if getattr(p, 'BOOL_NOT', None): cmd = ASTTestCombination(p.BOOL_NOT, p.pipe_commands) return cmd", "return ASTIfCommand(p.list_commands, p.compound_commands) # @_( #'test_command', # 'command_pipe', # #", "'command_pipe boolean_combination compound_command' # ) # def compound_command(self, p): #", "list from the lexer (required) debugfile = 'parser.out' tokens =", "on Jun 13, 2019 @author: sarvi ''' from sly import", "p): # print('simple_command(%s)' % (list(p))) if getattr(p, 'compound_commands', None): p.compound_commands.insert(0,", "return 'if %s; then\\n%s\\nelse\\n%s\\nfi' % (self.test_commands, self.then_commands, self.else_commands) else: return", "ASTCommand(p[0], None, getattr(p, 'arguments', None), getattr(p, 'redirects', None)) @_('argument', 'argument", "p[0] if __name__ == '__main__': lexer = BashLexer() parser =", "def __repr__(self): if self.executable: return ('%s %s %s %s %s'", "def group_command(self, p): if getattr(p, 'LBRACE', None): p.compound_commands.grouping = '{}'", "list() self.arguments = arguments or list() self.redirections = redirections or", "p.list_commands else: return ASTCommands(p.pipe_command) @_('NEWLINE', 'CMDSEP', 'AMPERSAND') def end_pipe(self, p):", "if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.test_expression) elif getattr(p, 'LPAREN',", "# 'cond_command', # 'arith_for_command' # ) # def shell_command(self, p):", "lexer (required) debugfile = 'parser.out' tokens = BashLexer.tokens precedence =", "ASTCommands(p.compound_command) @_( 'group_command', 'list_commands', 'if_command', ) def compound_command(self, p): return", "= ('test_commands', 'then_commands', 'else_commands') def __init__(self, test_commands, then_commands, else_commands=None): self.test_commands", "# 'for_command', # 'case_command', # 'WHILE compound_list DO compound_list DONE',", "None)) @_('echo_command', 'exec_command', 'test_command') def base_command(self, p): if len(p)==2: p[1].assignments", "Parser from .lexer import BashLexer class ASTCommands(list): __slots__ = ('grouping')", "for i in self.assignments]), self.executable, ' '.join([str(i) for i in", "return ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison,", "'| %s'%self.pipetocmd if self.pipetocmd else '')).strip() else: return ' '.join([str(i)", "pipe_commands') def pipe_commands(self, p): # print('simple_command(%s)' % (list(p))) if getattr(p,", "'base_command redirects', 'assignments base_command redirects') def simple_command(self, p): # print('simple_command(%s)'", "'\\n'.join(x) class ASTCommand: __slots__ = ('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd')", "redirects(self, p): return [p.redirect] if len(p)==1 else [p.redirect] + p.redirects", "return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions", "= ('leftexpr', 'combination', 'rightexpr', 'test_command', 'group') def __init__(self, combination, rightexpr,", "'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p, 'command_pipe', None): return", "__slots__ = ('assignments', 'executable', 'arguments', 'redirections', 'pipetocmd') def __init__(self, executable=None,", "or list() self.redirections = redirections or list() self.pipetocmd = pipetocmd", "getattr(p, 'redirects', None)) @_('argument', 'argument arguments') def arguments(self, p): return", "compound_list DONE', # 'UNTIL compound_list DO compound_list DONE', # 'select_command',", "p): if getattr(p, 'LBRACE', None): p.compound_commands.grouping = '{}' elif getattr(p,", "DO compound_list DONE', # 'select_command', # 'if_command', # 'subshell', #", "self.executable: return ('%s %s %s %s %s' % (' '.join([str(i)", "value def __repr__(self): return '%s%s%s'%(self.variable, self.assignop, self.value or '') class", "print('program(%s)' % (p.compound_commands)) return p.compound_commands @_('compound_command', 'compound_command end_command', 'compound_command end_command", ") # def shell_command(self, p): # print('assignments(%s)' % (list(p))) #", "'%s %s'%(self.test, self.rightvalue) else: return '%s' % (self.rightvalue) class ASTIfCommand:", "arguments or list() self.redirections = redirections or list() self.pipetocmd =", "else [p.assignment] + p.assignments @_('LET ID assignop value', 'ID assignop", "else [p.redirect] + p.redirects @_('REDIRECT', 'REDIRECT WORD') def redirect(self, p):", "None), getattr(p, 'arg_value', None)) @_('value', 'WORD') def arg_value(self, p): #", "sarvi ''' from sly import Parser from .lexer import BashLexer", "p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT, p.command_pipe) elif getattr(p,", "len(p)==1 else [p.argument] + p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value') def", "getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p, 'OPTION',", "p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER', 'ASSIGN') def boolean_comparison(self, p):", "RBRACE', 'LBRACE compound_commands RBRACE', 'LPAREN compound_commands RPAREN', ) def group_command(self,", "base_command(self, p): if len(p)==2: p[1].assignments = p.assignments.assignments return p[1] else:", "None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p, 'list_commands', None): p.list_commands.insert(0,", "test_commands, then_commands, else_commands=None): self.test_commands = test_commands self.then_commands = then_commands self.else_commands", "if self.option and self.value else (self.option or self.value) class ASTRedirection:", "getattr(p, 'PIPE', None): p.simple_command.pipetocmd = p.pipe_commands return p.simple_command @_('assignments', 'base_command',", "def arg_value(self, p): # print('value(%s)' % (list(p))) return p[0] @_('assignment',", "'list_commands', 'if_command', ) def compound_command(self, p): return p[0] @_( 'LBRACE", "p.test_command @_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def", "group_command(self, p): if getattr(p, 'LBRACE', None): p.compound_commands.grouping = '{}' elif", "% (list(p))) if getattr(p, 'compound_commands', None): p.compound_commands.insert(0, p.compound_command) return p.compound_commands", "self.assignments]), self.executable, ' '.join([str(i) for i in self.arguments]), ' '.join([str(i)", "pipetocmd=None): self.executable = executable self.assignments = assignments or list() self.arguments", "ASTArgument: __slots__ = ('option', 'value') def __init__(self, option=None, value=None): self.option", "BOOL_LESS, BOOL_GREATER, BOOL_EQ, BOOL_NEQ), # Nonassociative operators ('left', LIST_COMMANDS), ('left',", "= assignop self.value = value def __repr__(self): return '%s%s%s'%(self.variable, self.assignop,", "class ASTArgument: __slots__ = ('option', 'value') def __init__(self, option=None, value=None):", "RDBRACK') def test_command(self, p): if getattr(p, 'BOOL_NOT', None): return ASTTestCombination(p.BOOL_NOT,", "'pipe_command end_pipe list_commands', 'pipe_command boolean_combination list_commands') def list_commands(self, p): if", "p[0] @_('LBRACK test_expressions RBRACK', 'LDBRACK test_expressions RDBRACK') def test_command(self, p):", "def compound_command(self, p): return p[0] @_( 'LBRACE NEWLINE compound_commands RBRACE',", "if getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command) elif getattr(p,", "file def __repr__(self): return '%s%s'%(self.redirect, self.file) if self.file else '%s'%(self.redirect)", "else: return ' '.join([str(i) for i in self.assignments]) class ASTAssignment:", "= executable self.assignments = assignments or list() self.arguments = arguments", "list_commands(self, p): if getattr(p, 'boolean_combination', None): return ASTTestCombination(p.boolean_combination, p.list_commands, p.pipe_command)", "test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT test_expressions %prec BOOL_NOT', 'test_expressions", "'test', 'rightvalue') def __init__(self, test, rightvalue, leftvalue=None): self.test = test", "'redirect redirects') def redirects(self, p): return [p.redirect] if len(p)==1 else", "getattr(p, 'value', None)) @_('ASSIGN', 'ARITH_ASSIGN') def assignop(self, p): return p[0]", "boolean_comparison value %prec BOOL_COMPARISON', 'OPTION value') def test_expression(self, p): if", "@_('time_command pipe_commands', 'time_command BOOL_NOT pipe_commands', 'pipe_commands', 'BOOL_NOT pipe_commands') def pipe_command(self,", "ASTTestCombination(None, p.test_expressions, group=True) elif getattr(p, 'OPTION', None): return ASTTestCondition(p.boolean_comparison, p.value)", "%prec BOOL_COMPARISON', 'OPTION value') def test_expression(self, p): if getattr(p, 'BOOL_NOT',", "return ASTCommand(p[0], None, getattr(p, 'arguments', None), getattr(p, 'redirects', None)) @_('argument',", "__slots__ = ('option', 'value') def __init__(self, option=None, value=None): self.option =", "for i in self.assignments]) class ASTAssignment: __slots__ = ('variable', 'assignop',", "('grouping') def __init__(self, command, grouping=None): self.append(command) self.grouping = grouping def", "else: return ASTTestCombination(None, p.test_expressions, test_command=True) @_('test_expression', 'LPAREN test_expressions RPAREN', 'BOOL_NOT", "getattr(p, 'LPAREN', None): return ASTTestCombination(None, p.test_expressions, group=True) else: return p.test_expression", "return ASTRedirection(p.REDIRECT, getattr(p, 'WORD', None)) @_('echo_command', 'exec_command', 'test_command') def base_command(self,", "def exec_command(self, p): return ASTCommand(p[0], None, getattr(p, 'arguments', None), getattr(p,", "'value') def __init__(self, option=None, value=None): self.option = option self.value =", "= then_commands self.else_commands = else_commands def __repr__(self): if self.else_commands: return", "cmd @_('simple_command', 'simple_command PIPE pipe_commands') def pipe_commands(self, p): # print('simple_command(%s)'", "else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION', 'BOOL_EQ', 'BOOL_NEQ', 'BOOL_LESS', 'BOOL_GREATER',", "if len(p)==1 else [p.argument] + p.arguments @_('OPTION ASSIGN', 'OPTION', 'arg_value')", "self.value = value def __repr__(self): return '%s=%s'%(self.option, self.value) if self.option", "'{}' elif getattr(p, 'LPAREN', None): p.compound_commands.grouping = '()' return getattr(p,", "'group_command', 'list_commands', 'if_command', ) def compound_command(self, p): return p[0] @_(", "@_('OPTION ASSIGN', 'OPTION', 'arg_value') def argument(self, p): # print('assignment(%s)' %", "WORD') def redirect(self, p): # print('assignment(%s)' % (list(p))) return ASTRedirection(p.REDIRECT,", "self.rightexpr) elif self.test_command: return '[ %s ]'%(self.rightexpr) elif self.group: return", "compound_command(self, p): # if getattr(p, 'boolean_combination', None): # return ASTTestCombination(p.boolean_combination,", "list_commands THEN compound_commands FI', 'IF list_commands THEN NEWLINE compound_commands FI',", "%s %s' % (' '.join([str(i) for i in self.assignments]), self.executable,", "None): return ASTTestCondition(p.boolean_comparison, p.value) else: return ASTTestCondition(p.boolean_comparison, p.value1, p.value0) @_('OPTION'," ]
[ "- target_date return dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected", "= input('Format: [dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/') if len(parts)!= 3:", "3: print('Bad date found', date_str) return get_lmp_from_patient() year = int(parts[2])", "datetime.date(target_date.year, original_date.month, original_date.day) dt = this_year - target_date return dt.days", "max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day = get_lmp_from_patient() gest_length = datetime.timedelta(days", "gest_std = datetime.timedelta(days = 13) expected_due_date = lmp_day + gest_length", "original_date.day) dt = this_year - target_date return dt.days def print_due_date_information(min_due_date,", "print() def get_lmp_from_patient(): print(\"When was the patient's last normal menstrual", "target_date return dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected due", "print('But as late as ', max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day", "date_str.split('/') if len(parts)!= 3: print('Bad date found', date_str) return get_lmp_from_patient()", "= int(parts[2]) month = int(parts[1]) day = int(parts[0]) lmp =", "lmp = datetime.date(year, month, day) #print(lmp) return lmp #avg pregnancy", "was the patient's last normal menstrual cycle? \") date_str =", "gest_length min_due_date = expected_due_date - gest_std max_due_date = expected_due_date +", "[dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/') if len(parts)!= 3: print('Bad date", "print_header() lmp_day = get_lmp_from_patient() gest_length = datetime.timedelta(days = 281) gest_std", "if len(parts)!= 3: print('Bad date found', date_str) return get_lmp_from_patient() year", "month, day) #print(lmp) return lmp #avg pregnancy length is 281", "#print(lmp) return lmp #avg pregnancy length is 281 days def", "= datetime.date(target_date.year, original_date.month, original_date.day) dt = this_year - target_date return", "last normal menstrual cycle? \") date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018'", "#'05/06/2018' parts = date_str.split('/') if len(parts)!= 3: print('Bad date found',", "return get_lmp_from_patient() year = int(parts[2]) month = int(parts[1]) day =", "<reponame>biomed-bioinformatics-bootcamp/bmes-t580-2019-coursework-charrison620<gh_stars>0 import datetime def print_header(): print('----------------------------') print(' Due Date APP", "get_lmp_from_patient() year = int(parts[2]) month = int(parts[1]) day = int(parts[0])", "281) gest_std = datetime.timedelta(days = 13) expected_due_date = lmp_day +", "', expected_due_date.strftime('%a %b %d %Y')) print('But it may be as", "= int(parts[1]) day = int(parts[0]) lmp = datetime.date(year, month, day)", "this_year - target_date return dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your", "#avg pregnancy length is 281 days def compute_days_between_dates(original_date, target_date): this_year", "is ', expected_due_date.strftime('%a %b %d %Y')) print('But it may be", "= expected_due_date - gest_std max_due_date = expected_due_date + gest_std print_due_date_information(min_due_date,", "original_date.month, original_date.day) dt = this_year - target_date return dt.days def", "patient's last normal menstrual cycle? \") date_str = input('Format: [dd/mm/yyyy}')", "len(parts)!= 3: print('Bad date found', date_str) return get_lmp_from_patient() year =", "parts = date_str.split('/') if len(parts)!= 3: print('Bad date found', date_str)", "print('----------------------------') print(' Due Date APP ') print('----------------------------') print() def get_lmp_from_patient():", "is 281 days def compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year, original_date.month,", "early as ', min_due_date.strftime('%m/%d/%Y')) print('But as late as ', max_due_date.strftime('%m/%d/%Y'))", "day = int(parts[0]) lmp = datetime.date(year, month, day) #print(lmp) return", "= datetime.timedelta(days = 13) expected_due_date = lmp_day + gest_length min_due_date", "days def compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year, original_date.month, original_date.day) dt", "due date is ', expected_due_date.strftime('%a %b %d %Y')) print('But it", "def main(): print_header() lmp_day = get_lmp_from_patient() gest_length = datetime.timedelta(days =", "max_due_date, expected_due_date): print('Your expected due date is ', expected_due_date.strftime('%a %b", "def get_lmp_from_patient(): print(\"When was the patient's last normal menstrual cycle?", "date found', date_str) return get_lmp_from_patient() year = int(parts[2]) month =", "late as ', max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day = get_lmp_from_patient()", "datetime.timedelta(days = 281) gest_std = datetime.timedelta(days = 13) expected_due_date =", "dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected due date is", "int(parts[2]) month = int(parts[1]) day = int(parts[0]) lmp = datetime.date(year,", "dt = this_year - target_date return dt.days def print_due_date_information(min_due_date, max_due_date,", "the patient's last normal menstrual cycle? \") date_str = input('Format:", "= 13) expected_due_date = lmp_day + gest_length min_due_date = expected_due_date", "= int(parts[0]) lmp = datetime.date(year, month, day) #print(lmp) return lmp", "year = int(parts[2]) month = int(parts[1]) day = int(parts[0]) lmp", "it may be as early as ', min_due_date.strftime('%m/%d/%Y')) print('But as", "lmp #avg pregnancy length is 281 days def compute_days_between_dates(original_date, target_date):", "13) expected_due_date = lmp_day + gest_length min_due_date = expected_due_date -", "', max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day = get_lmp_from_patient() gest_length =", "as early as ', min_due_date.strftime('%m/%d/%Y')) print('But as late as ',", "print('----------------------------') print() def get_lmp_from_patient(): print(\"When was the patient's last normal", "def compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year, original_date.month, original_date.day) dt =", "print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected due date is ', expected_due_date.strftime('%a", "expected_due_date = lmp_day + gest_length min_due_date = expected_due_date - gest_std", "gest_length = datetime.timedelta(days = 281) gest_std = datetime.timedelta(days = 13)", "min_due_date.strftime('%m/%d/%Y')) print('But as late as ', max_due_date.strftime('%m/%d/%Y')) def main(): print_header()", "= 281) gest_std = datetime.timedelta(days = 13) expected_due_date = lmp_day", "cycle? \") date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/')", "lmp_day = get_lmp_from_patient() gest_length = datetime.timedelta(days = 281) gest_std =", "datetime.timedelta(days = 13) expected_due_date = lmp_day + gest_length min_due_date =", "print('But it may be as early as ', min_due_date.strftime('%m/%d/%Y')) print('But", "input('Format: [dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/') if len(parts)!= 3: print('Bad", "= this_year - target_date return dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date):", "normal menstrual cycle? \") date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018' parts", "may be as early as ', min_due_date.strftime('%m/%d/%Y')) print('But as late", "return lmp #avg pregnancy length is 281 days def compute_days_between_dates(original_date,", "date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/') if len(parts)!=", "compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year, original_date.month, original_date.day) dt = this_year", "datetime.date(year, month, day) #print(lmp) return lmp #avg pregnancy length is", "Due Date APP ') print('----------------------------') print() def get_lmp_from_patient(): print(\"When was", "as late as ', max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day =", "date is ', expected_due_date.strftime('%a %b %d %Y')) print('But it may", "return dt.days def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected due date", "get_lmp_from_patient() gest_length = datetime.timedelta(days = 281) gest_std = datetime.timedelta(days =", "') print('----------------------------') print() def get_lmp_from_patient(): print(\"When was the patient's last", "main(): print_header() lmp_day = get_lmp_from_patient() gest_length = datetime.timedelta(days = 281)", "\") date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018' parts = date_str.split('/') if", "expected_due_date - gest_std max_due_date = expected_due_date + gest_std print_due_date_information(min_due_date, max_due_date,", "281 days def compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year, original_date.month, original_date.day)", "expected due date is ', expected_due_date.strftime('%a %b %d %Y')) print('But", "int(parts[0]) lmp = datetime.date(year, month, day) #print(lmp) return lmp #avg", "- gest_std max_due_date = expected_due_date + gest_std print_due_date_information(min_due_date, max_due_date, expected_due_date)", "target_date): this_year = datetime.date(target_date.year, original_date.month, original_date.day) dt = this_year -", "print('Bad date found', date_str) return get_lmp_from_patient() year = int(parts[2]) month", "min_due_date = expected_due_date - gest_std max_due_date = expected_due_date + gest_std", "datetime def print_header(): print('----------------------------') print(' Due Date APP ') print('----------------------------')", "%Y')) print('But it may be as early as ', min_due_date.strftime('%m/%d/%Y'))", "pregnancy length is 281 days def compute_days_between_dates(original_date, target_date): this_year =", "print_header(): print('----------------------------') print(' Due Date APP ') print('----------------------------') print() def", "%d %Y')) print('But it may be as early as ',", "expected_due_date.strftime('%a %b %d %Y')) print('But it may be as early", "print(' Due Date APP ') print('----------------------------') print() def get_lmp_from_patient(): print(\"When", "be as early as ', min_due_date.strftime('%m/%d/%Y')) print('But as late as", "as ', max_due_date.strftime('%m/%d/%Y')) def main(): print_header() lmp_day = get_lmp_from_patient() gest_length", "gest_std max_due_date = expected_due_date + gest_std print_due_date_information(min_due_date, max_due_date, expected_due_date) main()", "Date APP ') print('----------------------------') print() def get_lmp_from_patient(): print(\"When was the", "found', date_str) return get_lmp_from_patient() year = int(parts[2]) month = int(parts[1])", "print('Your expected due date is ', expected_due_date.strftime('%a %b %d %Y'))", "import datetime def print_header(): print('----------------------------') print(' Due Date APP ')", "print(\"When was the patient's last normal menstrual cycle? \") date_str", "get_lmp_from_patient(): print(\"When was the patient's last normal menstrual cycle? \")", "def print_due_date_information(min_due_date, max_due_date, expected_due_date): print('Your expected due date is ',", "= lmp_day + gest_length min_due_date = expected_due_date - gest_std max_due_date", "length is 281 days def compute_days_between_dates(original_date, target_date): this_year = datetime.date(target_date.year,", "%b %d %Y')) print('But it may be as early as", "def print_header(): print('----------------------------') print(' Due Date APP ') print('----------------------------') print()", "month = int(parts[1]) day = int(parts[0]) lmp = datetime.date(year, month,", "lmp_day + gest_length min_due_date = expected_due_date - gest_std max_due_date =", "menstrual cycle? \") date_str = input('Format: [dd/mm/yyyy}') #'05/06/2018' parts =", "= date_str.split('/') if len(parts)!= 3: print('Bad date found', date_str) return", "date_str) return get_lmp_from_patient() year = int(parts[2]) month = int(parts[1]) day", "day) #print(lmp) return lmp #avg pregnancy length is 281 days", "+ gest_length min_due_date = expected_due_date - gest_std max_due_date = expected_due_date", "', min_due_date.strftime('%m/%d/%Y')) print('But as late as ', max_due_date.strftime('%m/%d/%Y')) def main():", "this_year = datetime.date(target_date.year, original_date.month, original_date.day) dt = this_year - target_date", "as ', min_due_date.strftime('%m/%d/%Y')) print('But as late as ', max_due_date.strftime('%m/%d/%Y')) def", "= datetime.date(year, month, day) #print(lmp) return lmp #avg pregnancy length", "= datetime.timedelta(days = 281) gest_std = datetime.timedelta(days = 13) expected_due_date", "= get_lmp_from_patient() gest_length = datetime.timedelta(days = 281) gest_std = datetime.timedelta(days", "int(parts[1]) day = int(parts[0]) lmp = datetime.date(year, month, day) #print(lmp)", "APP ') print('----------------------------') print() def get_lmp_from_patient(): print(\"When was the patient's", "expected_due_date): print('Your expected due date is ', expected_due_date.strftime('%a %b %d" ]
[ "MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'}))", "Silicon Valley, CA 00000'})) class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class':", "from django.core.validators import MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)],", "CA 00000'})) class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form): mpg =", "'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)],", "class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "'1 (default is 1 if left blank)'})) class DistanceForm(forms.Form): distance", "gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class", "django import forms from django.core.validators import MinValueValidator, MinLengthValidator class OriginForm(forms.Form):", "'inlineFormInputGroup', 'placeholder': '123 Tech St, Silicon Valley, CA 00000'})) class", "'1.23'})) class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class':", "'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control',", "MinLengthValidator class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "Silicon Valley, CA 00000'})) class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class':", "'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1 (default is 1 if left", "DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '15.2'}))", "= forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form):", "'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech St, Silicon Valley, CA", "'id': 'inlineFormInputGroup', 'placeholder': '1 (default is 1 if left blank)'}))", "import forms from django.core.validators import MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address", "Tech St, Silicon Valley, CA 00000'})) class DestinationForm(forms.Form): destination_address =", "St, Silicon Valley, CA 00000'})) class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)],", "'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "Valley, CA 00000'})) class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control',", "GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'}))", "origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech", "import MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control',", "OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123", "mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'})) class", "Tech St, Silicon Valley, CA 00000'})) class GasPriceForm(forms.Form): gas_price =", "Valley, CA 00000'})) class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control',", "1 if left blank)'})) class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class':", "'placeholder': '1.23'})) class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech", "django.core.validators import MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class':", "forms from django.core.validators import MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address =", "class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "'id': 'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class':", "widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech St, Silicon Valley,", "is 1 if left blank)'})) class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)],", "'123 Tech St, Silicon Valley, CA 00000'})) class GasPriceForm(forms.Form): gas_price", "NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1", "'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control',", "= forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1 (default is", "MinValueValidator, MinLengthValidator class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1 (default", "'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form): mpg = forms.FloatField(validators=[MinValueValidator(0.01)],", "blank)'})) class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech St, Silicon", "'12'})) class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1 (default is 1", "DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123", "widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1 (default is 1 if", "class NumPeopleForm(forms.Form): num_people = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "00000'})) class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "St, Silicon Valley, CA 00000'})) class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)],", "00000'})) class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup',", "if left blank)'})) class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control',", "'123 Tech St, Silicon Valley, CA 00000'})) class DestinationForm(forms.Form): destination_address", "class OriginForm(forms.Form): origin_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "(default is 1 if left blank)'})) class DistanceForm(forms.Form): distance =", "forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people", "= forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form):", "class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "class DestinationForm(forms.Form): destination_address = forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder':", "'id': 'inlineFormInputGroup', 'placeholder': '123 Tech St, Silicon Valley, CA 00000'}))", "widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '12'})) class NumPeopleForm(forms.Form): num_people =", "'placeholder': '123 Tech St, Silicon Valley, CA 00000'})) class GasPriceForm(forms.Form):", "= forms.CharField(validators=[MinLengthValidator(1)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '123 Tech St,", "left blank)'})) class DistanceForm(forms.Form): distance = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "CA 00000'})) class GasPriceForm(forms.Form): gas_price = forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id':", "from django import forms from django.core.validators import MinValueValidator, MinLengthValidator class", "'placeholder': '1 (default is 1 if left blank)'})) class DistanceForm(forms.Form):", "'placeholder': '123 Tech St, Silicon Valley, CA 00000'})) class DestinationForm(forms.Form):", "forms.FloatField(validators=[MinValueValidator(0.01)], widget=forms.TextInput(attrs={'class': 'form-control', 'id': 'inlineFormInputGroup', 'placeholder': '1.23'})) class MpgForm(forms.Form): mpg", "'inlineFormInputGroup', 'placeholder': '1 (default is 1 if left blank)'})) class" ]
[ "= (-2, (1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2,", "raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2, (2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting)", "work(user, room_id, raffle_id): # await UtilsTask.enter_room(user, room_id) json_rsp = await", "not await UtilsTask.is_normal_room(user, room_id): return if raffle_id is not None:", "raffle_id is not None: json_rsp = {'data': {'id': raffle_id}} else:", "为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user, room_id, raffle_id=None): if not await", "@staticmethod async def check(user, room_id, raffle_id=None): if not await UtilsTask.is_normal_room(user,", "user.id) if not json_rsp['code']: data = json_rsp['data'] gift_name = data[\"gift_name\"]", "if not json_rsp['code']: data = json_rsp['data'] gift_name = data[\"gift_name\"] gift_num", "Multi class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true", "= 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user, room_id, raffle_id=None):", "await UtilsTask.enter_room(user, room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)',", "data = json_rsp['data'] if data: raffle_id = int(data['id']) if not", "json_rsp['data'] gift_name = data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}') bili_statistics.add2results(gift_name,", "gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}') bili_statistics.add2results(gift_name, user.id, gift_num) return print(json_rsp)", "gift_name = data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}') bili_statistics.add2results(gift_name, user.id,", "from reqs.storm_raffle_handler import StormRaffleHandlerReq from tasks.utils import UtilsTask from .base_class", "json_rsp = await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings = [] data", "if raffle_id is not None: json_rsp = {'data': {'id': raffle_id}}", "(2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod", "DontWait, Multi): TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def", "{'id': raffle_id}} else: json_rsp = await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings", "async def work(user, room_id, raffle_id): # await UtilsTask.enter_room(user, room_id) json_rsp", "# 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user, room_id, raffle_id=None): if not", "room_id, raffle_id): # await UtilsTask.enter_room(user, room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join,", "UtilsTask from .base_class import Forced, DontWait, Multi class StormRaffleJoinTask(Forced, DontWait,", "if not await UtilsTask.is_normal_room(user, room_id): return if raffle_id is not", "room_id, raffle_id=None): if not await UtilsTask.is_normal_room(user, room_id): return if raffle_id", "import StormRaffleHandlerReq from tasks.utils import UtilsTask from .base_class import Forced,", "bili_statistics from reqs.storm_raffle_handler import StormRaffleHandlerReq from tasks.utils import UtilsTask from", "4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod async", "next_step_settings.append(next_step_setting) next_step_setting = (-2, (2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000,", "bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']: data = json_rsp['data'] gift_name =", "tasks.utils import UtilsTask from .base_class import Forced, DontWait, Multi class", "(1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2, (2, 4),", "next_step_setting = (-2, (2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM')", "class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod", "StormRaffleHandlerReq from tasks.utils import UtilsTask from .base_class import Forced, DontWait,", "= data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}') bili_statistics.add2results(gift_name, user.id, gift_num)", "= json_rsp['data'] if data: raffle_id = int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000):", "(-2, (1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2, (2,", "room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2, (2, 4), room_id, raffle_id)", "import bili_statistics from reqs.storm_raffle_handler import StormRaffleHandlerReq from tasks.utils import UtilsTask", "json_rsp = await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not", "room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod async def", "else: json_rsp = await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings = []", "raffle_id = int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting", "return next_step_settings @staticmethod async def work(user, room_id, raffle_id): # await", "data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}') bili_statistics.add2results(gift_name, user.id, gift_num) return", "room_id): return if raffle_id is not None: json_rsp = {'data':", "TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user, room_id,", "from tasks.utils import UtilsTask from .base_class import Forced, DontWait, Multi", "not json_rsp['code']: data = json_rsp['data'] gift_name = data[\"gift_name\"] gift_num =", "Multi): TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user,", "room_id) next_step_settings = [] data = json_rsp['data'] if data: raffle_id", "raffle_id=None): if not await UtilsTask.is_normal_room(user, room_id): return if raffle_id is", "check(user, room_id, raffle_id=None): if not await UtilsTask.is_normal_room(user, room_id): return if", "'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async def check(user, room_id, raffle_id=None): if", "user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting = (-2, (1, 3), room_id, raffle_id)", "= await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']:", "json_rsp['code']: data = json_rsp['data'] gift_name = data[\"gift_name\"] gift_num = data[\"gift_num\"]", "(-2, (2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings", "return if raffle_id is not None: json_rsp = {'data': {'id':", "json_rsp['data'] if data: raffle_id = int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖", "user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings = [] data = json_rsp['data'] if", "UtilsTask.is_normal_room(user, room_id): return if raffle_id is not None: json_rsp =", "raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']: data = json_rsp['data'] gift_name", "raffle_id): # await UtilsTask.enter_room(user, room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join, user,", "import Forced, DontWait, Multi class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME =", "import UtilsTask from .base_class import Forced, DontWait, Multi class StormRaffleJoinTask(Forced,", "next_step_settings = [] data = json_rsp['data'] if data: raffle_id =", "not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting = (-2, (1, 3),", "Forced, DontWait, Multi class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME = 'join_storm_raffle'", "async def check(user, room_id, raffle_id=None): if not await UtilsTask.is_normal_room(user, room_id):", "{'data': {'id': raffle_id}} else: json_rsp = await user.req_s(StormRaffleHandlerReq.check, user, room_id)", "raffle_id}} else: json_rsp = await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings =", "is not None: json_rsp = {'data': {'id': raffle_id}} else: json_rsp", "3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting = (-2, (2, 4), room_id,", "= {'data': {'id': raffle_id}} else: json_rsp = await user.req_s(StormRaffleHandlerReq.check, user,", "DontWait, Multi class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME = 'join_storm_raffle' #", "next_step_settings @staticmethod async def work(user, room_id, raffle_id): # await UtilsTask.enter_room(user,", "user, room_id) next_step_settings = [] data = json_rsp['data'] if data:", "= json_rsp['data'] gift_name = data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果: {gift_name}X{gift_num}')", "None: json_rsp = {'data': {'id': raffle_id}} else: json_rsp = await", "= int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting =", "'STORM') return next_step_settings @staticmethod async def work(user, room_id, raffle_id): #", "user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']: data = json_rsp['data']", "UtilsTask.enter_room(user, room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id)", "not None: json_rsp = {'data': {'id': raffle_id}} else: json_rsp =", "user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']: data =", "def work(user, room_id, raffle_id): # await UtilsTask.enter_room(user, room_id) json_rsp =", "bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod async def work(user, room_id, raffle_id):", "{raffle_id}', with_userid=False) next_step_setting = (-2, (1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting)", "await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings = [] data = json_rsp['data']", "# await UtilsTask.enter_room(user, room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join, user, raffle_id)", "if data: raffle_id = int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}',", "with_userid=False) next_step_setting = (-2, (1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting", "StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME = 'join_storm_raffle' # 为了速度,有时不用等room_id验证就参加,置room_id为0,is_normal_room自然会返回固定值true @staticmethod async", "next_step_setting = (-2, (1, 3), room_id, raffle_id) next_step_settings.append(next_step_setting) next_step_setting =", "<reponame>Ayouuuu/bili2.0 import bili_statistics from reqs.storm_raffle_handler import StormRaffleHandlerReq from tasks.utils import", "= (-2, (2, 4), room_id, raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return", "int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting = (-2,", "[] data = json_rsp['data'] if data: raffle_id = int(data['id']) if", "data: raffle_id = int(data['id']) if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False)", ".base_class import Forced, DontWait, Multi class StormRaffleJoinTask(Forced, DontWait, Multi): TASK_NAME", "def check(user, room_id, raffle_id=None): if not await UtilsTask.is_normal_room(user, room_id): return", "await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if not json_rsp['code']: data", "= [] data = json_rsp['data'] if data: raffle_id = int(data['id'])", "@staticmethod async def work(user, room_id, raffle_id): # await UtilsTask.enter_room(user, room_id)", "from .base_class import Forced, DontWait, Multi class StormRaffleJoinTask(Forced, DontWait, Multi):", "await UtilsTask.is_normal_room(user, room_id): return if raffle_id is not None: json_rsp", "room_id) json_rsp = await user.req_s(StormRaffleHandlerReq.join, user, raffle_id) bili_statistics.add2joined_raffles('节奏风暴(合计)', user.id) if", "reqs.storm_raffle_handler import StormRaffleHandlerReq from tasks.utils import UtilsTask from .base_class import", "= await user.req_s(StormRaffleHandlerReq.check, user, room_id) next_step_settings = [] data =", "raffle_id) next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod async def work(user,", "next_step_settings.append(next_step_setting) bili_statistics.add2raffle_ids(raffle_id/1000000, 'STORM') return next_step_settings @staticmethod async def work(user, room_id,", "if not bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting = (-2, (1,", "json_rsp = {'data': {'id': raffle_id}} else: json_rsp = await user.req_s(StormRaffleHandlerReq.check,", "bili_statistics.is_raffleid_duplicate(raffle_id/1000000): user.info(f'确认获取到飓风暴抽奖 {raffle_id}', with_userid=False) next_step_setting = (-2, (1, 3), room_id,", "data = json_rsp['data'] gift_name = data[\"gift_name\"] gift_num = data[\"gift_num\"] user.info(f'飓风暴({raffle_id})的参与结果:" ]
[ "for the early gate will cause # no updates to", "bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name + \"_identity\")}) GradualBNNode = GradualSimpleBatchNormalizationNode", "= tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node = late(name + \"_late\",", "as arguments \"\"\" assert set(children.keys()) == {\"subtree\", \"cost\"} subtree =", "+ late_vw.variable * late_gate) out_shape = [] assert early_vw.ndim ==", "epsilon / late_gate else: early_gate = 1 - late_gate network.set_hyperparameter(self.name", "out_shape.append(None) elif e is None: out_shape.append(l) elif l is None:", "\"\"\" assert set(children.keys()) == {\"subtree\", \"cost\"} subtree = children[\"subtree\"] cost", "(\"early\", \"late\") def init_state(self, network): children = self.raw_children() early =", "\"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref}) # NOTE: need separate node", "\"update_scale_factor\", # these updates are also multiplied by # late_gate", "# AND multiplied by it. Clipping only for the early", "assert e == l out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"},", "- late_gate) + late_vw.variable * late_gate) out_shape = [] assert", "late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\",", "+ \"_late\", {\"subtree\": late_subtree, \"cost\": cost}) early_subtree = tn.UpdateScaleNode(name +", "1) late_gate = treeano.utils.as_fX(late_gate) # NOTE: late gate cannot be", "2 nodes \"\"\" hyperparameter_names = (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer,", "return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name +", "later on, so rescale them early_gate / late_gate) def GradNetOptimizerInterpolationNode(name,", "import theano import theano.tensor as T import treeano import treeano.nodes", "set(children.keys()) == {\"subtree\", \"cost\"} subtree = children[\"subtree\"] cost = children[\"cost\"]", "\"\"\" hyperparameter_names = (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, )", "= tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\",", "\"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node =", "l is None: out_shape.append(e) else: assert e == l out_shape.append(e)", "network): children = self.raw_children() early = children[\"early\"] late = children[\"late\"]", "is None: out_shape.append(e) else: assert e == l out_shape.append(e) network.create_vw(", "it # AND multiplied by it. Clipping only for the", "(1 - late_gate) + late_vw.variable * late_gate) out_shape = []", "network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", #", "network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network, early_vw,", "== l out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\")", "self.raw_children() early = children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name,", "else: early_gate = 1 - late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\",", "late_gate = T.clip(late_gate, epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False)", "None: out_shape.append(l) elif l is None: out_shape.append(e) else: assert e", "network, early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable", "late_vw.shape): if e is None and l is None: out_shape.append(None)", "_GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network):", "T.clip(late_gate, epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse:", "self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1)", "divide by it # AND multiplied by it. Clipping only", "class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between 2 nodes \"\"\" hyperparameter_names", "late=treeano.core.ChildContainer, ) input_keys = (\"early\", \"late\") def init_state(self, network): children", "assert early_vw.ndim == late_vw.ndim for e, l in zip(early_vw.shape, late_vw.shape):", "network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network, early_vw, late_vw):", "import theano.tensor as T import treeano import treeano.nodes as tn", "= theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between 2", "\"late\") def init_state(self, network): children = self.raw_children() early = children[\"early\"]", "theano import theano.tensor as T import treeano import treeano.nodes as", "late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def", "\"_early_update_scale\", \"update_scale_factor\", # these updates are also multiplied by #", "are also multiplied by # late_gate later on, so rescale", "so rescale them early_gate / late_gate) def GradNetOptimizerInterpolationNode(name, children, early,", "late_gate = treeano.utils.as_fX(late_gate) # NOTE: late gate cannot be 0", "early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys = (\"early\", \"late\") def init_state(self, network):", "multiplied by it. Clipping only for the early gate will", "def init_state(self, network): children = self.raw_children() early = children[\"early\"] late", "them early_gate / late_gate) def GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs):", "+ \"_early_update_scale\", \"update_scale_factor\", # these updates are also multiplied by", "out_shape.append(l) elif l is None: out_shape.append(e) else: assert e ==", "**kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization as bn return", "{\"subtree\": early_subtree, \"cost\": cost_ref}) # NOTE: need separate node to", "= network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate =", "early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable *", "_GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization as", "(\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys = (\"early\",", "late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node = late(name +", "1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate =", "multiplied by # late_gate later on, so rescale them early_gate", "(\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon", "\"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", # these updates", "late_gate) def GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs): \"\"\" interpolates updates", "cost}) early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node = early(name", "def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization as bn return GradNetInterpolationNode(", "late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", # these updates are also", "nodes NOTE: this is a hack to take in node", "\"cost\"} subtree = children[\"subtree\"] cost = children[\"cost\"] cost_ref = tn.ReferenceNode(name", "= tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node = early(name + \"_early\",", "optimizers nodes NOTE: this is a hack to take in", "theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between 2 nodes", "**kwargs): \"\"\" interpolates updates from 2 optimizers nodes NOTE: this", "= network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate = epsilon /", "# late_gate later on, so rescale them early_gate / late_gate)", "GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name + \"_identity\")})", "GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs): \"\"\" interpolates updates from 2", "late, **kwargs): \"\"\" interpolates updates from 2 optimizers nodes NOTE:", "\"cost\": cost_ref}) # NOTE: need separate node to forward hyperparameter", "early = children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\")", "def GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs): \"\"\" interpolates updates from", "early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node = early(name +", "@treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def", "if use_multiplicative_inverse: early_gate = epsilon / late_gate else: early_gate =", "updates are also multiplied by # late_gate later on, so", "as tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates", "cost_ref = tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name +", "\"cost\": cost}) early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node =", "it. Clipping only for the early gate will cause #", "out_shape = [] assert early_vw.ndim == late_vw.ndim for e, l", "\"_early_update_scale\", late_node) early_node = early(name + \"_early\", {\"subtree\": early_subtree, \"cost\":", "e is None: out_shape.append(l) elif l is None: out_shape.append(e) else:", "early_gate = epsilon / late_gate else: early_gate = 1 -", "<gh_stars>10-100 import theano import theano.tensor as T import treeano import", "theano.tensor as T import treeano import treeano.nodes as tn fX", "as T import treeano import treeano.nodes as tn fX =", "treeano.sandbox.nodes import batch_normalization as bn return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name", "\"\"\" interpolates updates from 2 optimizers nodes NOTE: this is", "network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate) # NOTE: late gate cannot", "AND multiplied by it. Clipping only for the early gate", "{\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name + \"_identity\")}) GradualBNNode =", "l in zip(early_vw.shape, late_vw.shape): if e is None and l", "is a hack to take in node constructors as arguments", "\"_late\", {\"subtree\": late_subtree, \"cost\": cost}) early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\",", "= children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name,", "interpolates updates from 2 optimizers nodes NOTE: this is a", "\"\"\" interpolates outputs between 2 nodes \"\"\" hyperparameter_names = (\"late_gate\",)", "+ \"_late_update_scale\", subtree) late_node = late(name + \"_late\", {\"subtree\": late_subtree,", "late gate cannot be 0 because the early gate is", "children[\"cost\"] cost_ref = tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name", "NOTE: this is a hack to take in node constructors", "= [] assert early_vw.ndim == late_vw.ndim for e, l in", "NOTE: need separate node to forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node,", "if e is None and l is None: out_shape.append(None) elif", "only for the early gate will cause # no updates", "l is None: out_shape.append(None) elif e is None: out_shape.append(l) elif", "tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\", subtree)", "late_gate) out_shape = [] assert early_vw.ndim == late_vw.ndim for e,", "bn return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name", "network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate = epsilon / late_gate", "= self.raw_children() early = children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name)", "early_gate = 1 - late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate)", "Clipping only for the early gate will cause # no", "network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", # these updates are also multiplied", "is divide by it # AND multiplied by it. Clipping", "import treeano.nodes as tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl):", "late_vw.variable * late_gate) out_shape = [] assert early_vw.ndim == late_vw.ndim", "network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network, early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"],", "hack to take in node constructors as arguments \"\"\" assert", "e, l in zip(early_vw.shape, late_vw.shape): if e is None and", "1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate) # NOTE:", "to occur. late_gate = T.clip(late_gate, epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter(", "from 2 optimizers nodes NOTE: this is a hack to", "* (1 - late_gate) + late_vw.variable * late_gate) out_shape =", "a hack to take in node constructors as arguments \"\"\"", "= (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network)", ") @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\")", "is None: out_shape.append(l) elif l is None: out_shape.append(e) else: assert", "separate node to forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def", "@treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between 2 nodes \"\"\"", "out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl):", "- late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\",", "shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\",", "late_gate else: early_gate = 1 - late_gate network.set_hyperparameter(self.name + \"_late_update_scale\",", "early gate is divide by it # AND multiplied by", "children, early, late, **kwargs): \"\"\" interpolates updates from 2 optimizers", "to take in node constructors as arguments \"\"\" assert set(children.keys())", "late(name + \"_late\", {\"subtree\": late_subtree, \"cost\": cost}) early_subtree = tn.UpdateScaleNode(name", "variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\",", "+ \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", # these", "out_var = (early_vw.variable * (1 - late_gate) + late_vw.variable *", "init_state(self, network): children = self.raw_children() early = children[\"early\"] late =", "(early_vw.variable * (1 - late_gate) + late_vw.variable * late_gate) out_shape", "= treeano.utils.as_fX(late_gate) # NOTE: late gate cannot be 0 because", "late_node = late(name + \"_late\", {\"subtree\": late_subtree, \"cost\": cost}) early_subtree", "to_key=\"late\") def compute_output(self, network, early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1)", "in node constructors as arguments \"\"\" assert set(children.keys()) == {\"subtree\",", "\"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate) #", "early_gate / late_gate) def GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs): \"\"\"", "node to forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name):", "zip(early_vw.shape, late_vw.shape): if e is None and l is None:", "between 2 nodes \"\"\" hyperparameter_names = (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema(", "\"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\",", "= (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys =", "T import treeano import treeano.nodes as tn fX = theano.config.floatX", ") input_keys = (\"early\", \"late\") def init_state(self, network): children =", "[] assert early_vw.ndim == late_vw.ndim for e, l in zip(early_vw.shape,", "import batch_normalization as bn return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name +", "to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network, early_vw, late_vw): late_gate =", "cost_ref}) # NOTE: need separate node to forward hyperparameter return", "GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between 2 nodes \"\"\" hyperparameter_names =", "rescale them early_gate / late_gate) def GradNetOptimizerInterpolationNode(name, children, early, late,", "= epsilon / late_gate else: early_gate = 1 - late_gate", "use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate = epsilon", "/ late_gate else: early_gate = 1 - late_gate network.set_hyperparameter(self.name +", "tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node = late(name + \"_late\", {\"subtree\":", "treeano.nodes as tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\"", "arguments \"\"\" assert set(children.keys()) == {\"subtree\", \"cost\"} subtree = children[\"subtree\"]", "GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization as bn return GradNetInterpolationNode( name,", "updates from 2 optimizers nodes NOTE: this is a hack", "+ \"_costref\", reference=cost.name) late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node", "1 - late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name +", "assert set(children.keys()) == {\"subtree\", \"cost\"} subtree = children[\"subtree\"] cost =", "= early(name + \"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref}) # NOTE:", "early_node = early(name + \"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref}) #", "name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\": tn.IdentityNode(name + \"_identity\")}) GradualBNNode", "take in node constructors as arguments \"\"\" assert set(children.keys()) ==", "batch_normalization as bn return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"),", "late_gate later on, so rescale them early_gate / late_gate) def", "children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\")", "to forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from", "from treeano.sandbox.nodes import batch_normalization as bn return GradNetInterpolationNode( name, {\"early\":", "outputs between 2 nodes \"\"\" hyperparameter_names = (\"late_gate\",) children_container =", "network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network, early_vw, late_vw): late_gate", "== late_vw.ndim for e, l in zip(early_vw.shape, late_vw.shape): if e", "= network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable * (1 - late_gate)", "= children[\"subtree\"] cost = children[\"cost\"] cost_ref = tn.ReferenceNode(name + \"_costref\",", "= network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate) # NOTE: late gate", "NOTE: late gate cannot be 0 because the early gate", "the early gate is divide by it # AND multiplied", "+ \"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref}) # NOTE: need separate", "constructors as arguments \"\"\" assert set(children.keys()) == {\"subtree\", \"cost\"} subtree", "use_multiplicative_inverse: early_gate = epsilon / late_gate else: early_gate = 1", "e is None and l is None: out_shape.append(None) elif e", "{\"subtree\": late_subtree, \"cost\": cost}) early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\", late_node)", "early(name + \"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref}) # NOTE: need", "\"update_scale_factor\", late_gate) network.set_hyperparameter(self.name + \"_early_update_scale\", \"update_scale_factor\", # these updates are", "[\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate = epsilon / late_gate else:", "network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate =", "1) out_var = (early_vw.variable * (1 - late_gate) + late_vw.variable", "tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node = early(name + \"_early\", {\"subtree\":", "these updates are also multiplied by # late_gate later on,", "\"_late_update_scale\", subtree) late_node = late(name + \"_late\", {\"subtree\": late_subtree, \"cost\":", "= (\"early\", \"late\") def init_state(self, network): children = self.raw_children() early", "early gate will cause # no updates to occur. late_gate", "is None and l is None: out_shape.append(None) elif e is", "0 because the early gate is divide by it #", "forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes", "l out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class", "/ late_gate) def GradNetOptimizerInterpolationNode(name, children, early, late, **kwargs): \"\"\" interpolates", "2 optimizers nodes NOTE: this is a hack to take", "e == l out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, )", "\"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon =", "# NOTE: late gate cannot be 0 because the early", "# NOTE: need separate node to forward hyperparameter return _GradNetOptimizerInterpolationNode(name,", "# no updates to occur. late_gate = T.clip(late_gate, epsilon, 1)", "need separate node to forward hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs)", "children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self, network,", "treeano.utils.as_fX(late_gate) # NOTE: late gate cannot be 0 because the", "{\"subtree\", \"cost\"} subtree = children[\"subtree\"] cost = children[\"cost\"] cost_ref =", "= (early_vw.variable * (1 - late_gate) + late_vw.variable * late_gate)", "in zip(early_vw.shape, late_vw.shape): if e is None and l is", "and l is None: out_shape.append(None) elif e is None: out_shape.append(l)", "= 1 - late_gate network.set_hyperparameter(self.name + \"_late_update_scale\", \"update_scale_factor\", late_gate) network.set_hyperparameter(self.name", "reference=cost.name) late_subtree = tn.UpdateScaleNode(name + \"_late_update_scale\", subtree) late_node = late(name", "as bn return GradNetInterpolationNode( name, {\"early\": bn.SimpleBatchNormalizationNode(name + \"_bn\"), \"late\":", "will cause # no updates to occur. late_gate = T.clip(late_gate,", "is None: out_shape.append(None) elif e is None: out_shape.append(l) elif l", "= children[\"late\"] network.forward_input_to(early.name) network.forward_input_to(late.name) network.take_output_from(early.name, to_key=\"early\") network.take_output_from(late.name, to_key=\"late\") def compute_output(self,", "import treeano import treeano.nodes as tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\")", "epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate", "the early gate will cause # no updates to occur.", "cause # no updates to occur. late_gate = T.clip(late_gate, epsilon,", "by it. Clipping only for the early gate will cause", "\"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names =", "for e, l in zip(early_vw.shape, late_vw.shape): if e is None", "= late(name + \"_late\", {\"subtree\": late_subtree, \"cost\": cost}) early_subtree =", "children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys = (\"early\", \"late\")", "= children[\"cost\"] cost_ref = tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree =", "out_shape.append(e) else: assert e == l out_shape.append(e) network.create_vw( \"default\", variable=out_var,", "else: assert e == l out_shape.append(e) network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape),", "return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization", "input_keys = (\"early\", \"late\") def init_state(self, network): children = self.raw_children()", "epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if use_multiplicative_inverse: early_gate", "network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate)", "late_gate = network.find_hyperparameter([\"late_gate\"], 1) late_gate = treeano.utils.as_fX(late_gate) # NOTE: late", "network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable * (1 - late_gate) +", "hyperparameter return _GradNetOptimizerInterpolationNode(name, early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import", "# these updates are also multiplied by # late_gate later", "by it # AND multiplied by it. Clipping only for", "class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self,", "by # late_gate later on, so rescale them early_gate /", "None: out_shape.append(None) elif e is None: out_shape.append(l) elif l is", "this is a hack to take in node constructors as", "def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3)", "on, so rescale them early_gate / late_gate) def GradNetOptimizerInterpolationNode(name, children,", "cannot be 0 because the early gate is divide by", "late_subtree, \"cost\": cost}) early_subtree = tn.UpdateScaleNode(name + \"_early_update_scale\", late_node) early_node", "hyperparameter_names = (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys", "tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs", "\"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"],", "be 0 because the early gate is divide by it", "* late_gate) out_shape = [] assert early_vw.ndim == late_vw.ndim for", "hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\", \"multiplicative_inverse_for_early_gate\") def init_state(self, network): super(_GradNetOptimizerInterpolationNode,", "= T.clip(late_gate, epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"], False) if", "False) if use_multiplicative_inverse: early_gate = epsilon / late_gate else: early_gate", "init_state(self, network): super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate", "+ \"_early_update_scale\", late_node) early_node = early(name + \"_early\", {\"subtree\": early_subtree,", "subtree) late_node = late(name + \"_late\", {\"subtree\": late_subtree, \"cost\": cost})", "network.create_vw( \"default\", variable=out_var, shape=tuple(out_shape), tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names", "interpolates outputs between 2 nodes \"\"\" hyperparameter_names = (\"late_gate\",) children_container", "late_vw.ndim for e, l in zip(early_vw.shape, late_vw.shape): if e is", "because the early gate is divide by it # AND", "late_node) early_node = early(name + \"_early\", {\"subtree\": early_subtree, \"cost\": cost_ref})", "gate is divide by it # AND multiplied by it.", "compute_output(self, network, early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var =", "tags={\"output\"}, ) @treeano.register_node(\"grad_net_optimizer_interpolation\") class _GradNetOptimizerInterpolationNode(treeano.Wrapper1NodeImpl): hyperparameter_names = (\"late_gate\", \"gradnet_epsilon\", \"epsilon\",", "treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys = (\"early\", \"late\") def init_state(self,", "fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class GradNetInterpolationNode(treeano.NodeImpl): \"\"\" interpolates outputs between", "children[\"subtree\"] cost = children[\"cost\"] cost_ref = tn.ReferenceNode(name + \"_costref\", reference=cost.name)", "elif l is None: out_shape.append(e) else: assert e == l", "node constructors as arguments \"\"\" assert set(children.keys()) == {\"subtree\", \"cost\"}", "late_gate) + late_vw.variable * late_gate) out_shape = [] assert early_vw.ndim", "early_vw.ndim == late_vw.ndim for e, l in zip(early_vw.shape, late_vw.shape): if", "occur. late_gate = T.clip(late_gate, epsilon, 1) use_multiplicative_inverse = network.find_hyperparameter( [\"multiplicative_inverse_for_early_gate\"],", "gate will cause # no updates to occur. late_gate =", "cost = children[\"cost\"] cost_ref = tn.ReferenceNode(name + \"_costref\", reference=cost.name) late_subtree", "= treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer, ) input_keys = (\"early\", \"late\") def", "subtree = children[\"subtree\"] cost = children[\"cost\"] cost_ref = tn.ReferenceNode(name +", "late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable * (1 -", "also multiplied by # late_gate later on, so rescale them", "early_node, **kwargs) def GradualSimpleBatchNormalizationNode(name): from treeano.sandbox.nodes import batch_normalization as bn", "updates to occur. late_gate = T.clip(late_gate, epsilon, 1) use_multiplicative_inverse =", "early_subtree, \"cost\": cost_ref}) # NOTE: need separate node to forward", "def compute_output(self, network, early_vw, late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var", "no updates to occur. late_gate = T.clip(late_gate, epsilon, 1) use_multiplicative_inverse", "early, late, **kwargs): \"\"\" interpolates updates from 2 optimizers nodes", "None and l is None: out_shape.append(None) elif e is None:", "late_vw): late_gate = network.find_hyperparameter([\"late_gate\"], 1) out_var = (early_vw.variable * (1", "elif e is None: out_shape.append(l) elif l is None: out_shape.append(e)", "nodes \"\"\" hyperparameter_names = (\"late_gate\",) children_container = treeano.core.DictChildrenContainerSchema( early=treeano.core.ChildContainer, late=treeano.core.ChildContainer,", "== {\"subtree\", \"cost\"} subtree = children[\"subtree\"] cost = children[\"cost\"] cost_ref", "None: out_shape.append(e) else: assert e == l out_shape.append(e) network.create_vw( \"default\",", "super(_GradNetOptimizerInterpolationNode, self).init_state(network) epsilon = network.find_hyperparameter([\"gradnet_epsilon\", \"epsilon\"], 1e-3) late_gate = network.find_hyperparameter([\"late_gate\"],", "gate cannot be 0 because the early gate is divide", "children = self.raw_children() early = children[\"early\"] late = children[\"late\"] network.forward_input_to(early.name)", "treeano import treeano.nodes as tn fX = theano.config.floatX @treeano.register_node(\"grad_net_interpolation\") class" ]
[ "self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'):", "RawFile(object):#pragma: no cover def __init__(self,filename): self.filename = filename if filename.endswith('.gz'):", "= filename if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle", "= lzma.open(filenaem,'rt') else: self.handle = open(filename,'r') def __enter__(self): return self.handle", "cover import bz2 #pragma: no cover import lzma #pragma: no", "self.handle = lzma.open(filenaem,'rt') else: self.handle = open(filename,'r') def __enter__(self): return", "no cover def __init__(self,filename): self.filename = filename if filename.endswith('.gz'): self.handle", "import bz2 #pragma: no cover import lzma #pragma: no cover", "lzma #pragma: no cover class RawFile(object):#pragma: no cover def __init__(self,filename):", "#pragma: no cover import bz2 #pragma: no cover import lzma", "gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle =", "import gzip #pragma: no cover import bz2 #pragma: no cover", "= bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else: self.handle =", "cover class RawFile(object):#pragma: no cover def __init__(self,filename): self.filename = filename", "no cover class RawFile(object):#pragma: no cover def __init__(self,filename): self.filename =", "else: self.handle = open(filename,'r') def __enter__(self): return self.handle def __exit__(self,dtype,value,traceback):", "bz2 #pragma: no cover import lzma #pragma: no cover class", "bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else: self.handle = open(filename,'r')", "filename if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle =", "self.handle = open(filename,'r') def __enter__(self): return self.handle def __exit__(self,dtype,value,traceback): self.handle.close()", "filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else: self.handle = open(filename,'r') def __enter__(self):", "no cover import bz2 #pragma: no cover import lzma #pragma:", "cover def __init__(self,filename): self.filename = filename if filename.endswith('.gz'): self.handle =", "#pragma: no cover import lzma #pragma: no cover class RawFile(object):#pragma:", "#pragma: no cover class RawFile(object):#pragma: no cover def __init__(self,filename): self.filename", "if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt')", "self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else: self.handle", "import lzma #pragma: no cover class RawFile(object):#pragma: no cover def", "__init__(self,filename): self.filename = filename if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif", "self.filename = filename if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'):", "= gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle", "lzma.open(filenaem,'rt') else: self.handle = open(filename,'r') def __enter__(self): return self.handle def", "def __init__(self,filename): self.filename = filename if filename.endswith('.gz'): self.handle = gzip.open(filename,'rt')", "<filename>minus80/RawFile.py import gzip #pragma: no cover import bz2 #pragma: no", "elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else: self.handle = open(filename,'r') def", "cover import lzma #pragma: no cover class RawFile(object):#pragma: no cover", "gzip #pragma: no cover import bz2 #pragma: no cover import", "class RawFile(object):#pragma: no cover def __init__(self,filename): self.filename = filename if", "filename.endswith('.gz'): self.handle = gzip.open(filename,'rt') elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif", "elif filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt')", "no cover import lzma #pragma: no cover class RawFile(object):#pragma: no", "filename.endswith('bz2'): self.handle = bz2.open(filename,'rt') elif filename.endswith('xz'): self.handle = lzma.open(filenaem,'rt') else:" ]
[ "10_11_6) \" \"AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\",", "(KHTML, like Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\"", "Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\":", "X 10_11_6) \" \"AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/55.0.2883.95 \"", "\" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch,", "Intel Mac OS X 10_11_6) \" \"AppleWebKit/537.36 (KHTML, like Gecko)", "\"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"),", "class BaseConf(object): HEADERS = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac", "\"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\":", "import os class BaseConf(object): HEADERS = { \"User-Agent\": \"Mozilla/5.0 (Macintosh;", "{ \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) \"", "\"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate,", "\"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch, br\",", "-*- coding: utf-8 -*- import os class BaseConf(object): HEADERS =", "(Macintosh; Intel Mac OS X 10_11_6) \" \"AppleWebKit/537.36 (KHTML, like", "\" \"AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\":", "= { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)", "= \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379, db_number=0 ) CURCONF = TestConf", "coding: utf-8 -*- import os class BaseConf(object): HEADERS = {", "\"Accept-Encoding\": \"gzip, deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", }", "sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf): REDIS_URL", "# -*- coding: utf-8 -*- import os class BaseConf(object): HEADERS", "like Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\",", "\"max-age=0\", } class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379,", "\"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\",", "-*- import os class BaseConf(object): HEADERS = { \"User-Agent\": \"Mozilla/5.0", "os class BaseConf(object): HEADERS = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel", "\"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1',", "\" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip,", "\"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format(", "\"AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/55.0.2883.95 \" \"Safari/537.36\", \"Accept\": \"text/html,application/xhtml+xml,application/xml;\"", "\"Accept\": \"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch, br\", \"Accept-Language\":", "utf-8 -*- import os class BaseConf(object): HEADERS = { \"User-Agent\":", "\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) \" \"AppleWebKit/537.36", "<gh_stars>0 # -*- coding: utf-8 -*- import os class BaseConf(object):", "BaseConf(object): HEADERS = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS", "OS X 10_11_6) \" \"AppleWebKit/537.36 (KHTML, like Gecko) \" \"Chrome/55.0.2883.95", "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) \" \"AppleWebKit/537.36 (KHTML,", "TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379, db_number=0 ) CURCONF", "REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379, db_number=0 ) CURCONF =", "HEADERS = { \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X", "class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379, db_number=0 )", "\"text/html,application/xhtml+xml,application/xml;\" \"q=0.9,image/webp,*/*;\" \"q=0.8\", \"Accept-Encoding\": \"gzip, deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\",", "\"gzip, deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class", "br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf): REDIS_URL =", "deflate, sdch, br\", \"Accept-Language\": \"zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4\", \"Cache-Control\": \"max-age=0\", } class TestConf(BaseConf):", "Mac OS X 10_11_6) \" \"AppleWebKit/537.36 (KHTML, like Gecko) \"", "} class TestConf(BaseConf): REDIS_URL = \"redis://:{password}@{hostname}:{port}/{db_number}\".format( password=os.environ.get(\"REDIS_PWD\"), hostname='127.0.0.1', port=6379, db_number=0" ]
[ "@autoload_node def get_node(node): ... \"\"\" @functools.wraps(func) def wrapper(*args, **kwargs): primary_key", "display_name = display_name or '' # FIXME: Not everything that", "message_long='The query must match exactly one {name} record'.format(name=safe_name) )) else:", "the function Example usage: :: def get_node(node_id): node = Node.load(node_id)", "increment=200, each=True, include=None): \"\"\"Paginate a MODM query. :param StoredObject model:", "primary key or modularodm.Q query. Raise an appropriate HTTPError if", "raise HTTPError(http.GONE) return instance def autoload(Model, extract_key, inject_key, func): \"\"\"Decorator", "primary key to be fetched from the database :param basestring", "(see #get_or_http_error) :param type Model: database collection model to query", "by primary key and inject into kwargs. Raises an appropriate", "does not exist :raises: HTTPError(400) if no unique record is", "Model: database collection model to query (should be a subclass", "httplib as http import markupsafe from django.core.paginator import Paginator from", "record, e.g. Q('title', 'eq', 'Entitled') & Q('version', 'eq', 1) :param", "include=None): \"\"\"Paginate a MODM query. :param StoredObject model: Model to", "from django.core.paginator import Paginator from django.db.models import Q, QuerySet from", "paginator.page_range: page = paginator.page(page_num) if each: for item in page.object_list:", "Example usage: :: def get_node(node_id): node = Node.load(node_id) ... becomes", "raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record with that primary key", "\"\"\"Load an instance of Model by primary key or modularodm.Q", "if isinstance(queryset, QuerySet) and not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator", "to be markupsafe, but OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name)", "Q('title', 'eq', 'Entitled') & Q('version', 'eq', 1) :param bool allow_deleted:", "match exactly one {name} record'.format(name=safe_name) )) else: instance = Model.load(pk_or_query)", "def wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key)", "instance def autoload(Model, extract_key, inject_key, func): \"\"\"Decorator to autoload a", "or modularodm.Q query. Raise an appropriate HTTPError if no record", "be found'.format(name=safe_name) )) if getattr(instance, 'is_deleted', False) and getattr(instance, 'suspended',", "else: queryset = model.objects.all() # Pagination requires an order by", "Pagination requires an order by clause, especially when using Postgres.", "is found or if the query fails to find a", ":param basestring display_name: :raises: HTTPError(404) if the record does not", "<basestring> representation of the record's primary key, e.g. 'abcdef' -", "function Example usage: :: def get_node(node_id): node = Node.load(node_id) ...", "get_node(node): ... \"\"\" @functools.wraps(func) def wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key)", "accessible as when it's injected as an argument to the", "raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record matching that query could", "# see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and not queryset.ordered: queryset", "uses this decorator needs to be markupsafe, but OsfWebRenderer error.mako", "does... safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try: instance =", "= markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try: instance = Model.objects.get(pk_or_query) except", "autoload_node = functools.partial(autoload, Node, 'node_id', 'node') @autoload_node def get_node(node): ...", "getattr(instance, 'suspended', False): raise HTTPError(451, data=dict( # 451 - Unavailable", "appropriate HTTPError (see #get_or_http_error) :param type Model: database collection model", "unique record :param type Model: StoredObject subclass to query :param", "from the database :param basestring inject_key: name the instance will", "the query fails to find a unique record :param type", "'is_deleted', False): raise HTTPError(http.GONE) return instance def autoload(Model, extract_key, inject_key,", "primary key and inject into kwargs. Raises an appropriate HTTPError", "HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an instance of", "modularodm.Q query. Raise an appropriate HTTPError if no record is", ":raises: HTTPError(400) if no unique record is found :raises: HTTPError(410)", "bool allow_deleted: allow deleleted records? :param basestring display_name: :raises: HTTPError(404)", "the database :param basestring inject_key: name the instance will be", "query to uniquely select a record, e.g. Q('title', 'eq', 'Entitled')", "record does not exist :raises: HTTPError(400) if no unique record", "with that primary key could be found'.format(name=safe_name) )) if getattr(instance,", "1) :param bool allow_deleted: allow deleleted records? :param basestring display_name:", "each=True, include=None): \"\"\"Paginate a MODM query. :param StoredObject model: Model", "model.objects.all() # Pagination requires an order by clause, especially when", "Model to query. :param Q query: Optional query object. :param", "<QueryBase> subclass query to uniquely select a record, e.g. Q('title',", "http import markupsafe from django.core.paginator import Paginator from django.db.models import", "records? :param basestring display_name: :raises: HTTPError(404) if the record does", "model.objects.filter(query).include(*include) elif query: queryset = model.objects.filter(query) else: queryset = model.objects.all()", "each: for item in page.object_list: yield item else: yield page.object_list", "- a <basestring> representation of the record's primary key, e.g.", "that primary key could be found'.format(name=safe_name) )) if getattr(instance, 'is_deleted',", "an appropriate HTTPError (see #get_or_http_error) :param type Model: database collection", "display_name=None): \"\"\"Load an instance of Model by primary key or", "type Model: StoredObject subclass to query :param pk_or_query: :type pk_or_query:", "paginator = Paginator(queryset.all(), increment) for page_num in paginator.page_range: page =", "a record, e.g. Q('title', 'eq', 'Entitled') & Q('version', 'eq', 1)", "yielded. \"\"\" if include and query: queryset = model.objects.filter(query).include(*include) elif", "Q query: Optional query object. :param int increment: Page size", "if each: for item in page.object_list: yield item else: yield", "but OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query, Q):", "is yielded. If False, pages are yielded. \"\"\" if include", "queryset = model.objects.filter(query) else: queryset = model.objects.all() # Pagination requires", "pk_or_query: either - a <basestring> representation of the record's primary", "wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key) kwargs[inject_key]", "Unavailable For Legal Reasons message_short='Content removed', message_long='This content has been", "If True, each record is yielded. If False, pages are", "inject into kwargs. Raises an appropriate HTTPError (see #get_or_http_error) :param", "message_short='Content removed', message_long='This content has been removed' )) if not", "autoload(Model, extract_key, inject_key, func): \"\"\"Decorator to autoload a StoredObject instance", "False): raise HTTPError(http.GONE) return instance def autoload(Model, extract_key, inject_key, func):", ")) if getattr(instance, 'is_deleted', False) and getattr(instance, 'suspended', False): raise", "FIXME: Not everything that uses this decorator needs to be", "if not instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record with", "import functools import httplib as http import markupsafe from django.core.paginator", "to autoload a StoredObject instance by primary key and inject", "one {name} record'.format(name=safe_name) )) else: instance = Model.load(pk_or_query) if not", "model to query (should be a subclass of StoredObject) :param", "not allow_deleted and getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE) return instance", "not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment) for", "{name} record matching that query could be found'.format(name=safe_name) )) except", "from framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load", "not exist :raises: HTTPError(400) if no unique record is found", "injected as an argument to the function Example usage: ::", "Q): try: instance = Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict(", "argument to the function Example usage: :: def get_node(node_id): node", "and inject into kwargs. Raises an appropriate HTTPError (see #get_or_http_error)", "OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try:", "StoredObject subclass to query :param pk_or_query: :type pk_or_query: either -", "basestring extract_key: named URL field containing the desired primary key", "a MODM query. :param StoredObject model: Model to query. :param", "if getattr(instance, 'is_deleted', False) and getattr(instance, 'suspended', False): raise HTTPError(451,", "message_long='This content has been removed' )) if not allow_deleted and", "= queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment) for page_num in paginator.page_range:", "primary key, e.g. 'abcdef' - a <QueryBase> subclass query to", "requires an order by clause, especially when using Postgres. #", "record'.format(name=safe_name) )) else: instance = Model.load(pk_or_query) if not instance: raise", "Model: StoredObject subclass to query :param pk_or_query: :type pk_or_query: either", "StoredObject) :param basestring extract_key: named URL field containing the desired", "= display_name or '' # FIXME: Not everything that uses", "markupsafe, but OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query,", "utf-8 -*- import functools import httplib as http import markupsafe", "e.g. Q('title', 'eq', 'Entitled') & Q('version', 'eq', 1) :param bool", "when using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and", "if no unique record is found :raises: HTTPError(410) if the", "try: instance = Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No", "the record does not exist :raises: HTTPError(400) if no unique", "key, e.g. 'abcdef' - a <QueryBase> subclass query to uniquely", "data=dict( message_long='No {name} record with that primary key could be", "desired primary key to be fetched from the database :param", "as http import markupsafe from django.core.paginator import Paginator from django.db.models", "HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record matching that query could be", "record's primary key, e.g. 'abcdef' - a <QueryBase> subclass query", "Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must match exactly one", "object. :param int increment: Page size :param bool each: If", "framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an", ":: def get_node(node_id): node = Node.load(node_id) ... becomes import functools", "pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an instance of Model by primary", "to query :param pk_or_query: :type pk_or_query: either - a <basestring>", ":param bool allow_deleted: allow deleleted records? :param basestring display_name: :raises:", "clause, especially when using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset,", "subclass query to uniquely select a record, e.g. Q('title', 'eq',", "uniquely select a record, e.g. Q('title', 'eq', 'Entitled') & Q('version',", "and getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE) return instance def autoload(Model,", "be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query", "if the query fails to find a unique record :param", "page_num in paginator.page_range: page = paginator.page(page_num) if each: for item", "the record's primary key, e.g. 'abcdef' - a <QueryBase> subclass", "page = paginator.page(page_num) if each: for item in page.object_list: yield", "allow deleleted records? :param basestring display_name: :raises: HTTPError(404) if the", "it's injected as an argument to the function Example usage:", "Q('version', 'eq', 1) :param bool allow_deleted: allow deleleted records? :param", "query object. :param int increment: Page size :param bool each:", "fails to find a unique record :param type Model: StoredObject", "if no record is found or if the query fails", ":type pk_or_query: either - a <basestring> representation of the record's", "instance = Model.load(pk_or_query) if not instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No", "= Node.load(node_id) ... becomes import functools autoload_node = functools.partial(autoload, Node,", ":param StoredObject model: Model to query. :param Q query: Optional", "Raise an appropriate HTTPError if no record is found or", "has been removed' )) if not allow_deleted and getattr(instance, 'is_deleted',", "Reasons message_short='Content removed', message_long='This content has been removed' )) if", ":param bool each: If True, each record is yielded. If", "Raises an appropriate HTTPError (see #get_or_http_error) :param type Model: database", "the instance will be accessible as when it's injected as", "or '' # FIXME: Not everything that uses this decorator", "HTTPError(410) if the resource is deleted and allow_deleted = False", "raise HTTPError(451, data=dict( # 451 - Unavailable For Legal Reasons", "... \"\"\" @functools.wraps(func) def wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key) instance", "removed', message_long='This content has been removed' )) if not allow_deleted", "bool each: If True, each record is yielded. If False,", "include and query: queryset = model.objects.filter(query).include(*include) elif query: queryset =", "queryset = model.objects.all() # Pagination requires an order by clause,", "'eq', 'Entitled') & Q('version', 'eq', 1) :param bool allow_deleted: allow", "HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record with that primary key could", "-*- import functools import httplib as http import markupsafe from", "extract_key: named URL field containing the desired primary key to", "of StoredObject) :param basestring extract_key: named URL field containing the", "and allow_deleted = False :return: Model instance \"\"\" display_name =", "return func(*args, **kwargs) return wrapper def paginated(model, query=None, increment=200, each=True,", "record :param type Model: StoredObject subclass to query :param pk_or_query:", "getattr(instance, 'is_deleted', False) and getattr(instance, 'suspended', False): raise HTTPError(451, data=dict(", "functools autoload_node = functools.partial(autoload, Node, 'node_id', 'node') @autoload_node def get_node(node):", "a unique record :param type Model: StoredObject subclass to query", "= functools.partial(autoload, Node, 'node_id', 'node') @autoload_node def get_node(node): ... \"\"\"", "instance = Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name}", "if the record does not exist :raises: HTTPError(400) if no", "found :raises: HTTPError(410) if the resource is deleted and allow_deleted", "Node.load(node_id) ... becomes import functools autoload_node = functools.partial(autoload, Node, 'node_id',", "if not allow_deleted and getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE) return", "to be fetched from the database :param basestring inject_key: name", "& Q('version', 'eq', 1) :param bool allow_deleted: allow deleleted records?", "select a record, e.g. Q('title', 'eq', 'Entitled') & Q('version', 'eq',", "Paginator(queryset.all(), increment) for page_num in paginator.page_range: page = paginator.page(page_num) if", "def get_node(node_id): node = Node.load(node_id) ... becomes import functools autoload_node", "query: queryset = model.objects.filter(query) else: queryset = model.objects.all() # Pagination", "# -*- coding: utf-8 -*- import functools import httplib as", "query. Raise an appropriate HTTPError if no record is found", "the desired primary key to be fetched from the database", "primary key could be found'.format(name=safe_name) )) if getattr(instance, 'is_deleted', False)", "an order by clause, especially when using Postgres. # see:", "False :return: Model instance \"\"\" display_name = display_name or ''", "not instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record with that", "kwargs[inject_key] = instance return func(*args, **kwargs) return wrapper def paginated(model,", "a StoredObject instance by primary key and inject into kwargs.", "@functools.wraps(func) def wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key) instance = get_or_http_error(Model,", "instance return func(*args, **kwargs) return wrapper def paginated(model, query=None, increment=200,", "<filename>framework/database/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- import functools import httplib", "functools.partial(autoload, Node, 'node_id', 'node') @autoload_node def get_node(node): ... \"\"\" @functools.wraps(func)", "yielded. If False, pages are yielded. \"\"\" if include and", "query must match exactly one {name} record'.format(name=safe_name) )) else: instance", "a <basestring> representation of the record's primary key, e.g. 'abcdef'", "order by clause, especially when using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments", "query: queryset = model.objects.filter(query).include(*include) elif query: queryset = model.objects.filter(query) else:", "are yielded. \"\"\" if include and query: queryset = model.objects.filter(query).include(*include)", "- Unavailable For Legal Reasons message_short='Content removed', message_long='This content has", "markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try: instance = Model.objects.get(pk_or_query) except Model.DoesNotExist:", "field containing the desired primary key to be fetched from", "instance by primary key and inject into kwargs. Raises an", "get_or_http_error(Model, primary_key) kwargs[inject_key] = instance return func(*args, **kwargs) return wrapper", "int increment: Page size :param bool each: If True, each", "instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record with that primary", "get_node(node_id): node = Node.load(node_id) ... becomes import functools autoload_node =", ":param Q query: Optional query object. :param int increment: Page", "\"\"\"Decorator to autoload a StoredObject instance by primary key and", "if isinstance(pk_or_query, Q): try: instance = Model.objects.get(pk_or_query) except Model.DoesNotExist: raise", "\"\"\" display_name = display_name or '' # FIXME: Not everything", "or if the query fails to find a unique record", "HTTPError(404) if the record does not exist :raises: HTTPError(400) if", "find a unique record :param type Model: StoredObject subclass to", ":raises: HTTPError(404) if the record does not exist :raises: HTTPError(400)", "either - a <basestring> representation of the record's primary key,", "removed' )) if not allow_deleted and getattr(instance, 'is_deleted', False): raise", "using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and not", "an argument to the function Example usage: :: def get_node(node_id):", "record with that primary key could be found'.format(name=safe_name) )) if", "def paginated(model, query=None, increment=200, each=True, include=None): \"\"\"Paginate a MODM query.", "instance will be accessible as when it's injected as an", "= model.objects.filter(query) else: queryset = model.objects.all() # Pagination requires an", "containing the desired primary key to be fetched from the", "queryset = model.objects.filter(query).include(*include) elif query: queryset = model.objects.filter(query) else: queryset", "query (should be a subclass of StoredObject) :param basestring extract_key:", "primary_key) kwargs[inject_key] = instance return func(*args, **kwargs) return wrapper def", "instance of Model by primary key or modularodm.Q query. Raise", "be fetched from the database :param basestring inject_key: name the", "query. :param Q query: Optional query object. :param int increment:", "especially when using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet)", "inject_key, func): \"\"\"Decorator to autoload a StoredObject instance by primary", "django.db.models import Q, QuerySet from framework.exceptions import HTTPError def get_or_http_error(Model,", "safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try: instance = Model.objects.get(pk_or_query)", "must match exactly one {name} record'.format(name=safe_name) )) else: instance =", "def autoload(Model, extract_key, inject_key, func): \"\"\"Decorator to autoload a StoredObject", "by clause, especially when using Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if", ")) else: instance = Model.load(pk_or_query) if not instance: raise HTTPError(http.NOT_FOUND,", "for page_num in paginator.page_range: page = paginator.page(page_num) if each: for", "exist :raises: HTTPError(400) if no unique record is found :raises:", "return wrapper def paginated(model, query=None, increment=200, each=True, include=None): \"\"\"Paginate a", "key and inject into kwargs. Raises an appropriate HTTPError (see", "allow_deleted and getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE) return instance def", "basestring display_name: :raises: HTTPError(404) if the record does not exist", "pages are yielded. \"\"\" if include and query: queryset =", "query: Optional query object. :param int increment: Page size :param", "needs to be markupsafe, but OsfWebRenderer error.mako does... safe_name =", "key or modularodm.Q query. Raise an appropriate HTTPError if no", "allow_deleted=False, display_name=None): \"\"\"Load an instance of Model by primary key", "markupsafe from django.core.paginator import Paginator from django.db.models import Q, QuerySet", "no record is found or if the query fails to", "instance = get_or_http_error(Model, primary_key) kwargs[inject_key] = instance return func(*args, **kwargs)", "kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key) kwargs[inject_key] = instance return func(*args,", "into kwargs. Raises an appropriate HTTPError (see #get_or_http_error) :param type", "import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an instance", "HTTPError(451, data=dict( # 451 - Unavailable For Legal Reasons message_short='Content", "= paginator.page(page_num) if each: for item in page.object_list: yield item", "HTTPError(http.GONE) return instance def autoload(Model, extract_key, inject_key, func): \"\"\"Decorator to", "... becomes import functools autoload_node = functools.partial(autoload, Node, 'node_id', 'node')", "been removed' )) if not allow_deleted and getattr(instance, 'is_deleted', False):", "Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record matching that query", ":param pk_or_query: :type pk_or_query: either - a <basestring> representation of", "HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must match exactly one {name} record'.format(name=safe_name)", "primary_key = kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key) kwargs[inject_key] = instance", "instance \"\"\" display_name = display_name or '' # FIXME: Not", "For Legal Reasons message_short='Content removed', message_long='This content has been removed'", "model.objects.filter(query) else: queryset = model.objects.all() # Pagination requires an order", "error.mako does... safe_name = markupsafe.escape(display_name) if isinstance(pk_or_query, Q): try: instance", "= kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key) kwargs[inject_key] = instance return", "query. :param StoredObject model: Model to query. :param Q query:", "\"\"\"Paginate a MODM query. :param StoredObject model: Model to query.", "no unique record is found :raises: HTTPError(410) if the resource", "each: If True, each record is yielded. If False, pages", "Model.load(pk_or_query) if not instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record", "MODM query. :param StoredObject model: Model to query. :param Q", "= model.objects.filter(query).include(*include) elif query: queryset = model.objects.filter(query) else: queryset =", "subclass of StoredObject) :param basestring extract_key: named URL field containing", "key to be fetched from the database :param basestring inject_key:", "fetched from the database :param basestring inject_key: name the instance", "as an argument to the function Example usage: :: def", "autoload a StoredObject instance by primary key and inject into", "as when it's injected as an argument to the function", "https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name)", "database collection model to query (should be a subclass of", "\"\"\" @functools.wraps(func) def wrapper(*args, **kwargs): primary_key = kwargs.get(extract_key) instance =", "paginated(model, query=None, increment=200, each=True, include=None): \"\"\"Paginate a MODM query. :param", "queryset = queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment) for page_num in", "queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment) for page_num", "type Model: database collection model to query (should be a", "wrapper def paginated(model, query=None, increment=200, each=True, include=None): \"\"\"Paginate a MODM", "by primary key or modularodm.Q query. Raise an appropriate HTTPError", "StoredObject instance by primary key and inject into kwargs. Raises", "of the record's primary key, e.g. 'abcdef' - a <QueryBase>", "raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must match exactly one {name}", "that query could be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST,", "Page size :param bool each: If True, each record is", "import markupsafe from django.core.paginator import Paginator from django.db.models import Q,", "e.g. 'abcdef' - a <QueryBase> subclass query to uniquely select", "Postgres. # see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and not queryset.ordered:", "record matching that query could be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned:", ":param basestring extract_key: named URL field containing the desired primary", ")) if not allow_deleted and getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE)", "django.core.paginator import Paginator from django.db.models import Q, QuerySet from framework.exceptions", "query fails to find a unique record :param type Model:", "= False :return: Model instance \"\"\" display_name = display_name or", "elif query: queryset = model.objects.filter(query) else: queryset = model.objects.all() #", "extract_key, inject_key, func): \"\"\"Decorator to autoload a StoredObject instance by", "to uniquely select a record, e.g. Q('title', 'eq', 'Entitled') &", "Model instance \"\"\" display_name = display_name or '' # FIXME:", "an appropriate HTTPError if no record is found or if", ":param type Model: StoredObject subclass to query :param pk_or_query: :type", "If False, pages are yielded. \"\"\" if include and query:", "representation of the record's primary key, e.g. 'abcdef' - a", "HTTPError(400) if no unique record is found :raises: HTTPError(410) if", "this decorator needs to be markupsafe, but OsfWebRenderer error.mako does...", "except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record matching that", "of Model by primary key or modularodm.Q query. Raise an", "isinstance(queryset, QuerySet) and not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator =", "QuerySet) and not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(),", "HTTPError if no record is found or if the query", "message_long='No {name} record with that primary key could be found'.format(name=safe_name)", "from django.db.models import Q, QuerySet from framework.exceptions import HTTPError def", "message_long='No {name} record matching that query could be found'.format(name=safe_name) ))", "is found :raises: HTTPError(410) if the resource is deleted and", "appropriate HTTPError if no record is found or if the", "deleleted records? :param basestring display_name: :raises: HTTPError(404) if the record", "be a subclass of StoredObject) :param basestring extract_key: named URL", "resource is deleted and allow_deleted = False :return: Model instance", "False): raise HTTPError(451, data=dict( # 451 - Unavailable For Legal", "coding: utf-8 -*- import functools import httplib as http import", "display_name: :raises: HTTPError(404) if the record does not exist :raises:", "kwargs. Raises an appropriate HTTPError (see #get_or_http_error) :param type Model:", "import Q, QuerySet from framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query,", ")) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must match", "'abcdef' - a <QueryBase> subclass query to uniquely select a", "to query. :param Q query: Optional query object. :param int", "'node_id', 'node') @autoload_node def get_node(node): ... \"\"\" @functools.wraps(func) def wrapper(*args,", "func): \"\"\"Decorator to autoload a StoredObject instance by primary key", "else: instance = Model.load(pk_or_query) if not instance: raise HTTPError(http.NOT_FOUND, data=dict(", "data=dict( message_long='No {name} record matching that query could be found'.format(name=safe_name)", ":param basestring inject_key: name the instance will be accessible as", "found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must", "query=None, increment=200, each=True, include=None): \"\"\"Paginate a MODM query. :param StoredObject", "allow_deleted: allow deleleted records? :param basestring display_name: :raises: HTTPError(404) if", "False, pages are yielded. \"\"\" if include and query: queryset", "be markupsafe, but OsfWebRenderer error.mako does... safe_name = markupsafe.escape(display_name) if", ":raises: HTTPError(410) if the resource is deleted and allow_deleted =", "and query: queryset = model.objects.filter(query).include(*include) elif query: queryset = model.objects.filter(query)", "to the function Example usage: :: def get_node(node_id): node =", "# FIXME: Not everything that uses this decorator needs to", "(should be a subclass of StoredObject) :param basestring extract_key: named", "get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an instance of Model by", "{name} record'.format(name=safe_name) )) else: instance = Model.load(pk_or_query) if not instance:", "import Paginator from django.db.models import Q, QuerySet from framework.exceptions import", "matching that query could be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise", "HTTPError (see #get_or_http_error) :param type Model: database collection model to", "\"\"\" if include and query: queryset = model.objects.filter(query).include(*include) elif query:", "'node') @autoload_node def get_node(node): ... \"\"\" @functools.wraps(func) def wrapper(*args, **kwargs):", "query could be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict(", "= get_or_http_error(Model, primary_key) kwargs[inject_key] = instance return func(*args, **kwargs) return", "functools import httplib as http import markupsafe from django.core.paginator import", "# Pagination requires an order by clause, especially when using", "see: https://docs.djangoproject.com/en/1.10/topics/pagination/#required-arguments if isinstance(queryset, QuerySet) and not queryset.ordered: queryset =", "StoredObject model: Model to query. :param Q query: Optional query", "Paginator from django.db.models import Q, QuerySet from framework.exceptions import HTTPError", "collection model to query (should be a subclass of StoredObject)", "= Model.load(pk_or_query) if not instance: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name}", "record is yielded. If False, pages are yielded. \"\"\" if", "a <QueryBase> subclass query to uniquely select a record, e.g.", "size :param bool each: If True, each record is yielded.", "'suspended', False): raise HTTPError(451, data=dict( # 451 - Unavailable For", "content has been removed' )) if not allow_deleted and getattr(instance,", "Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record matching", "Legal Reasons message_short='Content removed', message_long='This content has been removed' ))", "and not queryset.ordered: queryset = queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment)", "decorator needs to be markupsafe, but OsfWebRenderer error.mako does... safe_name", "becomes import functools autoload_node = functools.partial(autoload, Node, 'node_id', 'node') @autoload_node", "'' # FIXME: Not everything that uses this decorator needs", "'eq', 1) :param bool allow_deleted: allow deleleted records? :param basestring", "and getattr(instance, 'suspended', False): raise HTTPError(451, data=dict( # 451 -", "increment: Page size :param bool each: If True, each record", "#get_or_http_error) :param type Model: database collection model to query (should", "could be found'.format(name=safe_name) )) if getattr(instance, 'is_deleted', False) and getattr(instance,", "found or if the query fails to find a unique", "model: Model to query. :param Q query: Optional query object.", "deleted and allow_deleted = False :return: Model instance \"\"\" display_name", "basestring inject_key: name the instance will be accessible as when", "'is_deleted', False) and getattr(instance, 'suspended', False): raise HTTPError(451, data=dict( #", "queryset.order_by(queryset.model._meta.pk.name) paginator = Paginator(queryset.all(), increment) for page_num in paginator.page_range: page", "False) and getattr(instance, 'suspended', False): raise HTTPError(451, data=dict( # 451", "return instance def autoload(Model, extract_key, inject_key, func): \"\"\"Decorator to autoload", "= model.objects.all() # Pagination requires an order by clause, especially", "import httplib as http import markupsafe from django.core.paginator import Paginator", "except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The query must match exactly", "to query (should be a subclass of StoredObject) :param basestring", "query :param pk_or_query: :type pk_or_query: either - a <basestring> representation", "increment) for page_num in paginator.page_range: page = paginator.page(page_num) if each:", "inject_key: name the instance will be accessible as when it's", "Optional query object. :param int increment: Page size :param bool", "Node, 'node_id', 'node') @autoload_node def get_node(node): ... \"\"\" @functools.wraps(func) def", "usage: :: def get_node(node_id): node = Node.load(node_id) ... becomes import", ":param type Model: database collection model to query (should be", "key could be found'.format(name=safe_name) )) if getattr(instance, 'is_deleted', False) and", "display_name or '' # FIXME: Not everything that uses this", "when it's injected as an argument to the function Example", "**kwargs): primary_key = kwargs.get(extract_key) instance = get_or_http_error(Model, primary_key) kwargs[inject_key] =", "def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None): \"\"\"Load an instance of Model", "import functools autoload_node = functools.partial(autoload, Node, 'node_id', 'node') @autoload_node def", "getattr(instance, 'is_deleted', False): raise HTTPError(http.GONE) return instance def autoload(Model, extract_key,", "URL field containing the desired primary key to be fetched", "= instance return func(*args, **kwargs) return wrapper def paginated(model, query=None,", ":return: Model instance \"\"\" display_name = display_name or '' #", "{name} record with that primary key could be found'.format(name=safe_name) ))", "each record is yielded. If False, pages are yielded. \"\"\"", "pk_or_query: :type pk_or_query: either - a <basestring> representation of the", "unique record is found :raises: HTTPError(410) if the resource is", "**kwargs) return wrapper def paginated(model, query=None, increment=200, each=True, include=None): \"\"\"Paginate", "in paginator.page_range: page = paginator.page(page_num) if each: for item in", "Model by primary key or modularodm.Q query. Raise an appropriate", "Q, QuerySet from framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False,", "be accessible as when it's injected as an argument to", "- a <QueryBase> subclass query to uniquely select a record,", ":param int increment: Page size :param bool each: If True,", "func(*args, **kwargs) return wrapper def paginated(model, query=None, increment=200, each=True, include=None):", "allow_deleted = False :return: Model instance \"\"\" display_name = display_name", "paginator.page(page_num) if each: for item in page.object_list: yield item else:", "that uses this decorator needs to be markupsafe, but OsfWebRenderer", "could be found'.format(name=safe_name) )) except Model.MultipleObjectsReturned: raise HTTPError(http.BAD_REQUEST, data=dict( message_long='The", "record is found or if the query fails to find", "the resource is deleted and allow_deleted = False :return: Model", "QuerySet from framework.exceptions import HTTPError def get_or_http_error(Model, pk_or_query, allow_deleted=False, display_name=None):", "will be accessible as when it's injected as an argument", "True, each record is yielded. If False, pages are yielded.", "an instance of Model by primary key or modularodm.Q query.", "is deleted and allow_deleted = False :return: Model instance \"\"\"", "= Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND, data=dict( message_long='No {name} record", "found'.format(name=safe_name) )) if getattr(instance, 'is_deleted', False) and getattr(instance, 'suspended', False):", "to find a unique record :param type Model: StoredObject subclass", "def get_node(node): ... \"\"\" @functools.wraps(func) def wrapper(*args, **kwargs): primary_key =", "-*- coding: utf-8 -*- import functools import httplib as http", "exactly one {name} record'.format(name=safe_name) )) else: instance = Model.load(pk_or_query) if", "data=dict( # 451 - Unavailable For Legal Reasons message_short='Content removed',", "data=dict( message_long='The query must match exactly one {name} record'.format(name=safe_name) ))", "node = Node.load(node_id) ... becomes import functools autoload_node = functools.partial(autoload,", "database :param basestring inject_key: name the instance will be accessible", "name the instance will be accessible as when it's injected", "= Paginator(queryset.all(), increment) for page_num in paginator.page_range: page = paginator.page(page_num)", "record is found :raises: HTTPError(410) if the resource is deleted", "# 451 - Unavailable For Legal Reasons message_short='Content removed', message_long='This", "if the resource is deleted and allow_deleted = False :return:", "everything that uses this decorator needs to be markupsafe, but", "if include and query: queryset = model.objects.filter(query).include(*include) elif query: queryset", "named URL field containing the desired primary key to be", "'Entitled') & Q('version', 'eq', 1) :param bool allow_deleted: allow deleleted", "Not everything that uses this decorator needs to be markupsafe,", "a subclass of StoredObject) :param basestring extract_key: named URL field", "isinstance(pk_or_query, Q): try: instance = Model.objects.get(pk_or_query) except Model.DoesNotExist: raise HTTPError(http.NOT_FOUND,", "subclass to query :param pk_or_query: :type pk_or_query: either - a", "451 - Unavailable For Legal Reasons message_short='Content removed', message_long='This content" ]
[ "Creates a new Image. :param name: Name of the image,", "2.0 (the \"License\"); # you may not use this file", "name, description, data): \"\"\" Creates a new Image. :param name:", "dashboard. :param data: Image data. :type name: unicode :type description:", "tab on job's dashboard. :param description: Description of the image", "\"\"\" Gets name of this Image. :return: The name of", "on job's dashboard. :param description: Description of the image displayed", "# # Copyright (c) 2016, deepsense.io # # Licensed under", "standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position from future.builtins import object import", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Channels tab on job's dashboard. :param data: Image data. :type", "unicode :type description: unicode :type data: PIL.Image \"\"\" self._name =", "Name of the image, displayed in the Channels tab on", "under the License. # from future import standard_library standard_library.install_aliases() #", "self._description = description self._data = data def to_input_image(self): \"\"\" Creates", "def name(self): \"\"\" Gets name of this Image. :return: The", "@property def description(self): \"\"\" Gets description of this Image. :return:", "input_image = InputImage() input_image.name = self.name input_image.description = self.description input_image.data", "text_conv, validate ) class Image(object): \"\"\" Represents information about images", "name: Name of the image, displayed in the Channels tab", "use this file except in compliance with the License. #", "\"\"\" return self._name @property def description(self): \"\"\" Gets description of", "format appropriate to be sent to Neptune. :rtype: InputImage \"\"\"", "this Image. :rtype: str \"\"\" return self._description @property def data(self):", "def data(self): \"\"\" Gets data of this Image. :return: The", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "-*- # # Copyright (c) 2016, deepsense.io # # Licensed", "License. # You may obtain a copy of the License", "from future import standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position from future.builtins", "standard_library.install_aliases() # pylint: disable=wrong-import-position from future.builtins import object import base64", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "limitations under the License. # from future import standard_library standard_library.install_aliases()", "of this Image. :return: The description of this Image. :rtype:", "# Copyright (c) 2016, deepsense.io # # Licensed under the", ":rtype: str \"\"\" return self._name @property def description(self): \"\"\" Gets", "# limitations under the License. # from future import standard_library", "Image. :rtype: str \"\"\" return self._name @property def description(self): \"\"\"", "def __init__(self, name, description, data): \"\"\" Creates a new Image.", "information about images sent to image channels. \"\"\" @validate(name=text_conv, description=text_conv,", "image in format appropriate to be sent to Neptune. :rtype:", "in compliance with the License. # You may obtain a", "of this Image. :rtype: str \"\"\" return self._name @property def", "software # distributed under the License is distributed on an", "description(self): \"\"\" Gets description of this Image. :return: The description", "description self._data = data def to_input_image(self): \"\"\" Creates InputImage that", "Channels tab on job's dashboard. :param description: Description of the", "self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue() image_buffer.close() input_image = InputImage() input_image.name", "Description of the image displayed in the Channels tab on", "of_type_validator, text_conv, validate ) class Image(object): \"\"\" Represents information about", "description, data): \"\"\" Creates a new Image. :param name: Name", "Image. :return: The name of this Image. :rtype: str \"\"\"", "displayed in the Channels tab on job's dashboard. :param description:", "that can be sent to Neptune. :return: input image in", "\"\"\" return self._description @property def data(self): \"\"\" Gets data of", "self._name = name self._description = description self._data = data def", "image_buffer.close() input_image = InputImage() input_image.name = self.name input_image.description = self.description", "= io.BytesIO() self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue() image_buffer.close() input_image =", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "to in writing, software # distributed under the License is", "# See the License for the specific language governing permissions", "Neptune. :return: input image in format appropriate to be sent", "language governing permissions and # limitations under the License. #", "or agreed to in writing, software # distributed under the", "-*- coding: utf-8 -*- # # Copyright (c) 2016, deepsense.io", "required by applicable law or agreed to in writing, software", "disable=wrong-import-position from future.builtins import object import base64 import io import", "import io import PIL.Image from neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation", "\"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue() image_buffer.close()", "@property def name(self): \"\"\" Gets name of this Image. :return:", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description, data):", "io.BytesIO() self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue() image_buffer.close() input_image = InputImage()", ":param name: Name of the image, displayed in the Channels", "to Neptune. :return: input image in format appropriate to be", "validate ) class Image(object): \"\"\" Represents information about images sent", "from neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv,", "input_image @property def name(self): \"\"\" Gets name of this Image.", "Gets description of this Image. :return: The description of this", "compliance with the License. # You may obtain a copy", "<reponame>jiji-online/neptune-cli # -*- coding: utf-8 -*- # # Copyright (c)", "agreed to in writing, software # distributed under the License", "data(self): \"\"\" Gets data of this Image. :return: The data", "Neptune. :rtype: InputImage \"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG') contents", "distributed under the License is distributed on an \"AS IS\"", "class Image(object): \"\"\" Represents information about images sent to image", ":type description: unicode :type data: PIL.Image \"\"\" self._name = name", "job's dashboard. :param data: Image data. :type name: unicode :type", "this Image. :return: The data of this Image. :rtype: PIL.Image", "image displayed in the Channels tab on job's dashboard. :param", "name of this Image. :rtype: str \"\"\" return self._name @property", "# pylint: disable=wrong-import-position from future.builtins import object import base64 import", "express or implied. # See the License for the specific", "appropriate to be sent to Neptune. :rtype: InputImage \"\"\" image_buffer", "except in compliance with the License. # You may obtain", ":type name: unicode :type description: unicode :type data: PIL.Image \"\"\"", "str \"\"\" return self._name @property def description(self): \"\"\" Gets description", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "format='PNG') contents = image_buffer.getvalue() image_buffer.close() input_image = InputImage() input_image.name =", "\"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description, data): \"\"\"", "not use this file except in compliance with the License.", "of the image, displayed in the Channels tab on job's", "PIL.Image \"\"\" self._name = name self._description = description self._data =", "new Image. :param name: Name of the image, displayed in", "= base64.b64encode(contents).decode('utf-8') return input_image @property def name(self): \"\"\" Gets name", "writing, software # distributed under the License is distributed on", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "about images sent to image channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image))", "of the image displayed in the Channels tab on job's", ":param description: Description of the image displayed in the Channels", "\"\"\" Gets description of this Image. :return: The description of", "CONDITIONS OF ANY KIND, either express or implied. # See", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "displayed in the Channels tab on job's dashboard. :param data:", "\"\"\" Represents information about images sent to image channels. \"\"\"", "tab on job's dashboard. :param data: Image data. :type name:", "The description of this Image. :rtype: str \"\"\" return self._description", "import ( of_type_validator, text_conv, validate ) class Image(object): \"\"\" Represents", "= name self._description = description self._data = data def to_input_image(self):", "\"\"\" self._name = name self._description = description self._data = data", "pylint: disable=wrong-import-position from future.builtins import object import base64 import io", "data): \"\"\" Creates a new Image. :param name: Name of", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= self.description input_image.data = base64.b64encode(contents).decode('utf-8') return input_image @property def name(self):", "the License is distributed on an \"AS IS\" BASIS, #", "dashboard. :param description: Description of the image displayed in the", "self.description input_image.data = base64.b64encode(contents).decode('utf-8') return input_image @property def name(self): \"\"\"", "image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue() image_buffer.close() input_image", "future import standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position from future.builtins import", "name: unicode :type description: unicode :type data: PIL.Image \"\"\" self._name", "input_image.description = self.description input_image.data = base64.b64encode(contents).decode('utf-8') return input_image @property def", "the image displayed in the Channels tab on job's dashboard.", "io import PIL.Image from neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation import", "Image data. :type name: unicode :type description: unicode :type data:", "License. # from future import standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position", "law or agreed to in writing, software # distributed under", "can be sent to Neptune. :return: input image in format", ":return: The description of this Image. :rtype: str \"\"\" return", "import PIL.Image from neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation import (", "this Image. :return: The description of this Image. :rtype: str", "data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description, data): \"\"\" Creates a new", ":param data: Image data. :type name: unicode :type description: unicode", "self._description @property def data(self): \"\"\" Gets data of this Image.", "= image_buffer.getvalue() image_buffer.close() input_image = InputImage() input_image.name = self.name input_image.description", "may obtain a copy of the License at # #", "description: unicode :type data: PIL.Image \"\"\" self._name = name self._description", "contents = image_buffer.getvalue() image_buffer.close() input_image = InputImage() input_image.name = self.name", "this Image. :rtype: str \"\"\" return self._name @property def description(self):", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "this Image. :return: The name of this Image. :rtype: str", "may not use this file except in compliance with the", "input image in format appropriate to be sent to Neptune.", "def description(self): \"\"\" Gets description of this Image. :return: The", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "of this Image. :return: The data of this Image. :rtype:", "Image. :rtype: str \"\"\" return self._description @property def data(self): \"\"\"", "this file except in compliance with the License. # You", "import standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position from future.builtins import object", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "data of this Image. :return: The data of this Image.", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "= description self._data = data def to_input_image(self): \"\"\" Creates InputImage", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", ":rtype: InputImage \"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG') contents =", "Gets name of this Image. :return: The name of this", "Copyright (c) 2016, deepsense.io # # Licensed under the Apache", "base64.b64encode(contents).decode('utf-8') return input_image @property def name(self): \"\"\" Gets name of", "return self._description @property def data(self): \"\"\" Gets data of this", "base64 import io import PIL.Image from neptune.generated.swagger_client import InputImage from", ") class Image(object): \"\"\" Represents information about images sent to", "be sent to Neptune. :rtype: InputImage \"\"\" image_buffer = io.BytesIO()", "Image. :return: The data of this Image. :rtype: PIL.Image \"\"\"", "Creates InputImage that can be sent to Neptune. :return: input", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "sent to Neptune. :return: input image in format appropriate to", "\"\"\" Gets data of this Image. :return: The data of", "neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv, validate", ":return: The name of this Image. :rtype: str \"\"\" return", "or implied. # See the License for the specific language", "to_input_image(self): \"\"\" Creates InputImage that can be sent to Neptune.", "Gets data of this Image. :return: The data of this", "self._data = data def to_input_image(self): \"\"\" Creates InputImage that can", "description of this Image. :rtype: str \"\"\" return self._description @property", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "to Neptune. :rtype: InputImage \"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG')", "input_image.data = base64.b64encode(contents).decode('utf-8') return input_image @property def name(self): \"\"\" Gets", "# -*- coding: utf-8 -*- # # Copyright (c) 2016,", "name(self): \"\"\" Gets name of this Image. :return: The name", "import InputImage from neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv, validate )", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "on job's dashboard. :param data: Image data. :type name: unicode", "(the \"License\"); # you may not use this file except", "from neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv, validate ) class Image(object):", "# you may not use this file except in compliance", "@property def data(self): \"\"\" Gets data of this Image. :return:", "of this Image. :rtype: str \"\"\" return self._description @property def", "neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv, validate ) class Image(object): \"\"\"", "= data def to_input_image(self): \"\"\" Creates InputImage that can be", "InputImage \"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer, format='PNG') contents = image_buffer.getvalue()", "# # Unless required by applicable law or agreed to", "# from future import standard_library standard_library.install_aliases() # pylint: disable=wrong-import-position from", "Image. :return: The description of this Image. :rtype: str \"\"\"", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "data. :type name: unicode :type description: unicode :type data: PIL.Image", "Version 2.0 (the \"License\"); # you may not use this", "Image(object): \"\"\" Represents information about images sent to image channels.", "PIL.Image from neptune.generated.swagger_client import InputImage from neptune.internal.common.models.parameters_validation import ( of_type_validator,", "implied. # See the License for the specific language governing", "in the Channels tab on job's dashboard. :param data: Image", "str \"\"\" return self._description @property def data(self): \"\"\" Gets data", "under the Apache License, Version 2.0 (the \"License\"); # you", "image_buffer.getvalue() image_buffer.close() input_image = InputImage() input_image.name = self.name input_image.description =", "name self._description = description self._data = data def to_input_image(self): \"\"\"", "description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description, data): \"\"\" Creates a", "return self._name @property def description(self): \"\"\" Gets description of this", "by applicable law or agreed to in writing, software #", "import object import base64 import io import PIL.Image from neptune.generated.swagger_client", "\"\"\" Creates InputImage that can be sent to Neptune. :return:", "future.builtins import object import base64 import io import PIL.Image from", "data def to_input_image(self): \"\"\" Creates InputImage that can be sent", "images sent to image channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def", "import base64 import io import PIL.Image from neptune.generated.swagger_client import InputImage", "permissions and # limitations under the License. # from future", "image, displayed in the Channels tab on job's dashboard. :param", "@validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description, data): \"\"\" Creates", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Unless required by applicable law or agreed to in writing,", "unicode :type data: PIL.Image \"\"\" self._name = name self._description =", "the specific language governing permissions and # limitations under the", "applicable law or agreed to in writing, software # distributed", "The data of this Image. :rtype: PIL.Image \"\"\" return self._data", "in writing, software # distributed under the License is distributed", "sent to image channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self,", "description: Description of the image displayed in the Channels tab", "description of this Image. :return: The description of this Image.", "deepsense.io # # Licensed under the Apache License, Version 2.0", "the Channels tab on job's dashboard. :param data: Image data.", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "self.name input_image.description = self.description input_image.data = base64.b64encode(contents).decode('utf-8') return input_image @property", "# You may obtain a copy of the License at", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "Image. :param name: Name of the image, displayed in the", "in format appropriate to be sent to Neptune. :rtype: InputImage", "of this Image. :return: The name of this Image. :rtype:", "to be sent to Neptune. :rtype: InputImage \"\"\" image_buffer =", "the License. # from future import standard_library standard_library.install_aliases() # pylint:", "the License for the specific language governing permissions and #", "( of_type_validator, text_conv, validate ) class Image(object): \"\"\" Represents information", "Apache License, Version 2.0 (the \"License\"); # you may not", "InputImage from neptune.internal.common.models.parameters_validation import ( of_type_validator, text_conv, validate ) class", "either express or implied. # See the License for the", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "governing permissions and # limitations under the License. # from", "coding: utf-8 -*- # # Copyright (c) 2016, deepsense.io #", "sent to Neptune. :rtype: InputImage \"\"\" image_buffer = io.BytesIO() self.data.save(image_buffer,", "InputImage that can be sent to Neptune. :return: input image", "data: Image data. :type name: unicode :type description: unicode :type", "Represents information about images sent to image channels. \"\"\" @validate(name=text_conv,", "The name of this Image. :rtype: str \"\"\" return self._name", ":return: The data of this Image. :rtype: PIL.Image \"\"\" return", "and # limitations under the License. # from future import", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "from future.builtins import object import base64 import io import PIL.Image", "__init__(self, name, description, data): \"\"\" Creates a new Image. :param", "name of this Image. :return: The name of this Image.", "to image channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name,", "def to_input_image(self): \"\"\" Creates InputImage that can be sent to", "input_image.name = self.name input_image.description = self.description input_image.data = base64.b64encode(contents).decode('utf-8') return", "= self.name input_image.description = self.description input_image.data = base64.b64encode(contents).decode('utf-8') return input_image", "a new Image. :param name: Name of the image, displayed", "job's dashboard. :param description: Description of the image displayed in", ":type data: PIL.Image \"\"\" self._name = name self._description = description", "self._name @property def description(self): \"\"\" Gets description of this Image.", "\"License\"); # you may not use this file except in", "InputImage() input_image.name = self.name input_image.description = self.description input_image.data = base64.b64encode(contents).decode('utf-8')", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# distributed under the License is distributed on an \"AS", ":rtype: str \"\"\" return self._description @property def data(self): \"\"\" Gets", "in the Channels tab on job's dashboard. :param description: Description", "# Unless required by applicable law or agreed to in", "the Channels tab on job's dashboard. :param description: Description of", "= InputImage() input_image.name = self.name input_image.description = self.description input_image.data =", "the image, displayed in the Channels tab on job's dashboard.", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "be sent to Neptune. :return: input image in format appropriate", "\"\"\" Creates a new Image. :param name: Name of the", "You may obtain a copy of the License at #", "utf-8 -*- # # Copyright (c) 2016, deepsense.io # #", ":return: input image in format appropriate to be sent to", "return input_image @property def name(self): \"\"\" Gets name of this", "data: PIL.Image \"\"\" self._name = name self._description = description self._data", "the Apache License, Version 2.0 (the \"License\"); # you may", "2016, deepsense.io # # Licensed under the Apache License, Version", "image channels. \"\"\" @validate(name=text_conv, description=text_conv, data=of_type_validator(PIL.Image.Image)) def __init__(self, name, description,", "object import base64 import io import PIL.Image from neptune.generated.swagger_client import", "(c) 2016, deepsense.io # # Licensed under the Apache License," ]
[ "usb_hid import time class HumanKeyboard(object): def __init__(self): self.keyboard = Keyboard(usb_hid.devices)", "adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode import usb_hid import", "from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode import usb_hid", "from adafruit_hid.keycode import Keycode import usb_hid import time class HumanKeyboard(object):", "= Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send a", "keyCode): \"\"\"Send a human like keypress. Keyword arguments: keyCode --", "class HumanKeyboard(object): def __init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard)", "import time class HumanKeyboard(object): def __init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout", "Keycode import usb_hid import time class HumanKeyboard(object): def __init__(self): self.keyboard", "keyCode -- the real key to be pressed (example Keycode.SEVEN)", "time class HumanKeyboard(object): def __init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout =", "keyPress(self, keyCode): \"\"\"Send a human like keypress. Keyword arguments: keyCode", "KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send a human like keypress. Keyword", "HumanKeyboard(object): def __init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def", "import Keycode import usb_hid import time class HumanKeyboard(object): def __init__(self):", "import KeyboardLayoutUS from adafruit_hid.keycode import Keycode import usb_hid import time", "def keyPress(self, keyCode): \"\"\"Send a human like keypress. Keyword arguments:", "\"\"\"Send a human like keypress. Keyword arguments: keyCode -- the", "a human like keypress. Keyword arguments: keyCode -- the real", "adafruit_hid.keycode import Keycode import usb_hid import time class HumanKeyboard(object): def", "__init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode):", "like keypress. Keyword arguments: keyCode -- the real key to", "def __init__(self): self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self,", "Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send a human", "keypress. Keyword arguments: keyCode -- the real key to be", "import usb_hid import time class HumanKeyboard(object): def __init__(self): self.keyboard =", "the real key to be pressed (example Keycode.SEVEN) \"\"\" self.keyboard.press(keyCode)", "human like keypress. Keyword arguments: keyCode -- the real key", "Keyword arguments: keyCode -- the real key to be pressed", "-- the real key to be pressed (example Keycode.SEVEN) \"\"\"", "arguments: keyCode -- the real key to be pressed (example", "adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import", "self.keyboard = Keyboard(usb_hid.devices) self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send", "Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode import", "from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode", "import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode", "self.keyboardLayout = KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send a human like", "real key to be pressed (example Keycode.SEVEN) \"\"\" self.keyboard.press(keyCode) time.sleep(0.1)", "= KeyboardLayoutUS(self.keyboard) def keyPress(self, keyCode): \"\"\"Send a human like keypress.", "KeyboardLayoutUS from adafruit_hid.keycode import Keycode import usb_hid import time class", "key to be pressed (example Keycode.SEVEN) \"\"\" self.keyboard.press(keyCode) time.sleep(0.1) self.keyboard.release(keyCode)", "<filename>src/picome/hukeyboard.py from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from" ]
[ ":type root: TreeNode :rtype: int \"\"\" if not root: return", "root: TreeNode :rtype: int \"\"\" if not root: return 0", "import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self,", "from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases()", "not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if", "MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self, input):", "return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ == '__main__': sol", "Solution from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self): return", "gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self, input): return self.maxDepth(input) def maxDepth(self,", "def maxDepth(self, root): \"\"\" :type root: TreeNode :rtype: int \"\"\"", "if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1", "return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ ==", "MaxBiTreeDepthTestCases() def run_test(self, input): return self.maxDepth(input) def maxDepth(self, root): \"\"\"", "maxDepth(self, root): \"\"\" :type root: TreeNode :rtype: int \"\"\" if", "return MaxBiTreeDepthTestCases() def run_test(self, input): return self.maxDepth(input) def maxDepth(self, root):", "run_test(self, input): return self.maxDepth(input) def maxDepth(self, root): \"\"\" :type root:", "TreeNode :rtype: int \"\"\" if not root: return 0 return", "src.base.solution import Solution from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def", "src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases() def", "from src.base.solution import Solution from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution):", "+ 1 if __name__ == '__main__': sol = MaxBiTreeDepth() sol.run_tests()", "import Solution from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class MaxBiTreeDepth(Solution): def gen_test_cases(self):", "MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self, input): return self.maxDepth(input)", "class MaxBiTreeDepth(Solution): def gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self, input): return", ":rtype: int \"\"\" if not root: return 0 return max(self.maxDepth(root.left),", "<filename>src/solutions/part2/q104_max_bi_tree_depth.py from src.base.solution import Solution from src.tests.part2.q104_test_max_bi_tree_depth import MaxBiTreeDepthTestCases class", "def gen_test_cases(self): return MaxBiTreeDepthTestCases() def run_test(self, input): return self.maxDepth(input) def", "return self.maxDepth(input) def maxDepth(self, root): \"\"\" :type root: TreeNode :rtype:", "self.maxDepth(input) def maxDepth(self, root): \"\"\" :type root: TreeNode :rtype: int", "max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ == '__main__': sol =", "def run_test(self, input): return self.maxDepth(input) def maxDepth(self, root): \"\"\" :type", "self.maxDepth(root.right)) + 1 if __name__ == '__main__': sol = MaxBiTreeDepth()", "int \"\"\" if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right))", "input): return self.maxDepth(input) def maxDepth(self, root): \"\"\" :type root: TreeNode", "root): \"\"\" :type root: TreeNode :rtype: int \"\"\" if not", "root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__", "0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 if __name__ == '__main__':", "\"\"\" if not root: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) +", "\"\"\" :type root: TreeNode :rtype: int \"\"\" if not root:" ]
[ "['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name',", "admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity', 'cost_price', 'selling_price',)", "django.contrib import admin from . import models class SupplierAdmin(admin.ModelAdmin): list_display", "'user_type') search_fields = ['employee_name', 'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin)", "models class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact', ) search_fields =", "class ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity', 'cost_price', 'selling_price',) search_fields =", "list_display = ('name', 'quantity', 'cost_price', 'selling_price',) search_fields = ['name', 'quantity',", "SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact', ) search_fields = ['supplier_name', 'contact',", "= ('supplier_name', 'contact', ) search_fields = ['supplier_name', 'contact', ] admin.site.register(models.Suppliers,", "import admin from . import models class SupplierAdmin(admin.ModelAdmin): list_display =", "(\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity', 'cost_price',", "InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity', 'cost_price', 'selling_price',) search_fields", "import models class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact', ) search_fields", "= (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity',", "InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type') search_fields = ['employee_name', 'user_type'] list_filter", "from . import models class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact',", "('supplier_name', 'contact', ) search_fields = ['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin)", "class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact', ) search_fields = ['supplier_name',", "= ['employee_name', 'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin):", "search_fields = ['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display", "['name', 'quantity', 'cost_price', 'selling_price',] list_filter = (\"branch\", \"supplier\",) admin.site.register(models.Product, ProductsAdmin)", "list_display = ('employee_name', 'user_type') search_fields = ['employee_name', 'user_type'] list_filter =", "= ['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display =", "('employee_name', 'user_type') search_fields = ['employee_name', 'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser,", "'contact', ) search_fields = ['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class", "'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type')", "search_fields = ['employee_name', 'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class", "'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display =", "list_display = ('supplier_name', 'contact', ) search_fields = ['supplier_name', 'contact', ]", "= ['name', 'quantity', 'cost_price', 'selling_price',] list_filter = (\"branch\", \"supplier\",) admin.site.register(models.Product,", "] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type') search_fields", "class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type') search_fields = ['employee_name', 'user_type']", "list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display = ('name',", "'quantity', 'cost_price', 'selling_price',) search_fields = ['name', 'quantity', 'cost_price', 'selling_price',] list_filter", "('name', 'quantity', 'cost_price', 'selling_price',) search_fields = ['name', 'quantity', 'cost_price', 'selling_price',]", ". import models class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name', 'contact', )", "'selling_price',) search_fields = ['name', 'quantity', 'cost_price', 'selling_price',] list_filter = (\"branch\",", "= ('employee_name', 'user_type') search_fields = ['employee_name', 'user_type'] list_filter = (\"user_type\",)", "admin from . import models class SupplierAdmin(admin.ModelAdmin): list_display = ('supplier_name',", ") search_fields = ['supplier_name', 'contact', ] admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin):", "admin.site.register(models.Suppliers, SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type') search_fields =", "SupplierAdmin) class InventoryUserAdmin(admin.ModelAdmin): list_display = ('employee_name', 'user_type') search_fields = ['employee_name',", "'cost_price', 'selling_price',) search_fields = ['name', 'quantity', 'cost_price', 'selling_price',] list_filter =", "= ('name', 'quantity', 'cost_price', 'selling_price',) search_fields = ['name', 'quantity', 'cost_price',", "from django.contrib import admin from . import models class SupplierAdmin(admin.ModelAdmin):", "search_fields = ['name', 'quantity', 'cost_price', 'selling_price',] list_filter = (\"branch\", \"supplier\",)", "['employee_name', 'user_type'] list_filter = (\"user_type\",) admin.site.register(models.InventoryUser, InventoryUserAdmin) class ProductsAdmin(admin.ModelAdmin): list_display", "ProductsAdmin(admin.ModelAdmin): list_display = ('name', 'quantity', 'cost_price', 'selling_price',) search_fields = ['name'," ]
[ "<gh_stars>1-10 try: name = \"\" except: pass else: print na<ref>me" ]
[ "token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\" } def", "self._session.headers = { \"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS", "{ \"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\"", "providedSession self._session.headers = { \"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145;", "(co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\" } def session(self): return self._session", "token if providedSession == False: self._session = requests.session() else: self._session", "class ByteSession(object): def __init__(self, token, providedSession=False): self._userToken = token if", "self._userToken = token if providedSession == False: self._session = requests.session()", "False: self._session = requests.session() else: self._session = providedSession self._session.headers =", "token, providedSession=False): self._userToken = token if providedSession == False: self._session", "= token if providedSession == False: self._session = requests.session() else:", "\"byte/0.2 (co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\" } def session(self): return", "self._session = requests.session() else: self._session = providedSession self._session.headers = {", "else: self._session = providedSession self._session.headers = { \"Authorization\": token, \"User-Agent\":", "\"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\" } def session(self):", "def __init__(self, token, providedSession=False): self._userToken = token if providedSession ==", "<reponame>ms7m/py-byte import requests class ByteSession(object): def __init__(self, token, providedSession=False): self._userToken", "__init__(self, token, providedSession=False): self._userToken = token if providedSession == False:", "import requests class ByteSession(object): def __init__(self, token, providedSession=False): self._userToken =", "requests.session() else: self._session = providedSession self._session.headers = { \"Authorization\": token,", "providedSession == False: self._session = requests.session() else: self._session = providedSession", "= providedSession self._session.headers = { \"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video;", "self._session = providedSession self._session.headers = { \"Authorization\": token, \"User-Agent\": \"byte/0.2", "\"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS 13.3.0) Alamofire/4.9.1\" }", "if providedSession == False: self._session = requests.session() else: self._session =", "= { \"Authorization\": token, \"User-Agent\": \"byte/0.2 (co.byte.video; build:145; iOS 13.3.0)", "providedSession=False): self._userToken = token if providedSession == False: self._session =", "== False: self._session = requests.session() else: self._session = providedSession self._session.headers", "= requests.session() else: self._session = providedSession self._session.headers = { \"Authorization\":", "ByteSession(object): def __init__(self, token, providedSession=False): self._userToken = token if providedSession", "requests class ByteSession(object): def __init__(self, token, providedSession=False): self._userToken = token" ]
[ "= mkQApp() # win.setWindowTitle('pyqtgraph example: ____') if __name__ == '__main__':", "mkQApp import numpy as np app = mkQApp() # win.setWindowTitle('pyqtgraph", "Description of example \"\"\" import pyqtgraph as pg from pyqtgraph.Qt", "-*- \"\"\" Description of example \"\"\" import pyqtgraph as pg", "pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui, mkQApp import", "utf-8 -*- \"\"\" Description of example \"\"\" import pyqtgraph as", "QtGui, mkQApp import numpy as np app = mkQApp() #", "example \"\"\" import pyqtgraph as pg from pyqtgraph.Qt import QtCore,", "as pg from pyqtgraph.Qt import QtCore, QtGui, mkQApp import numpy", "pg from pyqtgraph.Qt import QtCore, QtGui, mkQApp import numpy as", "import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui, mkQApp", "from pyqtgraph.Qt import QtCore, QtGui, mkQApp import numpy as np", "\"\"\" Description of example \"\"\" import pyqtgraph as pg from", "import numpy as np app = mkQApp() # win.setWindowTitle('pyqtgraph example:", "\"\"\" import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui,", "QtCore, QtGui, mkQApp import numpy as np app = mkQApp()", "import QtCore, QtGui, mkQApp import numpy as np app =", "-*- coding: utf-8 -*- \"\"\" Description of example \"\"\" import", "as np app = mkQApp() # win.setWindowTitle('pyqtgraph example: ____') if", "numpy as np app = mkQApp() # win.setWindowTitle('pyqtgraph example: ____')", "np app = mkQApp() # win.setWindowTitle('pyqtgraph example: ____') if __name__", "coding: utf-8 -*- \"\"\" Description of example \"\"\" import pyqtgraph", "# -*- coding: utf-8 -*- \"\"\" Description of example \"\"\"", "app = mkQApp() # win.setWindowTitle('pyqtgraph example: ____') if __name__ ==", "mkQApp() # win.setWindowTitle('pyqtgraph example: ____') if __name__ == '__main__': pg.exec()", "pyqtgraph.Qt import QtCore, QtGui, mkQApp import numpy as np app", "of example \"\"\" import pyqtgraph as pg from pyqtgraph.Qt import" ]
[ "{ \"cpu_count\" : 1, \"host_name\" : \"host1\", \"os_arch\" : \"x86_64\",", "configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"]", "'256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user']", "{\"disk_info\": [ { \"available\" : \"2\", \"type\" : \"ext4\", \"mountpoint\"", "\"/vagrant\"} ] } } ] } expected = { \"hBaseInstalled\":", "\"At least 3 Ganglia Server components should be installed in", "self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "\"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, { \"StackServices\": {", "'uid' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services,", "property should be set to true for distributed mode', 'type':", "Audit properties\") def test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\": { \"properties\":", "then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '2048'}", "} ] } ], \"configurations\": {} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\",", "expected[\"ram\"] = 0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] = 1 result", ": \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" :", "services['configurations'] = configurations expected = { \"admin-properties\": { \"properties\": {", "expectedHosts = componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self,", "} result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected)", "actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts", "] self.assertEquals(res, expected) def test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\": {\"service_name\"", "test_validateNonRootFs(self): hostInfo = {\"disk_info\": [ { \"available\" : \"2\", \"type\"", "\"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" }, \"components\": [ { \"StackServiceComponents\": {", "more contributor license agreements. See the NOTICE file distributed with", "} ], }], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({", "properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults,", "= self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [", "= {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([]) result =", "{ \"Hosts\" : { \"cpu_count\" : 8, \"total_mem\" : 6291456,", "{ \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\":", "\"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\":", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = []", "'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations,", "disk space requirements not met. ' '\\nRecommended disk space for", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components", "{ \"service_name\": \"SERVICE\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "= 0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] = 1 result =", "} } } expected = { \"admin-properties\": { \"properties\": {", "} } expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\":", "'some_float_value': {'minimum': '0.8'} } } } items = [] self.stackAdvisor.validateMinMax(items,", "\"HDFS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\":", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "\"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space", "recommendedDefaults, \"property1\"), expected) properties = {} recommendedDefaults = {\"property1\": \"value2\"}", "\"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\",", "\"Exactly 2 Ganglia Monitor components should be installed in cluster.\",", "metrics data', 'type': 'configuration' }, { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site',", "nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping =", "\"type\" : \"ext4\", \"mountpoint\" : \"/\" } ] res =", "hostInfo = {\"disk_info\": [ { \"available\" : \"1\", \"type\" :", "'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org',", "= { \"Versions\" : { \"stack_name\" : \"HDP\", \"stack_version\" :", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "None) def test_mergeValidators(self): childValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\":", "}, { 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed", "KeyError, err: actualComponentHostsMap[componentName] = [] for host in hosts: if", "{ \"available\" : '1', \"type\" : \"ext4\", \"mountpoint\" : \"/\"", "actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1, l2): if", "= [ { \"available\": str(15<<30), # 15 GB \"type\" :", "str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\"", "{ \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } }, { \"StackServiceComponents\": {", "== hostGroupName][0] hosts = [info[\"fqdn\"] for info in hostsInfos] for", "\"ranger.service.http.enabled\": \"false\", } } } services['configurations'] = configurations expected =", "], }], \"configurations\": {} } hosts = { \"items\" :", "\"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"]", "result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Ganglia Monitor", "configurations = {} clusterData = { \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666,", "ANY KIND, either express or implied. See the License for", "= [\"HBASE\"] configurations = {} components = [] host_item =", "disk space host['Hosts']['disk_info'] = [ { \"available\" : '1', \"type\"", "\"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\"", "\"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} }", "property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self): import imp, os", "'type': 'configuration' } ] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo =", "before \"\"\" servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\":", "\"Oozie Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\",", "configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] =", "} res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected =", "{'level': 'ERROR', 'message': 'Value should be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties,", "'level': 'ERROR'}, {\"message\": \"Value should be integer\", \"level\": \"ERROR\"}, {\"message\":", "for host in hosts: if host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host)", "\"\"\" services = { \"services\" : [ { \"StackServices\" :", "'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "services = { \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\"", "set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the metrics to Ambari", "no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected", "{ \"items\": [ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1,", "preferable - no warning hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\"", "'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' : '256'} properties = {'namenode_heapsize': '2048',", "ASF licenses this file to you under the Apache License,", "\"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations } expected =", "\"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\",", "\"ranger-env\": {\"properties\": {}} } recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\"", "'false' } host = { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" :", "expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"]", "\"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\",", "def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value1\"}", "'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services =", "[\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"]", "'WARN', 'message': 'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report", ": \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } ] }", "\"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"]", "'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' }, { 'message': 'Value", "{} # Recommend for not existing DB_FLAVOR and http enabled,", "\"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ]", "\"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }], \"configurations\": configurations, \"ambari-server-properties\":", "services, hosts) self.assertTrue(res) #Value is begger then expected recommendedDefaults =", "} ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\",", "{ \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\",", "already installed services, recommendation for installed components should match the", "= {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] = [] for component in", "\"HDFS\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\",", "[ { \"StackServices\": { \"service_name\": \"ZOOKEEPER\" }, \"components\": [ {", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"6\", \"type\" :", "\"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\",", "recommended recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' :", "{ 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations =", "8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData", "components = [] hosts = { \"items\" : [] }", ": \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" :", "'WARN', 'message': 'Ambari Metrics disk space requirements not met. '", "= {\"disk_info\": [ { \"available\" : \"1\", \"type\" : \"ext4\",", "'type': 'configuration' }, { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN',", "\"mountpoint\": \"/\" }] } }, ]} services = { \"services\":", "\"2\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/dev/shm\" } ) self.assertEquals([\"/\"],", "\"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties = {\"property1\": \"value1\"} recommendedDefaults", "/boot with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"4\",", "\"cpu_count\" : 1, \"host_name\" : \"host1\", \"os_arch\" : \"x86_64\", \"os_type\"", "{ 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE':", "} }, \"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" } }", "DB_FLAVOR ORACLE and https enabled, HDP-2.2\") # Test Recommend LDAP", "datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"])", "local FS, enough space hostInfo = {\"disk_info\": [ { \"available\"", "properties = {} recommendedDefaults = {\"property1\": \"value2\"} expected = {'level':", "= '' hosts = '' #Default configuration recommendedDefaults = {'dfs.datanode.du.reserved':", "self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ { \"name\": \"HDFS\",", "self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData =", "having any component installed) as part of recommendation received during", "] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected =", "test_mergeValidators(self): childValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"},", "# Test - Cluster data with 1 host result =", "\"ext4\", \"mountpoint\" : \"/\" } ]} properties = {\"property1\": \"file:///var/dir\"}", "from unittest import TestCase from mock.mock import patch, MagicMock class", "\"cpu_count\" : 6, \"total_mem\" : 50331648, \"disk_info\" : [ {\"mountpoint\"", "= { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 6, \"disk\": 6,", "\"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": {", "def __enter__(self): return self exists_mock.return_value = True open_mock.return_value = MagicFile()", "metrics to Ambari Metrics service.', 'type': 'configuration' } ] self.assertEquals(res,", "} properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", "\"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # non-local FS,", "self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already installed slaves", "{ \"service_name\": \"AMBARI_METRICS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "services = {\"configurations\": configurations, \"services\": []} clusterData = { \"containers\"", "\"available\" : \"6\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" }", "'Queue is not exist, or not corresponds to existing YARN", "= self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received should be as below:", "{ \"cpu_count\" : 1, \"host_name\" : \"host2\", \"os_arch\" : \"x86_64\",", "properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None)", "self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address is recommended to be deleted", "\"DATANODE\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\": configurations", "\"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\":", "\"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\" : \"host2\",", "\"available\" : \"2\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/dev/shm\" }", "= self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) # 2)", "{ \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", } } } services['configurations'] =", "properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false'", "\"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with", "}], 'name': 'host-group-2' }] } } \"\"\" # Assert that", "= self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self):", "namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1) # [host2]", "\"StackServiceComponents\" : { \"cardinality\" : \"1+\", \"component_category\" : \"SLAVE\", \"component_name\"", "\"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": { \"properties\": {} }", "enabled, HDP-2.3 services = { \"Versions\" : { \"stack_version\" :", "expectedItems, result): actualItems = [] for item in result[\"items\"]: next", "{'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' : '300'} res_expected =", "services, hosts) self.assertEquals(nodemanager, None) # unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\",", "\"/grid/0\" } ) recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties,", "\\n\" \\ \"Recommended disk space for partition / is 1G\"", "with low space available hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\"", "}, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[", "1 Ganglia Server components should be installed in cluster.\", \"level\":", "self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations =", "= { \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" :", "= self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertTrue(res) #Value is begger", "{\"message\": \"Value should be integer\", \"level\": \"ERROR\"}, {\"message\": \"Value should", "nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def assertHostLayout(self, componentsHostsMap,", "# local FS, enough space hostInfo = {\"disk_info\": [ {", "None) def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\":", "\"Ganglia Server\", \"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\",", "2097152 } }, { \"href\" : \"/api/v1/hosts/host2\", \"Hosts\" : {", "properties = {'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services,", "recommendedDefaults = {} expected = {'level': 'ERROR', 'message': 'Value should", "\"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo = [", "None) self.assertEquals(configurations, expected) # with AMS configurations = {} services", "{\"message\": item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"] = item[\"host\"] except KeyError,", "None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self): # no AMS configurations =", "{\"message\": \"At least 3 Ganglia Server components should be installed", "reqiuredDiskSpace) == None) # local FS, no enough space hostInfo", "'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff", "'property1', hostInfo, reqiuredDiskSpace) == None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000),", "\"property1\"), None) properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value2\"}", "expectedItems = [ {\"message\": \"Value is less than the recommended", "imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = { \"services\": [ { \"StackServices\": {", "See the License for the specific language governing permissions and", "} expected = { \"storm-site\": { \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\"", "self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0])", "preferable /grid/0 mountpoint - warning hostInfo[\"disk_info\"].append( { \"available\" : \"3\",", "expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"]", "\"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\":", "\"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0),", "\"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" } } } recommendedDefaults = {", ": {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self):", "{\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } }) expected[\"referenceHost\"]", "\"tmpfs\", \"mountpoint\" : \"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot", "{ \"available\" : \"4\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\"", "'clientPort': \"2183\" } } } services = { \"services\": [", "'false' } properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase',", "\"oozie_user\": \"oozie\" } }, \"falcon-env\": { \"properties\": { \"falcon_user\": \"falcon\"", "] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems = [] result", "'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}},", "services = '' hosts = '' #Default configuration recommendedDefaults =", "{ \"items\" : [ host ] } services = {", "} } } recommendedDefaults = { \"mapred-site\": { \"properties\": {", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]} ] } ]", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]} ] } ] services =", "# 1) ok: namenode_heapsize > recommended recommendedDefaults = {'namenode_heapsize': '1024',", "recommendedDefaults, configurations, services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations = {}", "= socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts)", "= { \"items\" : [ { \"Hosts\" : { \"cpu_count\"", "4, \"total_mem\" : 500000, \"host_name\" : \"host2\", \"disk_info\" : [", "DB_FLAVOR and http enabled, HDP-2.3 services = { \"Versions\" :", "'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize':", "} ], \"configurations\": {} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected", "services[\"configurations\"] = {} expected = { 'admin-properties': { 'properties': {", "no warning hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" : \"ext4\",", "import os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath", "{ \"StackServices\": { \"service_name\": \"FALCON\" }, \"components\": [] }, {", "\"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } } recommendedDefaults =", "{} } } expected = { 'admin-properties': { 'properties': {", "= 3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] =", "= self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\",", "= self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received", "language governing permissions and limitations under the License. ''' import", "not len(l1) == len(l2) or not sorted(l1) == sorted(l2): raise", "self.stackAdvisor = clazz() self.maxDiff = None # substitute method in", "clusterData = { \"containers\" : 5, \"ramPerContainer\": 256 } expected", "\"hbase123\" } } } } expected = { 'hbase-site': {", "\"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\":", "}] } }, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1,", ": \"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with", "def test_recommendationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\":", "services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components =", "def test_validationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", "{ 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host", "\"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components,", "0, \"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\":", "is 10G', 'type': 'configuration' } ] self.assertEquals(res, expected) # 2", "'false' } properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase',", "\"cpu\": 6, \"disk\": 6, \"ram\": 48, \"reservedRam\": 6, \"hbaseRam\": 8,", "\"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, { \"StackServices\": { \"service_name\": \"OOZIE\"", "= recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for hostGroup", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] }", ": 1048576 } }, ] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\",", "properties del services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\": { \"properties\": {", "= self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = [] self.assertEquals(res,", "only / mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo)", "agreements. See the NOTICE file distributed with this work for", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space available hostInfo[\"disk_info\"].append( {", "{\"message\": \"Exactly 2 Ganglia Monitor components should be installed in", "in servicesInfo: nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] = []", "NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] =", "\"host1\" ] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\",", "{\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\":", "{ \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" }", "'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*',", "= { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' }", "} ], \"configurations\": configurations } # positive res = self.stackAdvisor.validateStormConfigurations(properties,", "recommendedDefaults = {\"property1\": \"value2\"} expected = {'message': 'It is recommended", "expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"]", "recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None)", "'properties': { 'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': { 'properties': {", "Metrics disk space requirements not met. \\n\" \\ \"Recommended disk", "\"WARN\"}, {'message': 'Value should be set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'},", "expected = [] self.assertEquals(res, expected) properties['metrics.reporter.register'] = '' res =", "or not corresponds to existing YARN leaf queue', 'level': 'ERROR'}", "self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"},", "'In distributed mode hbase.rootdir should point to HDFS.', 'type': 'configuration'", "567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 } expected = { \"mapred-site\":", "} ] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations = { \"storm-site\":", "Version 2.0 (the \"License\"); you may not use this file", "\"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}] } ]", "component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None) #", "to use root partition for hbase.rootdir', 'type': 'configuration' }, {", "\"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\":", "services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\",", ": \"6\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } )", "met. ' '\\nRecommended disk space for partition / is 10G',", "= [{'config-type': 'hadoop-env', 'message': 'Value is less than the recommended", "\"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\":", "= [] for component in serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\":", "= self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {\"message\": \"Value is less", "proper mountpoint with more space available hostInfo[\"disk_info\"].append( { \"available\" :", "'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env': {'properties':", "on all hosts for cardinality ALL even if the component", "def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ { \"name\": \"YARN\", \"components\": []", "not use this file except in compliance with the License.", "0 and 1 Ganglia Server components should be installed in", "= '' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected", "[], \"display_name\": \"WebHCat Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\",", "\"vboxsf\", \"mountpoint\" : \"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper", "result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Between 0", "expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations = {", "def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg = \"Ambari Metrics disk", "\"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{ \"size\": '8',", "\"mapred-site\": { \"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\",", "= hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"] =", "15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" }, {", "you may not use this file except in compliance with", "\"ALL\", \"category\": \"SLAVE\", \"is_master\": False}] } ] services = self.prepareServices(servicesInfo)", "= self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) # Test -", "{ \"cpu_count\" : 6, \"total_mem\" : 50331648, \"disk_info\" : [", "\"custom_commands\": [], \"display_name\": \"Oozie Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\":", "def test_validateHDFSConfigurations(self): configurations = {} services = '' hosts =", "mountpoint - warning hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" :", "services = { \"services\" : [ { \"StackServices\" : {", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "# 2) fail: namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] = '1022'", "the License. You may obtain a copy of the License", "'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res,", "= [ {\"message\": \"Value is less than the recommended default", "Ganglia Server components should be installed in cluster.\", \"level\": \"ERROR\"}", "{ \"StackServices\": { \"service_name\": \"ZOOKEEPER\" }, \"components\": [ { \"StackServiceComponents\":", "\"mountpoint\" : \"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def", "FS, WASB properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace)", "hosts in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self):", "300)] } services = { \"services\" : [ ], \"configurations\":", "\"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]} ] }", "{\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn !=", "\"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\":", "self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR POSTGRES and https enabled, HDP-2.3\")", "configurations) expectedItems = [ { 'message': 'Value is greater than", "'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected =", "= [ { \"available\" : '1', \"type\" : \"ext4\", \"mountpoint\"", "\"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\",", "\"hbase\" } }, \"hbase-env\": { \"properties\": { \"hbase_user\": \"hbase123\" }", "3 Ganglia Server components should be installed in cluster.\", \"level\":", "to store HDFS data', 'type': 'configuration' } ] self.assertEquals(res, expected)", "\"mountpoint\" : \"/grid/0\" }, { \"available\" : str(15<<30), # 15", "hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" : 4, \"total_mem\" : 500000, \"host_name\"", "\"/default-rack\", \"total_mem\" : 1048576 } }, ] } datanodes =", "\"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\":", "True, \"hostnames\": [\"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts", "{\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return hosts def prepareServices(self, servicesInfo): services", "\"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\":", "by user /var mountpoint, which is non-root , but not", "'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir':", "'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2' }] } }", ": \"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint", ": \"2\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]}", "[{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1' }, {", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }, \"components\":", "os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with", "= '' #Default configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties =", "'name': 'host-group-1', 'components': [] }, { 'name': 'host-group-2', 'components': [{", "# host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\",", "} ], \"configurations\": configurations } expected = { \"storm-site\": {", "'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN', 'message': 'Value", "self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems", "[\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True,", "\"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\",", "'Consider not using / partition for storing metrics data. '", "return hosts def prepareServices(self, servicesInfo): services = { \"Versions\" :", "{ \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\": {", "component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services", "\"size\": '8', \"mountpoint\": \"/\" }] } }, { \"href\": \"/api/v1/hosts/host2\",", "170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] = 512", ": \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath =", "host['Hosts']['disk_info'] = [ { \"available\": str(15<<30), # 15 GB \"type\"", "== None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048)", "\"available\" : str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\"", "expected = { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 8, \"disk\":", "installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self):", "unittest import TestCase from mock.mock import patch, MagicMock class TestHDP206StackAdvisor(TestCase):", "\"stack_name\" : \"HDP\", \"stack_version\" : \"2.0.6\" } } services[\"services\"] =", "additional information regarding copyright ownership. The ASF licenses this file", "\"ph_cpu_count\" : 1, \"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\"", "'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2'", "res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self):", "\"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive", "with 1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result,", "\"service_name\": \"HDFS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"NAMENODE\",", "2 hosts - pick minimum memory servicesList.append(\"YARN\") services = services", "2048, \"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\":", "res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) #Value is", "2097152, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] } },", "enabled, HDP-2.3\") # Recommend for DB_FLAVOR ORACLE and https enabled,", ": \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"]", "under the License. ''' import socket from unittest import TestCase", "'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN', 'message':", "\"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\":", "'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration' } ]", "\"Test for DB_FLAVOR ORACLE and https enabled, HDP-2.2\") # Test", "result) def test_validationMinMax(self): configurations = { \"mapred-site\": { \"properties\": {", "configurations expected[\"hdfs-site\"] = { 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024',", "'message': 'Ambari Metrics disk space requirements not met. ' '\\nRecommended", "\"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None) # unknown service unknown_component =", "'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } } recommendedConfigurations = {}", "] } services = { \"services\": [ { \"StackServices\": {", "expected) properties = {} recommendedDefaults = {\"property1\": \"value2\"} expected =", "\"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\",", "siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test", ": '300'} res_expected = [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations,", "\"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\"", "\"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox", "expectedItems = [ {\"message\": \"Between 0 and 1 Ganglia Server", "= getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff = None #", "[ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\",", "no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) # More", "[] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with low space available", "\"storm-site\": { \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations,", "None) # More preferable /grid/0 mountpoint - warning hostInfo[\"disk_info\"].append( {", "[ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\",", "} }, 'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%',", "[\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"} recommendedDefaults", "Server\", \"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]}", "recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self): import imp, os testDirectory =", "of 0.8 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type':", "512, \"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test", "'*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts':", "cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo =", "services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR ORACLE and https", "\"hive\" } }, \"oozie-env\": { \"properties\": { \"oozie_user\": \"oozie\" }", "True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\":", "data', 'type': 'configuration' } ] self.assertEquals(res, expected) # incorrect hbase.rootdir", ": '300', 'namenode_opt_maxnewsize' : '300'} res_expected = [] res =", "'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'In distributed mode", "'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' :", "law or agreed to in writing, software distributed under the", "{ \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\",", "is not used\", \"host\": \"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result)", "None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg = \"Ambari Metrics", "{ \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\",", "'namenode_opt_maxnewsize' : '300'} res_expected = [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults,", "False, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts =", "expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '2048'} res", ": \"host2\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" :", "], }], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\":", "= self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [ {", "} for hostName in hostsNames: nextHost = {\"Hosts\":{\"host_name\" : hostName}}", "'ranger-env': {'properties': {}}, 'usersync-properties': { 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN':", ": { \"service_name\" : \"HDFS\" }, \"components\" : [ {", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"4\", \"type\" :", "self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Between 0 and 1", "getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff = None # substitute", "expected) # with AMS configurations = {} services = {", "} } expected = { 'admin-properties': { 'properties': { 'policymgr_external_url':", "' '\\nRecommended disk space for partition / is 10G', 'type':", ": \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" :", "expected[\"reservedRam\"] = 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result,", "{\"properties\": {}} } recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations,", "34816, \"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\":", "[ {'message': 'Queue is not exist, or not corresponds to", "} ] } } hosts = { \"items\" : [", "= { \"items\" : [ host ] } services =", "'level': 'WARN', 'message': 'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to", "\"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } parentValidators =", ": \"HDFS\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{", "\"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": {", "\"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\"", "= 170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] =", "\"properties\": { 'clientPort': \"2183\" } } } services = {", "# with AMS configurations = {} services = { \"services\":", "256 } expected = { \"yarn-env\": { \"properties\": { \"min_user_id\":", "'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups':", "hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators = { \"HDFS\": {\"hdfs-site\":", ": \"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" :", "hosts = { \"items\" : [host_item for i in range(1,", "\"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } } ] },", ": 5, \"ramPerContainer\": 256 } expected = { \"yarn-env\": {", "\"hostnames\":[ \"host1\" ] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\",", "str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/\"", "disk space requirements not met. \\n\" \\ \"Recommended disk space", "expected) def test_getZKHostPortString(self): configurations = { \"zoo.cfg\": { \"properties\": {", "expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self):", ": str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\" :", "services = services = {\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\"", "KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError:", "be installed on all hosts in cluster.\", \"level\": \"ERROR\"} ]", "licenses this file to you under the Apache License, Version", "len(l2) or not sorted(l1) == sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2))", "'*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts':", "'WARN', 'message': 'In distributed mode hbase.rootdir should point to HDFS.',", "\"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"}", "= { \"services\" : [ ], \"configurations\": { \"hbase-site\": {", "item[\"host\"] except KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self):", "{ \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } }", "# positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected", "services, recommendation for installed components should match the existing layout", "services, hosts) self.assertFalse(res) #Value is less then expected recommendedDefaults =", "{ \"service_name\": \"HDFS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "Ranger Audit properties\") def test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\": {", "servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\":", "\"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"]", "None) self.assertEquals({'message': 'It is not recommended to use root partition", "no enough space hostInfo = {\"disk_info\": [ { \"available\" :", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\" }, \"components\":", "= {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties = {\"property1\":", "no AMS configurations = {} services = { \"services\": [", "self.assertTrue(warn != None) self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn) # non-local", "[ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'It", "assertValidationResult(self, expectedItems, result): actualItems = [] for item in result[\"items\"]:", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with more space available hostInfo[\"disk_info\"].append( {", "service.', 'type': 'configuration' } ] self.assertEquals(res, expected) def test_getHostsWithComponent(self): services", ": 6291456, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" :", "result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) # Test", "for hostName in hostsNames: nextHost = {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost)", "os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as fp:", "hosts) expectedItems = [ {\"message\": \"Value is less than the", "'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults,", "expected = {'level': 'ERROR', 'message': 'Value should be set for", "recommendation for installed components should match the existing layout \"\"\"", "hostsNames: nextHost = {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return hosts def", "return self exists_mock.return_value = True open_mock.return_value = MagicFile() return self.get_system_min_uid_real()", "\"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum':", "non-root , but not preferable - no warning hostInfo[\"disk_info\"].append( {", "\"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\",", "services, hosts) expected = [ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level':", "recommended default of 512\", \"level\": \"WARN\"}, {'message': 'Value should be", "'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env': {'properties': {}}, 'usersync-properties': { 'properties':", "] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo = [ { \"name\":", "expected = { \"hBaseInstalled\": False, \"components\": components, \"cpu\": 0, \"disk\":", "nextComponent = { \"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\":", "\"StackServices\": { \"service_name\": \"ZOOKEEPER\" }, \"components\": [ { \"StackServiceComponents\": {", "None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"]", "\"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[", "6, \"total_mem\" : 50331648, \"disk_info\" : [ {\"mountpoint\" : \"/\"},", "{ \"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\":", "170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result, expected) def prepareHosts(self,", "\"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\",", "'\\nRecommended disk space for partition / is 10G', 'type': 'configuration'", "should be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def", "for component in serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\": { \"component_name\":", "'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {} recommendedDefaults", "\"http.enabled\": \"false\", \"https.service.port\": \"8888\", } } } services['configurations'] = configurations", "disk space for partition / is 1G\" # local FS,", "[\"host1\"] } } ] } ], \"configurations\": configurations } result", "{ \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\":", "\"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\":", "for storing metrics data. ' '/ is already used by", "50331648, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"},", "\"7777\", \"ranger.service.http.enabled\": \"false\", } } } services['configurations'] = configurations expected", "self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\",", "test_validationCardinalityExactAmount(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "info in hostsInfos] for component in hostGroup[\"components\"]: componentName = component[\"name\"]", "queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems", "serviceInfo in servicesInfo: nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] =", "{ 'properties': { 'hbase.superuser': 'hbase123' } }, \"hbase-env\": { \"properties\":", "\"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\":", "\"cardinality\" : \"1+\", \"component_category\" : \"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\"", "self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\":", "{ \"StackServices\": { \"service_name\": \"OOZIE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\",", "host_item = { \"Hosts\" : { \"cpu_count\" : 6, \"total_mem\"", "non-local FS, WASB properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo,", "\"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\":", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"HDFS\" },", "'1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize':", "'hbase.cluster.distributed': 'false' } host = { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\"", "hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"] = 4", "4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\")", "installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self):", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo = [ {", "/boot with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"3\",", "\"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]} warn =", "] self.assertEquals(res, expected) # incorrect hbase.rootdir in distributed mode properties", "{'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts':", "AMS configurations = {} services = { \"services\": [ {", "\"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\",", "Ambari Metrics service.', 'type': 'configuration' } ] self.assertEquals(res, expected) def", "\"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] }", "not using / partition for storing metrics temporary data. '", "\"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\":", "\"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\": True}]", "and http enabled, HDP-2.3 services = { \"Versions\" : {", "for hbase.rootdir', 'type': 'configuration' }, { 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site',", ": 4, \"total_mem\" : 500000, \"host_name\" : \"host2\", \"disk_info\" :", "{} } hosts = { \"items\" : [ { \"href\"", "1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\":", "warning hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\"", "\"ALL\", \"category\": \"MASTER\", \"is_master\": True}] } ] services = self.prepareServices(servicesInfo)", "'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address':", "FS, no enough space hostInfo = {\"disk_info\": [ { \"available\"", "mode properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", "\"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "= { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\",", "\"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]} ] }", "}] }, 'blueprint_cluster_binding': { 'host_groups': [{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org'", "at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to", "result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"At least", "self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([])", "\"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\":", "= componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1,", "] } } hosts = { \"items\" : [host_item for", "{'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024',", "\"4\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"],", "leaf queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\"", "[\"HBASE\"] configurations = {} components = [] host_item = {", "result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected = { \"hBaseInstalled\":", "{ 'properties': { 'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': { 'properties':", "{'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res)", "# Recommend for not existing DB_FLAVOR and http enabled, HDP-2.3", "expected) def test_validateStormSiteConfigurations(self): configurations = { \"storm-site\": { \"properties\": {", "by datanode to store HDFS data', 'type': 'configuration' } ]", "'configuration' } ] self.assertEquals(res, expected) # 2 partitions host['Hosts']['disk_info'] =", "[ { \"StackServices\": { \"service_name\": \"RANGER\" }, \"components\": [ {", "{'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site':", "'It is recommended to set value value2 for property property1',", "'components': [] }, { 'name': 'host-group-2', 'components': [{ 'name': 'DATANODE'", "170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] = 1", "\"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie Server\", \"is_client\": \"false\", \"is_master\":", ": \"/\" } ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace)", "'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message': errorMsg, 'level': 'WARN'},", "= self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1]) #", ": \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]}", "\"Ganglia Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\",", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "\"HDFS\" }, \"components\" : [ { \"StackServiceComponents\" : { \"cardinality\"", "None) self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn) # non-local FS, HDFS", "'') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\": {", "ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups':", "} self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ { \"name\":", "configurations = {} components = [] host_item = { \"Hosts\"", "} }, { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] }", "{ 'host_groups': [{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1'", "3072, \"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result =", "hostsNames): hosts = { \"items\": [] } for hostName in", "[ { \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" :", "= 170.66666666666666 expected[\"reservedRam\"] = 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components,", "} }, \"hbase-env\": { \"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\",", "= { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter',", "component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping", "are not added to any free hosts (not having any", "item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"] = item[\"host\"] except KeyError, err:", "{} services = {\"configurations\": configurations, \"services\": []} clusterData = {", "}] } } \"\"\" # Assert that the list is", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more space available hostInfo[\"disk_info\"].append( {", "\"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'} } }", "\"items\": [ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1, \"host_name\":", "services[\"configurations\"] = { \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", }", ": \"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\" :", "self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self):", "changedConfigurations services['configurations'] = configurations expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}},", "hostGroupName = hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for binding in bindings", "self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz =", "HDP-2.3\") # Recommend for DB_FLAVOR ORACLE and https enabled, HDP-2.2", "self.assertEquals(res, res_expected) # 2) fail: namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize']", "= {'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "HDP-2.3\") # Recommend for DB_FLAVOR POSTGRES and https enabled, HDP-2.3", "self.assertEquals(res, expected) properties['metrics.reporter.register'] = '' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations,", "\"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\",", "result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations =", "with open(stackAdvisorPath, 'rb') as fp: stack_advisor = imp.load_module( 'stack_advisor', fp,", "\"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\",", "= [ {\"message\": \"Exactly 2 Ganglia Monitor components should be", "'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari Metrics disk space", "\"/default-rack\", \"total_mem\" : 2097152 } }, { \"href\" : \"/api/v1/hosts/host2\",", "'0.8'} } } } items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations)", "mountpoint with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"7\",", "\"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\",", "{ \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } } ] }, {", "services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result", "def test_getZKHostPortString(self): configurations = { \"zoo.cfg\": { \"properties\": { 'clientPort':", "def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ { \"name\": \"HDFS\", \"components\": [", "\"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }], \"configurations\":", "[]} clusterData = { \"containers\" : 5, \"ramPerContainer\": 256 }", "self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP values\") # Test Ranger Audit", "hostInfo, reqiuredDiskSpace) == None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024)", "\"host\": \"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo", ": '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host = { \"href\" :", "\"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666,", "= {\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\" : \"2.6.0.2.2\" },", "{ \"href\" : \"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\" : 1,", "\"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\": 512,", "\"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152, \"disk_info\": [ { \"available\":", "\"https://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services,", "def test_validationMinMax(self): configurations = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\":", "= { \"totalAvailableRam\": 2048 } ambariHostName = socket.getfqdn() expected =", "6, \"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\":", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with more space available hostInfo[\"disk_info\"].append(", "{ 'delete': 'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts)", "'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN', 'message': 'Should be set to", "\"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": { \"properties\": {", "'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services", "\"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result, expected) def", "hosts) self.assertEquals(nodemanager, None) # unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\",", "properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value2\"} expected =", "] } ] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations =", "= self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Ganglia Monitor component", "] } expected = { \"hBaseInstalled\": True, \"components\": components, \"cpu\":", "= { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"},", "'hbase-site': { 'properties': { 'hbase.superuser': 'hbase123' } }, \"hbase-env\": {", "\"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ],", "\"components\": components, \"cpu\": 8, \"disk\": 8, \"ram\": 6, \"reservedRam\": 2,", "}, 'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } }", "try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try:", "except in compliance with the License. You may obtain a", "only 1 partition, enough disk space, no warnings res =", "{\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\",", "low space available hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" :", "{ \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations", "= os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py')", "services = self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"])", "Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]}", "= {} services = { \"services\": [ { \"StackServices\": {", "\"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\":", "} }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] =", "'1024'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user':", "{ 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed property", "self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts)", "\"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host2\", \"rack_info\" : \"/default-rack\",", "available hostInfo[\"disk_info\"].append( { \"available\" : \"7\", \"type\" : \"ext4\", \"mountpoint\"", "UID_MIN 200 UID_MIN 500 \"\"\" def __exit__(self, exc_type, exc_val, exc_tb):", "len(l1) == len(l2) or not sorted(l1) == sorted(l2): raise AssertionError(\"list1={0},", "test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations = {} components = []", "'Value should be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected)", "[ {\"message\": \"Ganglia Monitor component should be installed on all", "= item[\"host\"] except KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def", "= { \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 } expected", "\"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" :", "{} services = { \"services\": [ ], \"configurations\": configurations }", "True, \"hostnames\": [\"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts", "+ root partition + hbase.rootdir == hbase.tmp.dir warnings properties =", "{ 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env':", "\"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\": 3,", "componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap =", "services = { \"services\": [ { \"StackServices\": { \"service_name\": \"ZOOKEEPER\"", "AMS configurations = {} services = { \"services\": [ ],", "\"properties\": { \"http.enabled\": \"false\", \"https.service.port\": \"8888\", } } } services['configurations']", "self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {'message': 'Queue is not exist,", "\"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\"", "512, \"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] }", "}, \"hbase-env\": { \"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", }", "'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' }, { 'message':", "'message': 'Value is less than the recommended default of 1024',", "result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components = [] hosts", "\"hdfs\", \"proxyuser_group\": \"users\" } }, \"hive-env\": { \"properties\": { \"webhcat_user\":", "should be installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result)", "{\"message\": \"Host is not used\", \"level\": \"ERROR\", \"host\": \"host2\"} ]", "\"hostnames\": [\"host1\", \"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts", "\"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, ], \"configurations\":", "available hostInfo[\"disk_info\"].append( { \"available\" : \"6\", \"type\" : \"ext4\", \"mountpoint\"", "import imp import os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory,", "to HDFS.', 'type': 'configuration' }, { 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site',", "[ { \"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] } }", "'Value is less than the recommended default of 1024', 'type':", "\"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\",", "{ \"items\" : [] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components,", "\"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\",", ": \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } }) expected[\"referenceHost\"] =", "\"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\": 3072,", "(ASF) under one or more contributor license agreements. See the", "== len(l2) or not sorted(l1) == sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1,", "}, { \"href\" : \"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\" :", "\"\"\" Recommendation received should be as below: { 'blueprint': {", "= configurations expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\":", "if the component has been installed in the cluster before", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"2\", \"type\" : \"tmpfs\",", "for cardinality ALL even if the component has been installed", "\"items\" : [ { \"Hosts\" : { \"cpu_count\" : 6,", "\"is_master\": True, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts", "\"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\": 3072,", "\"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # local FS,", "services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\",", "}, \"components\": [] }, { \"StackServices\": { \"service_name\": \"FALCON\" },", "component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"]", "properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false'", "\"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie Server\", \"is_client\": \"false\",", "}}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\",", "{} components = [] host_item = { \"Hosts\" : {", "= self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Exactly 2 Ganglia", "\"hive-env\": { \"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" } },", "recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn != None) self.assertEquals({'message': 'It is not", "'1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' : '256'} properties = {'namenode_heapsize':", "'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {} recommendedDefaults =", "\"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData = { \"totalAvailableRam\": 2048 } ambariHostName", "\"ph_cpu_count\" : 1, \"public_host_name\" : \"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\"", "{ \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\":", "'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties,", "'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site':", "and https enabled, HDP-2.2 configurations = { \"admin-properties\": { \"properties\":", "hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations,", "\"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:7777\" } } } recommendedConfigurations", "[host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) #", "= {} for hostGroup in blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos", "\"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo =", "\"/\" } ] } } hosts = { \"items\" :", "expected = { \"yarn-env\": { \"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name':", "\"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" },", "'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user': 'hive',", "or more contributor license agreements. See the NOTICE file distributed", "# Recommend for DB_FLAVOR POSTGRES and https enabled, HDP-2.3 configurations", "should be installed on all hosts in cluster.\", \"level\": \"ERROR\"}", "\"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"]", "services, hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not installed nodemanager", "\"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\" Recommend", "Software Foundation (ASF) under one or more contributor license agreements.", "{ \"hbase_user\": \"hbase123\" } } } } expected = {", "}, \"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\",", "recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' : '256'}", "= {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend", "distributed with this work for additional information regarding copyright ownership.", "dfs.dir & hbase.rootdir crosscheck + root partition + hbase.rootdir ==", "\"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host2\",", "}}] }, { \"StackServices\": { \"service_name\": \"OOZIE\" }, \"components\": [{", "'namenode_opt_maxnewsize' : '256'} properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300',", "For already installed services, recommendation for installed components should match", "self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) # with AMS configurations", "for component in hostGroup[\"components\"]: componentName = component[\"name\"] try: actualComponentHostsMap[componentName] except", "{ 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults = { 'metrics.reporter.register':", "'host_groups': [{ 'name': 'host-group-1', 'components': [] }, { 'name': 'host-group-2',", "expected[\"hdfs-site\"] = { 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices':", "self exists_mock.return_value = True open_mock.return_value = MagicFile() return self.get_system_min_uid_real() def", "# non-local FS, WASB properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1',", "[ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }, \"components\": [ {", "[] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}},", "expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"]", "\"hive_user\": \"hive\" } }, \"oozie-env\": { \"properties\": { \"oozie_user\": \"oozie\"", "= 256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"] =", "expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:7777\" }", "HDFS data', 'type': 'configuration' } ] self.assertEquals(res, expected) # incorrect", ": [ { \"StackServices\" : { \"service_name\" : \"HDFS\" },", "'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res =", "Unless required by applicable law or agreed to in writing,", "recommended default of 1024', 'type': 'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'},", "\"available\": str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\" :", "'message': 'Value is greater than the recommended maximum of 2047", ": \"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 1048576 } },", "hosts = { \"items\" : [ { \"href\" : \"/api/v1/hosts/host1\",", "should be integer\", \"level\": \"ERROR\"}, {\"message\": \"Value should be set\",", "\"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\"", "} }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\",", "\"falcon\" } } } hosts = { \"items\": [ {", "hosts = self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap =", "as hbase.rootdir to store metrics data', 'type': 'configuration' }, {", "space hostInfo = {\"disk_info\": [ { \"available\" : \"1048578\", \"type\"", "{ \"name\": \"HDFS\", \"components\": [ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\":", "Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\": { \"properties\":", "\"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties =", "{\"mountpoint\" : \"/vagrant\"} ] } }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"]", "list is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE", "except KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList", "] } ], \"configurations\": {} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services)", "2 Ganglia Monitor components should be installed in cluster.\", \"level\":", "and https enabled, HDP-2.2\") # Test Recommend LDAP values services[\"ambari-server-properties\"]", "\"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] } }, ]}", "with 2 hosts - pick minimum memory servicesList.append(\"YARN\") services =", "\"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData,", "self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\":", "\"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" } }, \"hive-env\": {", "res_expected = [{'config-type': 'hadoop-env', 'message': 'Value is less than the", "{ \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\"", "hbase.rootdir == hbase.tmp.dir warnings properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir'", "[ { \"available\" : '1', \"type\" : \"ext4\", \"mountpoint\" :", "= { \"storm-site\": { \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }", "= self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self):", "\"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}", "expectedItems = [ {\"message\": \"Host is not used\", \"level\": \"ERROR\",", "express or implied. See the License for the specific language", "\"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256',", "2047 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration'", "\"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ) self.assertEquals([\"/\"],", "configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts)", ": { \"cpu_count\" : 8, \"total_mem\" : 6291456, \"disk_info\" :", "[ { \"StackServices\": { \"service_name\": \"SERVICE\" }, \"components\": [ {", ": \"/\" } ] recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir':", "recommendedDefaults = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\":", "self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo", "hbase.rootdir in distributed mode properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir'", "'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = { \"services\": [ { \"StackServices\": {", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\"", "\"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected =", "\"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None)", "of recommendation received during Add service operation. For already installed", "\"components\": [ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True,", "\"falcon_user\": \"falcon\" } } } hosts = { \"items\": [", "patch, MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self): import imp import os", "is less than the recommended default of 512\", \"level\": \"WARN\"},", "not corresponds to existing YARN leaf queue', 'level': 'ERROR'} ]", "[{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\": True}] } ]", "\"/vagrant\"} ] } } hosts = { \"items\" : [host_item", "[ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } }", "\"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\",", "123.54 } expected = { \"mapred-site\": { \"properties\": { 'mapreduce.job.queuename':", "'name': 'DATANODE' }] }] }, 'blueprint_cluster_binding': { 'host_groups': [{ 'hosts':", "expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"http://host1:7777\" }", "\"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/\"},", "in the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open')", "\"\"\" Recommend on all hosts for cardinality ALL even if", "= [ { \"name\": \"YARN\", \"components\": [] } ] services", "\"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\",", "\"mountpoint\" : \"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with", "'ams-hbase-site', 'level': 'WARN', 'message': 'It is not recommended to use", "hosts) expected = [ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level':", "{ \"stack_name\" : \"HDP\", \"stack_version\" : \"2.0.6\" } } services[\"services\"]", "partition + hbase.rootdir == hbase.tmp.dir warnings properties = { 'hbase.rootdir':", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"]", "\"file:///var/dir\"} # only / mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults,", "childValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\":", "hosts) expectedItems = [ {\"message\": \"Exactly 2 Ganglia Monitor components", "'message': 'It is not recommended to use root partition for", "] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[", "self.assertTrue(res) #Value is begger then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'}", "} }, 'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } }", "self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties = {\"property1\": \"value1\"} recommendedDefaults =", "} }, \"hbase-env\": { \"properties\": { \"hbase_user\": \"hbase123\" } }", "{ 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', }", "obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required", "500 \"\"\" def __exit__(self, exc_type, exc_val, exc_tb): pass def __enter__(self):", "'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1',", "that the list is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert", "namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] = '255' res_expected", "] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2)", "} } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations, expected) def", "properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None)", "'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false',", "'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems =", "170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result, expected) def prepareHosts(self, hostsNames): hosts", "= {} services = '' hosts = '' #Default configuration", "service operation. For already installed services, recommendation for installed components", "3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts,", "{'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}},", "{ \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\",", "hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] = 3.0", "{'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize':", "\"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test - Cluster data", "} }, \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } },", "\"host1\", \"host2\" ] }, \"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{", "'type': 'configuration' } ] self.assertEquals(res, expected) # incorrect hbase.rootdir in", "\"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}] }", "hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems =", "= [] for serviceInfo in servicesInfo: nextService = {\"StackServices\":{\"service_name\" :", "components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected)", "'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData,", "hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with low", "\"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" : 4, \"total_mem\" : 500000,", "\"embedded\" } } } recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir':", "test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ { \"name\": \"YARN\", \"components\": [] }", "{\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } hosts", "{'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}},", ", but not preferable - no warning hostInfo[\"disk_info\"].append( { \"available\"", "\"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]},", "\"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" } }, \"oozie-env\": { \"properties\": {", "None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR POSTGRES and https enabled,", "\"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"},", "\"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\",", "'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}},", "mock.mock import patch, MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self): import imp", "http enabled, HDP-2.3\") # Recommend for DB_FLAVOR POSTGRES and https", "} siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\"", "exist, or not corresponds to existing YARN leaf queue', 'level':", "\"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[", "\"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\": { \"properties\": {", "!= None) self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn) # non-local FS,", "= os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as", "= component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return", "} self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\" Recommend on all hosts", "hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\",", "self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self,", "{ \"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\":", "os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor =", "{\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\"", "\"c6402.ambari.apache.org\"] }}] }, { \"StackServices\": { \"service_name\": \"OOZIE\" }, \"components\":", "} }, { \"href\" : \"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\"", "of 512\", \"level\": \"WARN\"}, {'message': 'Value should be set for", "except KeyError, err: actualComponentHostsMap[componentName] = [] for host in hosts:", "\"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 1048576 } }, ]", "expected) properties = {\"property1\": \"value1\"} recommendedDefaults = {} expected =", "is less than the recommended default of 1024', 'type': 'configuration',", "{ 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res", "\"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{", "expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"]", "self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) # Test - Cluster", "\"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations']", "\"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\",", "0, \"ram\": 0, \"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\":", "[\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, { \"StackServices\": { \"service_name\": \"OOZIE\" },", "configurations, services, hosts) expected = [ { 'config-name': 'hbase.rootdir', 'config-type':", "512, \"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\":", "\"Test Ranger Audit properties\") def test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\":", "\"disk\": 0, \"ram\": 0, \"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\": 256,", "\"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True,", "= self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList", "= [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\":", "test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "] }, \"dependencies\":[ ] }, ], }], \"configurations\": {} }", "= [ {\"message\": \"Host is not used\", \"host\": \"host2\", \"level\":", "\"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList,", "services, hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services = { \"services\":", "\"3\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/boot/grub\" } ) self.assertEquals([\"/\"],", "during Add service operation. For already installed services, recommendation for", "is recommended to be deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] =", "[ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\",", "}, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\":", "in hostGroup[\"components\"]: componentName = component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError, err:", "[ {\"message\": \"Value is less than the recommended default of", "[] for component in serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\": {", "'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties':", "mode', 'type': 'configuration' } ] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "\"ext4\", \"mountpoint\" : \"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected)", "expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components = [] hosts", "\"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\",", "the specific language governing permissions and limitations under the License.", "hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for binding in bindings if binding[\"name\"]", "return services def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings", "\"display_name\": \"Hive Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\":", "hosts = { \"items\" : [ { \"Hosts\" : {", ": \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" :", "\"service_name\": \"HDFS\" }, \"components\": [] }, { \"StackServices\": { \"service_name\":", "170.66666666666666 expected[\"reservedRam\"] = 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services)", "assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap", ": \"3\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } )", "\"mountpoint\": \"/\" } ] } } hosts = { \"items\"", "'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address': { 'delete':", "'config-type': 'storm-site', 'level': 'WARN', 'message': 'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter", "/grid/0 mountpoint - warning hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\"", "in hostsNames: nextHost = {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return hosts", "actualItems = [] for item in result[\"items\"]: next = {\"message\":", "to existing YARN leaf queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result)", "License. ''' import socket from unittest import TestCase from mock.mock", "{ \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\":", "self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP values\")", "\"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\":", "expected = { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 6, \"disk\":", "than the recommended default of 1024', 'type': 'configuration', 'config-name': 'namenode_heapsize',", "Test that already installed slaves are not added to any", "or agreed to in writing, software distributed under the License", "this file to you under the Apache License, Version 2.0", "# root mountpoint with low space available hostInfo[\"disk_info\"].append( { \"available\"", "} expected = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\":", "{ \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\":", "\"type\" : \"ext4\", \"mountpoint\" : \"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\",", "\"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"http://host1:7777\" } } } recommendedConfigurations", "except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except", "[ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\",", "}, \"oozie-env\": { \"properties\": { \"oozie_user\": \"oozie\" } }, \"falcon-env\":", "space for partition / is 1G\" # local FS, enough", "{ \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] } } ] } ],", "services[\"changed-configurations\"] = changedConfigurations services['configurations'] = configurations expected = {'oozie-env': {'properties':", "Add service operation. For already installed services, recommendation for installed", "{ \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 } expected =", "non-local FS, HDFS properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo,", "\"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\":", "configurations = {} services = '' hosts = '' #Default", "{ 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' }", "i in range(1, 300)] } services = { \"services\" :", "} } recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties =", "\"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\":", "\"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } }", "'256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\"", "def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components = [] hosts =", "{ \"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\":", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"SERVICE\" },", "/ partition for storing metrics data. ' '/ is already", "{} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit", "{} expected = { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080',", "\"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}", "to store metrics data', 'type': 'configuration' }, { 'config-name': 'hbase.rootdir',", "\"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } parentValidators = { \"HDFS\": {\"hdfs-site\":", "] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts)", "\"mountpoint\" : \"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties,", ": \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" :", "a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by", "{ \"available\" : str(15<<30), # 15 GB \"type\" : \"ext4\",", "= [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res,", "\"StackServices\": { \"service_name\": \"HIVE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\":", "512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test - Cluster data with", ": \"/vagrant\"} ] } }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] =", ": '256'} properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize'", "mountpoint with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"6\",", "\"total_mem\": 2097152, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] }", "recommendedDefaults, configurations, services, None) expected = [ {'config-name': 'metrics.reporter.register', 'config-type':", "hosts) expectedItems = [ {\"message\": \"Between 0 and 1 Ganglia", "test_recommendOnAllHosts(self): \"\"\" Recommend on all hosts for cardinality ALL even", "= {} clusterData = { \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\":", "\"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\",", "services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([]) result", "[\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\",", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"]", "{\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\":", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo)", "\"Value should be integer\", \"level\": \"ERROR\"}, {\"message\": \"Value should be", "if not len(l1) == len(l2) or not sorted(l1) == sorted(l2):", "\"Ambari Metrics disk space requirements not met. \\n\" \\ \"Recommended", ": \"1048578\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]}", "as below: { 'blueprint': { 'host_groups': [{ 'name': 'host-group-1', 'components':", "{ \"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\":", "hostInfo = {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"],", "\"StackServices\": { \"service_name\": \"SERVICE\" }, \"components\": [ { \"StackServiceComponents\": {", "as fp: stack_advisor = imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb',", "UID_MIN 500 \"\"\" def __exit__(self, exc_type, exc_val, exc_tb): pass def", "hbase.rootdir crosscheck + root partition + hbase.rootdir == hbase.tmp.dir warnings", "res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = [", "res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = []", "\"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170,", "serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"],", "\"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\"", "} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services", ": \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host2\", \"rack_info\" :", "= self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = {", "# incorrect hbase.rootdir in distributed mode properties = { 'hbase.rootdir':", "expected, \"Test for DB_FLAVOR ORACLE and https enabled, HDP-2.2\") #", "{\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\":", "# 15 GB \"type\": \"ext4\", \"mountpoint\": \"/\" } ] }", "[{ 'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1' }, { 'hosts': [{", "'property1', hostInfo, reqiuredDiskSpace) == None) # non-local FS, WASB properties", "{\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } parentValidators", "} }, \"ranger-site\": { \"properties\": { \"http.enabled\": \"false\", \"https.service.port\": \"8888\",", "imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl',", "configurations = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\":", "true for distributed mode', 'type': 'configuration' } ] self.assertEquals(res, expected)", "{'message': 'It is recommended to set value value2 for property", ": \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" :", "\"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo = [ { \"name\":", "'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'It is not", "8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\":", "for not existing DB_FLAVOR and http enabled, HDP-2.3 services =", "\"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData,", "= { 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster',", "list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems, result): actualItems = [] for", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"SERVICE\" }, \"components\":", "to set value value2 for property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties,", "} } hosts = { \"items\" : [ host ]", "}, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\",", "'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected)", "\"service_name\": \"RANGER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\",", "\"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\",", "\"services\": [ { \"StackServices\": { \"service_name\": \"ZOOKEEPER\" }, \"components\": [", "\"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" } }, \"oozie-env\": {", "configurations } # only 1 partition, enough disk space, no", "\"mountpoint\" : \"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults", "None) properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value2\"} expected", "\"StackServices\": { \"service_name\": \"RANGER\" }, \"components\": [ { \"StackServiceComponents\": {", "configurations, services, hosts) expected = [] self.assertEquals(res, expected) # 1", "recommendedDefaults, configurations, services, hosts) expected = [ {'config-name': 'hbase.rootdir', 'config-type':", "\"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]} ]", "'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using / partition", "componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1, l2):", "= \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations = {} services", "[ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'In", "'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed property should", "= { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080', } },", "1, \"host_name\" : \"host2\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\",", "\"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] },", "} # only 1 partition, enough disk space, no warnings", "{ \"services\": [ ], \"configurations\": configurations } expected = {", "to you under the Apache License, Version 2.0 (the \"License\");", "\"StackServices\": { \"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations }", "\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\" Recommend on all", "self.assertEquals(res, expected) def test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\": {\"service_name\" :", "{\"ambari-server.user\":\"ambari_user\"} } clusterData = { \"totalAvailableRam\": 2048 } ambariHostName =", "hosts) expectedItems = [ {\"message\": \"Ganglia Monitor component should be", "data with 1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None)", "[\"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "\"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\":", "}, ]} services = { \"services\": [ { \"StackServices\": {", "{ \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [] }, {", "{ \"properties\": { \"hbase_user\": \"hbase123\" } } } } expected", "def test_validateNonRootFs(self): hostInfo = {\"disk_info\": [ { \"available\" : \"2\",", "open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py',", "\"NOT_EXISTING\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\":", "'true' } }, 'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' }", "'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address': { 'delete': 'true' }", "{\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\":", "\"mountpoint\" : \"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with", "'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups':", ": \"vboxsf\", \"mountpoint\" : \"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "= {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts':", ": \"HDFS\" }, \"components\" : [ { \"StackServiceComponents\" : {", "\"properties\": { \"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\": { \"properties\": {", "less than the recommended default of 1024', 'type': 'configuration', 'config-name':", "FS, HDFS properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace)", "{ \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\"", "the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or", "\"type\" : \"ext4\", \"mountpoint\" : \"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "met. \\n\" \\ \"Recommended disk space for partition / is", "\"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\":", "'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address': { 'delete': 'true' } }", "False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\",", "properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = { \"services\":", "http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]} ] } ] services", "} ] } ], \"configurations\": configurations } result = self.stackAdvisor.getZKHostPortString(services)", "6, \"ram\": 48, \"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\":", "of 1024', 'type': 'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize',", "'', '') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\":", "\"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]} properties =", "one or more contributor license agreements. See the NOTICE file", "= True open_mock.return_value = MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\",", "\"total_mem\" : 1048576 } }, ] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\",", "\"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } }, { \"StackServiceComponents\":", "\"stack_version\" : \"2.3\", }, \"services\": [ { \"StackServices\": { \"service_name\":", "\"ext4\", \"mountpoint\" : \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo)", ": \"2.0.6\" } } services[\"services\"] = [] for serviceInfo in", "err: actualComponentHostsMap[componentName] = [] for host in hosts: if host", "metrics temporary data. ' '/ partition is already used as", "\"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\":", "self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations = { \"zoo.cfg\": { \"properties\":", "= os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = {", "requirements not met. ' '\\nRecommended disk space for partition /", "'delete': 'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations,", "permissions and limitations under the License. ''' import socket from", "self.assertEquals(result, expected) # Test - Cluster data with 2 hosts", "'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults,", "should be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties", "\"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } parentValidators = {", "\"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\"", "} expected = { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080'", "= {} services = {\"configurations\": configurations, \"services\": []} clusterData =", "self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations = {} services = ''", "\"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\",", "\"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\": 512,", "\"is_master\": component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError:", "} } } services['configurations'] = configurations expected = { \"admin-properties\":", "\"configurations\": configurations } # positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations,", "{ \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } }, {", "170.66666666666666 } self.assertEquals(result, expected) def prepareHosts(self, hostsNames): hosts = {", "'service_check.queue.name': 'default' } }, \"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\",", "\"ext4\", \"mountpoint\" : \"/\" } ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults,", "properties = {'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services,", "\"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}]", "\"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\":", "1G\" # local FS, enough space hostInfo = {\"disk_info\": [", "\"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\": True}] } ] services =", "[{ \"size\": '8', \"mountpoint\": \"/\" }] } }, ]} services", "'1024'} properties = {'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations,", "\"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "enabled, HDP-2.3\") # Recommend for DB_FLAVOR POSTGRES and https enabled,", "components, \"cpu\": 8, \"disk\": 8, \"ram\": 6, \"reservedRam\": 2, \"hbaseRam\":", "configurations, services, None) expected = [ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site',", "\"hostnames\": [\"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts =", "3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] = 170", "socket from unittest import TestCase from mock.mock import patch, MagicMock", "[ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\":", "{ \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:7777\" } } }", "available hostInfo[\"disk_info\"].append( { \"available\" : \"5\", \"type\" : \"vboxsf\", \"mountpoint\"", "= stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that", "expectedItems = [ { 'message': 'Value is greater than the", "{ 'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\": { \"properties\": { \"fs.defaultFS\":", "\"Host is not used\", \"host\": \"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems,", ": \"/default-rack\", \"total_mem\" : 2097152, \"disk_info\": [ { \"available\": str(15<<30),", "yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value should be integer\", \"level\": \"ERROR\"},", ": \"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" :", "{ \"storm-site\": { \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, }", "[\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} }", "clusterData, None, None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = []", "' 'to report the metrics to Ambari Metrics service.', 'type':", "\"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{ \"size\": '8', \"mountpoint\":", "def prepareServices(self, servicesInfo): services = { \"Versions\" : { \"stack_name\"", "{'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*',", "\"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults = {", "\"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations, expected)", "\"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } } }", "recommended default of 256', 'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults,", "def test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\":", ": \"1+\", \"component_category\" : \"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\" :", "\"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\" ] }", "\"cpu_count\" : 1, \"host_name\" : \"host2\", \"os_arch\" : \"x86_64\", \"os_type\"", "[ { \"name\": \"YARN\", \"components\": [] } ] services =", "{ \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" } }, \"hive-env\": { \"properties\":", "actualComponentHostsMap = {} for hostGroup in blueprintMapping: hostGroupName = hostGroup[\"name\"]", "} properties = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = {", "\"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } } ] }, { \"StackServices\":", "\"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }]", "exc_type, exc_val, exc_tb): pass def __enter__(self): return self exists_mock.return_value =", "\"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations, expected)", "'hadoop-env', 'message': 'Value is less than the recommended default of", "\"items\": [] } for hostName in hostsNames: nextHost = {\"Hosts\":{\"host_name\"", "'../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = { \"services\": [", "\"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\": {", "imp import os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py')", "]} properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) ==", "\"falcon-env\": { \"properties\": { \"falcon_user\": \"falcon\" } } } hosts", "\"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\",", "\"property1\"), expected) properties = {\"property1\": \"value1\"} recommendedDefaults = {} expected", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with low space available hostInfo[\"disk_info\"].append( {", "services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts", "1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result, expected) def", "\"total_mem\" : 2097152 } }, { \"href\" : \"/api/v1/hosts/host2\", \"Hosts\"", "} ] } ], \"configurations\": { \"admin-properties\": { \"properties\": {", "\"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/var\" }", "[ { \"Hosts\" : { \"cpu_count\" : 8, \"total_mem\" :", "\"category\": \"MASTER\", \"is_master\": True}] } ] services = self.prepareServices(servicesInfo) localhost", "\"SLAVE\", \"is_master\": False}] } ] services = self.prepareServices(servicesInfo) hosts =", "configurations = {} services = { \"services\": [ ], \"configurations\":", "\"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations'] = configurations expected = {'oozie-env':", "services['configurations'] = configurations expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site':", "configurations = { \"storm-site\": { \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" }", "\"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn != None)", "\"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {}", "{ \"StackServices\": { \"service_name\": \"RANGER\" }, \"components\": [ { \"StackServiceComponents\":", "= os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath)", "component installed) as part of recommendation received during Add service", "\"value2\"} expected = {'message': 'It is recommended to set value", "'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData,", "{'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}}", "under the Apache License, Version 2.0 (the \"License\"); you may", "services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP values\") # Test", "def checkEqual(self, l1, l2): if not len(l1) == len(l2) or", "{\"disk_info\": [ { \"available\" : \"1048578\", \"type\" : \"ext4\", \"mountpoint\"", "# Assert that DATANODE is placed on host-group-2 self.assertEquals(recommendations['blueprint']['host_groups'][1]['components'][0]['name'], 'DATANODE')", "{ \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\":", "} }, \"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\",", "#Default configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '1024'}", "} self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) # with AMS", "{\"property1\": \"file:///var/dir\"} # only / mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties,", "} }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\",", "'256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address", "def test_validationCardinalityExactAmount(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", "{ \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } } } } expected", "\"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False}] }", "self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0)", "def test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir':", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "hostInfo) == None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg =", "} } services['configurations'] = configurations expected = { \"admin-properties\": {", "result) def test_recommendOnAllHosts(self): \"\"\" Recommend on all hosts for cardinality", "data', 'type': 'configuration' }, { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level':", "\"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", } } } services['configurations']", "\"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\", \"category\":", "\"configurations\": { \"hbase-site\": { \"properties\": { \"hbase.superuser\": \"hbase\" } },", "is begger then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties =", "import patch, MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self): import imp import", "\"mountpoint\" : \"/\" } ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo,", "= 170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] =", "} }, { \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] }", "GB \"type\": \"ext4\", \"mountpoint\": \"/\" } ] } } hosts", "even if the component has been installed in the cluster", "\"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host1\",", "self.assertEquals(result, expected) def prepareHosts(self, hostsNames): hosts = { \"items\": []", "components, \"cpu\": 6, \"disk\": 6, \"ram\": 48, \"reservedRam\": 6, \"hbaseRam\":", "\"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } },", "] }, ], \"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\":", "[\"host1\"] } } ] }, ], \"configurations\": { \"admin-properties\": {", "result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"] }", "\"amMemory\": 170.66666666666666 } self.assertEquals(result, expected) def prepareHosts(self, hostsNames): hosts =", "{ \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\":", "recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test", "{'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN', 'message': 'Value is less", "256', 'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '')", "# 2 partitions host['Hosts']['disk_info'] = [ { \"available\": str(15<<30), #", "/var mountpoint, which is non-root , but not preferable -", "corresponds to existing YARN leaf queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems,", "self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\" Recommend on all hosts for", "[ { \"available\" : \"1048578\", \"type\" : \"ext4\", \"mountpoint\" :", "in hosts: if host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName", "in writing, software distributed under the License is distributed on", "\"available\" : \"5\", \"type\" : \"vboxsf\", \"mountpoint\" : \"/vagrant\" }", ": \"ext4\", \"mountpoint\" : \"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "required by applicable law or agreed to in writing, software", "\"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat Server\", \"is_client\": \"false\", \"is_master\": \"true\",", "configurations, services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations = {} #", "servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\",", "} } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self):", "= \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations", "result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def", "'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\",", "self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]),", "}, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'} }", "expected) def test_recommendYARNConfigurations(self): configurations = {} services = {\"configurations\": configurations,", "hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def", "self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList =", "\"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } } ] }", "#Value is less then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties", "\"configurations\": configurations } # only 1 partition, enough disk space,", "\"dependencies\":[ ] }, ], }], \"configurations\": {} } hosts =", "warnings properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", "\"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\":", "self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {\"property1\": \"value1\"} recommendedDefaults =", "} expected = { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 6,", "True, \"components\": components, \"cpu\": 6, \"disk\": 6, \"ram\": 48, \"reservedRam\":", "{ \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\"", "\"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\": {\"properties\":", "\"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] },", "= [] hosts = { \"items\" : [ { \"Hosts\"", "'*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts':", "\"ram\": 48, \"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816,", "self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Ganglia Monitor component should", "\"hostnames\": [\"host1\"] } } ] }, { \"StackServices\": { \"service_name\":", "\"Hosts\" : { \"cpu_count\" : 1, \"host_name\" : \"host1\", \"os_arch\"", "partition for hbase.rootdir', 'type': 'configuration' }, { 'config-name': 'hbase.tmp.dir', 'config-type':", "'/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': {", "= component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] =", "}, { \"StackServices\": { \"service_name\": \"OOZIE\" }, \"components\": [{ \"href\":", "\"available\" : \"3\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" }", "\"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo =", "'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' }, { 'message': 'Value is", "] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components =", "{\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\":", "services, hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators = { \"HDFS\":", "distributed under the License is distributed on an \"AS IS\"", "\"available\" : \"3\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/boot/grub\" }", "[ { \"available\" : \"2\", \"type\" : \"ext4\", \"mountpoint\" :", "component should be installed on all hosts in cluster.\", \"level\":", "[ { 'message': 'Value is greater than the recommended maximum", "= [] host_item = { \"Hosts\" : { \"cpu_count\" :", "unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self):", "stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb') as fp:", "{ 'hbase.superuser': 'hbase123' } }, \"hbase-env\": { \"properties\": { \"hbase_master_heapsize\":", "CONDITIONS OF ANY KIND, either express or implied. See the", "', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration' }", "test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\"", "{\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services,", "{'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups':", "] } ], }], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\"", "\"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {} expected = {", ": \"/default-rack\", \"total_mem\" : 1048576 } }, ] } datanodes", "\"\"\" # Assert that the list is empty for host-group-1", "} } ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\",", "\"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1,", "test_getServicesSiteProperties(self): import imp, os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory,", "\"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"},", "of 256', 'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '',", "is already used as hbase.rootdir to store metrics data', 'type':", "'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = { \"services\": [ { \"StackServices\":", "items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable", "}, { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [ {", "self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received should be as below: {", "[ {\"message\": \"Between 0 and 1 Ganglia Server components should", "\"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, {", "actualComponentHostsMap[componentName] = [] for host in hosts: if host not", "1, \"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\":", "HDP-2.2\") # Test Recommend LDAP values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\"", "pick minimum memory servicesList.append(\"YARN\") services = services = {\"services\": [{\"StackServices\":", ": \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/var\" } )", "be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self):", "{ \"hBaseInstalled\": False, \"components\": components, \"cpu\": 0, \"disk\": 0, \"ram\":", "\"WebHCat Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\",", "clusterData, services, hosts) self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address is recommended", "{ \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, {", "properties = {'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services,", "'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase',", "/ partition for storing metrics temporary data. ' '/ partition", "- no warning hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" :", "clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit properties\") def", "\"cpu\": 0, \"disk\": 0, \"ram\": 0, \"reservedRam\": 1, \"hbaseRam\": 1,", "{ \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", } } } clusterData =", "actualHosts) def checkEqual(self, l1, l2): if not len(l1) == len(l2)", "configurations, services, hosts) expected = [ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site',", ": \"ext4\", \"mountpoint\" : \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1',", "expected = { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080', }", "hosts[\"items\"].append(nextHost) return hosts def prepareServices(self, servicesInfo): services = { \"Versions\"", "self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems = [ { 'message': 'Value is", "recommendedDefaults, configurations, services, hosts) self.assertFalse(res) #Value is less then expected", "childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "recommendedDefaults, \"property1\"), expected) properties = {\"property1\": \"value1\"} recommendedDefaults = {}", "= {\"property1\": \"value1\"} recommendedDefaults = {} expected = {'level': 'ERROR',", "when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations']", "\"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\" : \"host1\",", "self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message': errorMsg, 'level':", "[ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia", "[ { \"StackServices\" : { \"service_name\" : \"HDFS\" }, \"components\"", "], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\"", "\"total_mem\" : 50331648, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\"", "{'message': 'Value should be set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\":", "{ \"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } } }", "hosts = { \"items\" : [ host ] } services", "\"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties,", "components = [] host_item = { \"Hosts\" : { \"cpu_count\"", "} ] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ {", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with", "hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as fp: stack_advisor =", "} ) recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults,", "#test line UID_MIN 200 UID_MIN 500 \"\"\" def __exit__(self, exc_type,", "configurations, '', '') self.assertEquals(res, res_expected) # 2) fail: namenode_heapsize, namenode_opt_maxnewsize", "def get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object): def read(self): return \"\"\"", "sorted(l1) == sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems,", "= {} expected = {'level': 'ERROR', 'message': 'Value should be", "should be set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self):", "socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap", "that already installed slaves are not added to any free", "'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems = []", "\"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more space", "\"Hive Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\",", "be set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value should be", ": \"/\" } ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services,", "\"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1,", "}, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\":", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\":", "expectedItems = [ {\"message\": \"Ganglia Monitor component should be installed", "1, \"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152,", "servicesList = [] components = [] hosts = { \"items\"", "\"storm-site\": { \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults", "'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using", "{\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} }", "} ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result", "[ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\":", "\"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\",", "{ \"properties\": { \"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\": {\"properties\": {}}", "} expected = { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 8,", "\"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie", "existing layout \"\"\" services = { \"services\" : [ {", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}] } ] services =", "result) def test_validationHostIsNotUsed(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "\"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ] },", "\"0-1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]} ] }", "def setUp(self): import imp import os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath", "'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed'", "\"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\"", "] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result =", "\"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\",", "def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components = [] hosts =", "{ \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"http://host1:7777\" } } }", "\"2.3\", }, \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\", \"service_version\":", "'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1' }, { 'hosts':", "self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"]) result =", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo = [ {", "\"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result", "{\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[", "\"ramPerContainer\": 256 } expected = { \"yarn-env\": { \"properties\": {", "be set to true for distributed mode', 'type': 'configuration' }", "\"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ]", "\"ext4\", \"mountpoint\" : \"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "} result = self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [", "\"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\",", "\"components\": [] }, { \"StackServices\": { \"service_name\": \"FALCON\" }, \"components\":", "{ 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res", ") with open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp,", "and 1 Ganglia Server components should be installed in cluster.\",", "recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received should be as", "is not exist, or not corresponds to existing YARN leaf", "\"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" :", "\"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] } } ] }", "available hostInfo[\"disk_info\"].append( { \"available\" : \"2\", \"type\" : \"tmpfs\", \"mountpoint\"", "[\"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "{ 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations,", "= { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:8888\" } },", "'configuration' }, { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message':", "YARN leaf queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] =", "\"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] },", "self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not", "{ \"mapred-site\": { \"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\":", "warn) # Set by user /var mountpoint, which is non-root", "test_validationYARNServicecheckQueueName(self): servicesInfo = [ { \"name\": \"YARN\", \"components\": [] }", "You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0", "\"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\",", "= { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self):", "} expected = { \"mapred-site\": { \"properties\": { 'mapreduce.job.queuename': 'default',", "self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap,", "\"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo)", "test_recommendYARNConfigurations(self): configurations = {} services = {\"configurations\": configurations, \"services\": []}", "}, \"ranger-hdfs-plugin-properties\": { \"properties\": {} } } expected = {", "{ \"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\":", "}, \"components\": [] }, { \"StackServices\": { \"service_name\": \"HIVE\" },", "installed components should match the existing layout \"\"\" services =", "\"ZOOKEEPER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\":", "recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {}", "components, \"cpu\": 0, \"disk\": 0, \"ram\": 0, \"reservedRam\": 1, \"hbaseRam\":", "expected) # Verify dfs.namenode.rpc-address is recommended to be deleted when", "'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN', 'message': 'Value is less than", "\"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\",", "self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\",", "[ { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" :", "{ \"service_name\": \"OOZIE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": {", "{ \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\",", "'storm-site', 'level': 'WARN', 'message': 'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter '", "'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org',", "{\"newserviceconf\": \"abc2.3\"} } parentValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\":", ": { \"cpu_count\" : 1, \"host_name\" : \"host2\", \"os_arch\" :", "\"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" } }, \"hive-env\": { \"properties\": {", "] } } ] } expected = { \"hBaseInstalled\": True,", "} configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services,", "} } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations, expected) def", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"]", "'configuration' }, { 'message': 'Value is less than the recommended", "hosts = { \"items\": [ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\": {", "15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]", "'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties':", "installed slaves are not added to any free hosts (not", "[hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) # host2 self.assertEquals(namenode,", "} expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"http://host1:7777\"", "'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } }", "# [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts)", ": \"3\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/boot/grub\" } )", "TestCase from mock.mock import patch, MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self):", "}, { 'name': 'host-group-2', 'components': [{ 'name': 'DATANODE' }] }]", "less than the recommended default of 512\", \"level\": \"WARN\"}, {'message':", "'WARN'}, warn) # non-local FS, HDFS properties = {\"property1\": \"hdfs://h1\"}", "[\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"At least 3 Ganglia", "{}}, 'usersync-properties': { 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS':", "1, \"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152", "\"type\" : \"tmpfs\", \"mountpoint\" : \"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "\"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo =", "not used\", \"host\": \"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def", "and https enabled, HDP-2.3 configurations = { \"admin-properties\": { \"properties\":", "= {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "\"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\",", "\"/\" } ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "hostInfo[\"disk_info\"].append( { \"available\" : \"5\", \"type\" : \"vboxsf\", \"mountpoint\" :", "1048576 errorMsg = \"Ambari Metrics disk space requirements not met.", "services = {\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\" : \"2.6.0.2.2\"", "- pick minimum memory servicesList.append(\"YARN\") services = services = {\"services\":", "\"hbase_regionserver_heapsize\": \"8192\", } } } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components,", "= self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = {", "\"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\",", "the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists')", "{ 'blueprint': { 'host_groups': [{ 'name': 'host-group-1', 'components': [] },", "recommendedDefaults, configurations) expectedItems = [ { 'message': 'Value is greater", "} ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn !=", "'type': 'configuration' }, { 'message': 'Value is less than the", "\"rack_info\" : \"/default-rack\", \"total_mem\" : 1048576 } }, ] }", "\"ext4\", \"mountpoint\" : \"/grid/0\" }, { \"available\" : str(15<<30), #", "reqiuredDiskSpace) == None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000),", "= imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = { \"services\": [ { \"StackServices\":", "self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using", "def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", ": \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" :", "but not preferable - no warning hostInfo[\"disk_info\"].append( { \"available\" :", "recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self): import", "be as below: { 'blueprint': { 'host_groups': [{ 'name': 'host-group-1',", "} ]} properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace)", "= { 'hbase-site': { 'properties': { 'hbase.superuser': 'hbase123' } },", "clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP values\") #", "\"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }},", "('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz()", "= [ { 'message': 'Value is greater than the recommended", "{ \"Versions\" : { \"stack_name\" : \"HDP\", \"stack_version\" : \"2.0.6\"", "= {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for", "'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'},", "\"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] },", "\"level\": \"ERROR\"}, {\"message\": \"Value should be set\", \"level\": \"ERROR\"} ]", "self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {'message': 'Queue", "used as hbase.rootdir to store metrics data', 'type': 'configuration' },", "'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true'", "{\"mountpoint\" : \"/vagrant\"} ] } } ] } expected =", "\"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode", "\"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\":", "may not use this file except in compliance with the", "services = { \"Versions\" : { \"stack_name\" : \"HDP\", \"stack_version\"", "} }, 'ranger-env': {'properties': {}}, 'usersync-properties': { 'properties': { 'SYNC_LDAP_URL':", "'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } }", "\"component_category\" : \"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\"", "self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList =", "'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo = [", "1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\":", "} } \"\"\" # Assert that the list is empty", "root partition for hbase.rootdir', 'type': 'configuration' }, { 'config-name': 'hbase.tmp.dir',", "\"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result,", ": 1, \"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" :", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"]", "hosts) expected = [ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN',", "} } hosts = { \"items\" : [host_item for i", "'configuration' } ] self.assertEquals(res, expected) def test_getHostsWithComponent(self): services = {\"services\":", "[\"host1\",\"host2\",\"host3\"] } } ] } ], \"configurations\": {} } result", "blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for binding in", "'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host = {", "TestHDP206StackAdvisor(TestCase): def setUp(self): import imp import os testDirectory = os.path.dirname(os.path.abspath(__file__))", "{ \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": { \"properties\":", "for not existing DB_FLAVOR and http enabled, HDP-2.3\") # Recommend", "{ \"hadoop-env\": { \"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" }", "} }, \"hive-env\": { \"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\"", "'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'It is not recommended", "\"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\",", "\"abc2.3\"} } parentValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"},", "test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ { \"name\": \"HDFS\", \"components\": [ {\"name\":", ": \"ext4\", \"mountpoint\" : \"/\" } ]} properties = {\"property1\":", "'300'} res_expected = [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '',", "'level': 'ERROR', 'message': 'hbase.cluster.distributed property should be set to true", "[] result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations", "expected) # dfs.dir & hbase.rootdir crosscheck + root partition +", "[ ], \"configurations\": configurations } expected = { \"storm-site\": {", "\"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"2\", \"category\":", "\"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\",", "def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already installed slaves are not", "= self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {'message': 'Queue is not", "servicesList = [\"HBASE\"] components = [] hosts = { \"items\"", "\"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\": 3072,", "= self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts)", "{} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" :", "\\ \"Recommended disk space for partition / is 1G\" #", "} }, ]} services = { \"services\": [ { \"StackServices\":", "'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user':", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"ZOOKEEPER\" },", ": serviceInfo[\"name\"]}} nextService[\"components\"] = [] for component in serviceInfo[\"components\"]: nextComponent", "'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data',", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] }", "{ \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\":", "/ is 10G', 'type': 'configuration' } ] self.assertEquals(res, expected) #", "changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations'] =", "\"RANGER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\":", "is 1G\" # local FS, enough space hostInfo = {\"disk_info\":", "\"hBaseInstalled\": False, \"components\": components, \"cpu\": 0, \"disk\": 0, \"ram\": 0,", ": \"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\",", "{ \"properties\": {} } } expected = { 'admin-properties': {", "try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent)", "\"value2\"} expected = {'level': 'ERROR', 'message': 'Value should be set", "\"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [],", "slaves are not added to any free hosts (not having", "'rb') as fp: stack_advisor = imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py',", "See the NOTICE file distributed with this work for additional", "hostGroup[\"components\"]: componentName = component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName]", "\"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\"", "}) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666", "'usersync-properties': { 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount',", "'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user':", "} }, \"ranger-env\": {\"properties\": {}} } recommendedConfigurations = {} services['services'][0]['StackServices']['service_version']", "res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) def", "expected = {'level': 'ERROR', 'message': 'Value should be recommended for", "in result[\"items\"]: next = {\"message\": item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"]", "} recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected,", "'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as fp: stack_advisor = imp.load_module( 'stack_advisor',", "} } } hosts = { \"items\": [ { \"href\":", "components = [] hosts = { \"items\" : [ {", "'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*',", "recommended minimum of 0.8 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name':", "self.assertFalse(res) #Value is less then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'}", "}], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\": {", "\"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [] }, { \"StackServices\":", ": \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } )", "# virtualbox fs with more space available hostInfo[\"disk_info\"].append( { \"available\"", "= self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] }", "KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def assertHostLayout(self,", "{\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services,", "'WARN', 'message': 'It is not recommended to use root partition", "} ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with more space", "{ 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' },", "\"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\": \"7777\",", "} hosts = { \"items\" : [ { \"href\" :", "def read(self): return \"\"\" #test line UID_MIN 200 UID_MIN 500", "= self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts =", "agreed to in writing, software distributed under the License is", "\"500\", 'service_check.queue.name': 'default' } }, \"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\":", ": \"/grid/0\" } ) recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn =", ": \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" :", "} }, \"ranger-hdfs-plugin-properties\": { \"properties\": {} } } expected =", "None) expected = [] self.assertEquals(res, expected) properties['metrics.reporter.register'] = '' res", "= \"ndfqueue\" expectedItems = [] result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems,", "'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' }, { 'message': 'Value is less", "'level': 'WARN', 'message': 'Ambari Metrics disk space requirements not met.", "fs with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"5\",", "} }, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1, \"host_name\":", "None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def", "{ \"cpu_count\" : 8, \"total_mem\" : 6291456, \"disk_info\" : [", "{} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR", "values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" : \"false\",", "}], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData = { \"totalAvailableRam\":", "expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*',", "= [ {\"message\": \"Ganglia Monitor component should be installed on", "\"available\": str(15<<30), # 15 GB \"type\": \"ext4\", \"mountpoint\": \"/\" }", "in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo", "{ \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\")", "result) def test_validationYARNServicecheckQueueName(self): servicesInfo = [ { \"name\": \"YARN\", \"components\":", "\"Ganglia Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]},", "DB_FLAVOR and http enabled, HDP-2.3\") # Recommend for DB_FLAVOR POSTGRES", "= { \"Hosts\" : { \"cpu_count\" : 6, \"total_mem\" :", "report the metrics to Ambari Metrics service.', 'type': 'configuration' }", "information regarding copyright ownership. The ASF licenses this file to", "'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN',", ") self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with more space available", "\"7\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/1\" } ) self.assertEquals([\"/grid/1\",", "hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations = { \"mapred-site\": {", "{ \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\",", ": \"/vagrant\"} ] } } hosts = { \"items\" :", "\"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152, \"disk_info\":", ": \"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self):", "hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [", "8, \"total_mem\" : 6291456, \"disk_info\" : [ {\"mountpoint\" : \"/\"},", "less than the recommended default of 256', 'type': 'configuration'}] res", "\"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties,", "= \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"] =", "components should be installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems,", "services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations =", "} ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space available", "Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\":", "None) # unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts)", "properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"} # only", ": \"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" :", "\"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\",", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "\"hbase.superuser\": \"hbase\" } }, \"hbase-env\": { \"properties\": { \"hbase_user\": \"hbase123\"", "hostsInfos = [binding[\"hosts\"] for binding in bindings if binding[\"name\"] ==", "\"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] }, \"dependencies\":[", "[{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\":", "'1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) #Value", "\"true\", } } } } expected = { \"admin-properties\": {", "{ \"properties\": { 'clientPort': \"2183\" } } } services =", "hosts) self.assertFalse(res) #Value is less then expected recommendedDefaults = {'dfs.datanode.du.reserved':", "\"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def", "\"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[", "{\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "\"mountpoint\" : \"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint", "} recommendedDefaults = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\",", "space hostInfo = {\"disk_info\": [ { \"available\" : \"1\", \"type\"", "= [binding[\"hosts\"] for binding in bindings if binding[\"name\"] == hostGroupName][0]", "[] self.assertEquals(res, expected) # dfs.dir & hbase.rootdir crosscheck + root", "servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\",", "\"available\" : '1', \"type\" : \"ext4\", \"mountpoint\" : \"/\" }", "False}] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"])", "result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Exactly 2", "nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"]", "https enabled, HDP-2.2 configurations = { \"admin-properties\": { \"properties\": {", "minimum of 0.8 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value',", "'/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group':", ": \"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more", "= {\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn", "the list is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that", "'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl =", "\"1+\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\":", "\"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\",", "hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" : 4, \"total_mem\"", "'Value should be set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value", "\"\"\" Test that already installed slaves are not added to", "configurations = {} # 1) ok: namenode_heapsize > recommended recommendedDefaults", "\"/vagrant\"} ] } }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"]", "{\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\"", "\"ORACLE\", } }, \"ranger-site\": { \"properties\": { \"http.enabled\": \"false\", \"https.service.port\":", "'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] =", "self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations = {} # 1) ok: namenode_heapsize", "\"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\",", "l2)) def assertValidationResult(self, expectedItems, result): actualItems = [] for item", "= [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\":", "= { \"yarn-env\": { \"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name': 'default'", "hbase.rootdir to store metrics data', 'type': 'configuration' }, { 'config-name':", "self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"],", "\"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\",", "\"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo", "[{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ {", "# only / mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1',", "is not recommended to use root partition for property1', 'level':", "== None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg = \"Ambari", "'host-group-2' }] } } \"\"\" # Assert that the list", "configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '1024'} res", "} } ] } ], \"configurations\": {} } result =", "services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services,", "[binding[\"hosts\"] for binding in bindings if binding[\"name\"] == hostGroupName][0] hosts", "] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}}", "property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties =", "\"hbase-site\": { \"properties\": { \"hbase.superuser\": \"hbase\" } }, \"hbase-env\": {", "\"cpu_count\" : 4, \"total_mem\" : 500000, \"host_name\" : \"host2\", \"disk_info\"", "res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = []", "operation. For already installed services, recommendation for installed components should", "is less than the recommended default of 256', 'type': 'configuration'}]", "'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1' }, { 'hosts': [{ 'fqdn':", "\"stack_version\" : \"2.0.6\" } } services[\"services\"] = [] for serviceInfo", "services, hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData = {} #", "'c6402.ambari.apache.org' }], 'name': 'host-group-1' }, { 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org'", "{'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN', 'message': 'Should be set", "pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations", "[ {\"message\": \"Host is not used\", \"host\": \"host2\", \"level\": \"ERROR\"}", "{\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } ]", "self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList =", "store HDFS data', 'type': 'configuration' } ] self.assertEquals(res, expected) #", "{\"property1\": \"value2\"} expected = {'level': 'ERROR', 'message': 'Value should be", "[\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"2\", \"category\": \"MASTER\",", "\"display_name\": \"Ganglia Server\", \"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\",", "AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems, result): actualItems = []", "'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) # Verify", ": 1, \"host_name\" : \"host1\", \"os_arch\" : \"x86_64\", \"os_type\" :", "Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]}", ": 50331648, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" :", "\"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\":", "expectedItems = [ {'message': 'Queue is not exist, or not", "test_recommendRangerConfigurations(self): clusterData = {} # Recommend for not existing DB_FLAVOR", "\"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", } } } clusterData", "\"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] }, {", "\"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\",", "= { \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", } },", "{ \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\":", "with open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath,", "configurations, services, hosts) self.assertFalse(res) #Value is less then expected recommendedDefaults", "imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff =", "distributed mode', 'type': 'configuration' } ] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self):", "\"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\",", "} } ], \"configurations\": configurations } # positive res =", "self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) # unknown component unknown_component", "'configuration' }, { 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message':", "= self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations", "in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts)", "compliance with the License. You may obtain a copy of", "\"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Exactly", "\"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\",", "expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"]", "\"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self):", "{ \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\",", ": \"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults =", "configurations, services, None) expected = [] self.assertEquals(res, expected) properties['metrics.reporter.register'] =", "\"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } })", ": \"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" :", "hosts[\"items\"][0][\"Hosts\"] } # Test - Cluster data with 1 host", "hosts[\"items\"][1]) # not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts)", "\"total_mem\" : 2097152, \"disk_info\": [ { \"available\": str(15<<30), # 15", "\"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\", \"category\":", "[info[\"fqdn\"] for info in hostsInfos] for component in hostGroup[\"components\"]: componentName", "for info in hostsInfos] for component in hostGroup[\"components\"]: componentName =", "{'properties': {}}, 'usersync-properties': { 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org',", "= { \"items\": [] } for hostName in hostsNames: nextHost", "] services = self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts = self.prepareHosts([localhost,", "warn) # non-local FS, HDFS properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties,", "[] }, { 'name': 'host-group-2', 'components': [{ 'name': 'DATANODE' }]", "} } } } expected = { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\":", "\"amMemory\": 123.54 } expected = { \"mapred-site\": { \"properties\": {", "} result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected = {", "True}] } ] services = self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts", "\"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }],", "\"ranger-site\": { \"properties\": { \"http.enabled\": \"false\", \"https.service.port\": \"8888\", } }", "}, { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider", "== hbase.tmp.dir warnings properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' :", "if binding[\"name\"] == hostGroupName][0] hosts = [info[\"fqdn\"] for info in", "(not having any component installed) as part of recommendation received", "} } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8)", "}] }], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData = {", "= [ {'message': 'Queue is not exist, or not corresponds", "{ \"totalAvailableRam\": 2048 } ambariHostName = socket.getfqdn() expected = {'oozie-env':", "'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group':", "'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*',", "\"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}] } ]", "\"level\": \"WARN\"}, {'message': 'Value should be set for yarn.nodemanager.linux-container-executor.group', 'level':", "hostInfo) == None) # More preferable /grid/0 mountpoint - warning", "= [ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] }", "sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems, result): actualItems", "'default' } }, \"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\":", "'*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user':", "\"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"},", "prepareHosts(self, hostsNames): hosts = { \"items\": [] } for hostName", "{ \"StackServiceComponents\" : { \"cardinality\" : \"1+\", \"component_category\" : \"SLAVE\",", ": [ { \"StackServiceComponents\" : { \"cardinality\" : \"1+\", \"component_category\"", "work for additional information regarding copyright ownership. The ASF licenses", "\"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"]", "{} # 1) ok: namenode_heapsize > recommended recommendedDefaults = {'namenode_heapsize':", "expected = [ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message':", "= {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result =", "} } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self):", "\"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\"", "self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations =", "services['configurations'] = configurations expected[\"hdfs-site\"] = { 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data',", "== sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems, result):", "self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations =", "org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the metrics to Ambari Metrics service.',", "'level': 'WARN'}, warn) # Set by user /var mountpoint, which", "\"ranger.service.http.enabled\": \"true\", } } } } expected = { \"admin-properties\":", "\"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", ": \"ext4\", \"mountpoint\" : \"/grid/0\" } ) recommendedDefaults = {\"property1\":", "enabled, HDP-2.2 configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\":", "self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock):", "= {'level': 'ERROR', 'message': 'Value should be recommended for property1'}", "enough space hostInfo = {\"disk_info\": [ { \"available\" : \"1\",", "[ ], \"configurations\": { \"hbase-site\": { \"properties\": { \"hbase.superuser\": \"hbase\"", "copyright ownership. The ASF licenses this file to you under", "self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations = { \"mapred-site\":", "self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR POSTGRES", "services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for not existing DB_FLAVOR and", "} }, \"falcon-env\": { \"properties\": { \"falcon_user\": \"falcon\" } }", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"4\", \"type\"", "[{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\":", "{ \"cpu_count\" : 4, \"total_mem\" : 500000, \"host_name\" : \"host2\",", "{ 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env':", "= [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\":", "\"is_master\": False, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts", "}] }] }, 'blueprint_cluster_binding': { 'host_groups': [{ 'hosts': [{ 'fqdn':", "hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb')", "} } } items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems", "], \"configurations\": configurations } result = self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\"", "recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for hostGroup in", "expected = { \"mapred-site\": { \"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\":", "{ \"service_name\": \"RANGER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services,", "layout \"\"\" services = { \"services\" : [ { \"StackServices\"", "recommendedDefaults, configurations, services, None) expected = [] self.assertEquals(res, expected) properties['metrics.reporter.register']", "\"7777\", \"ranger.service.http.enabled\": \"true\", } } } } expected = {", "'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host =", "= [] result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self):", "{ \"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" } }, \"hive-env\":", "1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{ \"size\":", "of 2047 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type':", "# dfs.dir & hbase.rootdir crosscheck + root partition + hbase.rootdir", ") self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space available hostInfo[\"disk_info\"].append(", "distributed mode properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase',", "\"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\",", "configurations } result = self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected)", "is less then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties =", "self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # local FS, no", "\"properties\": { \"hbase_user\": \"hbase123\" } } } } expected =", "hosts, components, None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self): # no AMS", "partitions host['Hosts']['disk_info'] = [ { \"available\": str(15<<30), # 15 GB", "\"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] } ],", "{} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result,", "\"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie Server\", \"is_client\": \"false\", \"is_master\": \"true\",", "[ { \"available\": str(15<<30), # 15 GB \"type\": \"ext4\", \"mountpoint\":", "= component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName] = []", "DB_FLAVOR POSTGRES and https enabled, HDP-2.3\") # Recommend for DB_FLAVOR", "root partition for property1', 'level': 'WARN'}, warn) # Set by", "{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\",", "\"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } }", "\"POSTGRES\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\":", "{\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value2\"} expected = {'message': 'It", "self.maxDiff = None # substitute method in the instance self.get_system_min_uid_real", "'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'},", "= { \"zoo.cfg\": { \"properties\": { 'clientPort': \"2183\" } }", "= MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo = [ {", "}, { \"available\" : str(15<<30), # 15 GB \"type\" :", "'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*',", "}, 'property_attributes': { 'dfs.namenode.rpc-address': { 'delete': 'true' } } }", "\"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } }", "} self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ { \"name\":", "# no AMS configurations = {} services = { \"services\":", "\"level\": \"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo", "{ \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\":", "'config-name': 'some_float_value', 'type': 'configuration' } ] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self):", "services def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings =", "\"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services,", "not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys(): expectedHosts =", "self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo = [ { \"name\": \"YARN\",", "\"components\": components, \"cpu\": 0, \"disk\": 0, \"ram\": 0, \"reservedRam\": 1,", "{'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024',", "\"Ganglia Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\",", "services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts", "None, services, None) self.assertEquals(configurations, expected) # with AMS configurations =", "= self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode", "} } ] } ], \"configurations\": configurations } # only", "} recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = {", "# only 1 partition, enough disk space, no warnings res", "hosts, components, None) expected = { \"hBaseInstalled\": False, \"components\": components,", "'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*',", "warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message':", "= {\"disk_info\": [ { \"available\" : \"1048578\", \"type\" : \"ext4\",", "'Value is greater than the recommended maximum of 2047 ',", "\"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations,", "\"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, {", "test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData = { \"mapMemory\": 567, \"reduceMemory\":", "\"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"} recommendedDefaults =", "clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for not existing DB_FLAVOR", "Ganglia Monitor components should be installed in cluster.\", \"level\": \"ERROR\"}", "} self.assertEquals(result, expected) def prepareHosts(self, hostsNames): hosts = { \"items\":", "None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData =", "services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services,", "\"hbase_user\": \"hbase123\" } } } } expected = { 'hbase-site':", "'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir':", "\"ram\": 0, \"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\": 512,", ": [ ], \"configurations\": { \"hbase-site\": { \"properties\": { \"hbase.superuser\":", "test_validateStormSiteConfigurations(self): configurations = { \"storm-site\": { \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\"", "reqiuredDiskSpace = 1048576 errorMsg = \"Ambari Metrics disk space requirements", "{ \"StackServices\" : { \"service_name\" : \"HDFS\" }, \"components\" :", "clusterData = {} # Recommend for not existing DB_FLAVOR and", "'' hosts = '' #Default configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'}", "\"Versions\" : { \"stack_name\" : \"HDP\", \"stack_version\" : \"2.0.6\" }", "def __exit__(self, exc_type, exc_val, exc_tb): pass def __enter__(self): return self", "\"available\" : \"1048578\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" }", "for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value should be integer\", \"level\":", "\"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\":", "{} services = '' hosts = '' #Default configuration recommendedDefaults", "} services[\"services\"] = [] for serviceInfo in servicesInfo: nextService =", "'properties': { 'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env': {'properties': {}}, 'usersync-properties':", "'*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups':", "= [] self.assertEquals(res, expected) # 1 partition, no enough disk", "\"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts)", "result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {\"message\": \"Value is", "\"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\",", ": 6, \"total_mem\" : 50331648, \"disk_info\" : [ {\"mountpoint\" :", "hostName}} hosts[\"items\"].append(nextHost) return hosts def prepareServices(self, servicesInfo): services = {", "'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the metrics", "= self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self): #", "{'message': 'Queue is not exist, or not corresponds to existing", "= configurations expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties':", "expectedItems = [ {\"message\": \"At least 3 Ganglia Server components", ": \"HDP\", \"stack_version\" : \"2.0.6\" } } services[\"services\"] = []", "{'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive',", "Test Recommend LDAP values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" : \"true\",", "\"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] },", "\"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', }", "\"c6401.ambari.apache.org\" ] } } ] } ] } hosts =", "\"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations,", "self.assertEquals(namenode, hosts[\"items\"][1]) # not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services,", "\"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" : \"/\"},", "'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations,", "\"totalAvailableRam\": 2048 } ambariHostName = socket.getfqdn() expected = {'oozie-env': {'properties':", "host ] } services = { \"services\": [ { \"StackServices\":", "\"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\",", "self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR ORACLE", "\"yarn-env\": { \"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name': 'default' } },", "\"\"\" servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\",", "[\"host2\", \"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts =", "{ \"containers\" : 5, \"ramPerContainer\": 256 } expected = {", "= self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {'message':", "\"service_name\": \"HDFS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"DATANODE\",", "expected = [] self.assertEquals(res, expected) # dfs.dir & hbase.rootdir crosscheck", "component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] } } try:", "{'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertTrue(res)", "\"/hadoop/data\" } }, \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" }", "{\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\"", "[ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\",", "services, hosts) expected = [] self.assertEquals(res, expected) # dfs.dir &", "} clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations,", "'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'In distributed mode hbase.rootdir should", "in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName]", "{ \"stack_version\" : \"2.3\", }, \"services\": [ { \"StackServices\": {", "{ \"available\" : \"7\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/1\"", "\"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{ \"size\": '8', \"mountpoint\":", "\"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\",", ": \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {} expected = { 'admin-properties':", "\"Value should be set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def", "\"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, { \"StackServices\": { \"service_name\":", "'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*',", "\"4096\", \"hbase_regionserver_heapsize\": \"8192\", } } } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts,", "'Value should be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected)", "\"3\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } ) recommendedDefaults", "services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test", "\"Test Recommend LDAP values\") # Test Ranger Audit properties del", "\"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with more", "{ \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } } ]", "\"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] }, \"dependencies\":[", "recommendedDefaults, 'property1', hostInfo) == None) # More preferable /grid/0 mountpoint", "binding[\"name\"] == hostGroupName][0] hosts = [info[\"fqdn\"] for info in hostsInfos]", "\"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received should be", "\"hbase-env\": { \"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", } }", "{'level': 'ERROR', 'message': 'Value should be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties,", "} ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\":", "}, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ],", "[], \"display_name\": \"Hive Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\",", "\"host2\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo = [ {", "\"display_name\": \"WebHCat Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\":", "\"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\":", "True, \"components\": components, \"cpu\": 8, \"disk\": 8, \"ram\": 6, \"reservedRam\":", "}, { 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2' }]", "= {'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' : '300'} res_expected", "'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2' }] } } \"\"\" #", "\"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } ) recommendedDefaults =", "\"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }, \"components\": [", "'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes':", "existing YARN leaf queue', 'level': 'ERROR'} ] self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"]", "setUp(self): import imp import os testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath =", "[] for serviceInfo in servicesInfo: nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}}", "'*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties':", ": \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {} expected", "mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None)", "{ \"timeline.metrics.service.operation.mode\": \"embedded\" } } } recommendedDefaults = { 'hbase.rootdir':", "8, \"disk\": 8, \"ram\": 6, \"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\":", "hostInfo = {\"disk_info\": [ { \"available\" : \"2\", \"type\" :", "} } expected = { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", }", "\"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" }", "self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR ORACLE and https enabled, HDP-2.2\")", "\"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\",", "hosts) \"\"\" Recommendation received should be as below: { 'blueprint':", ") self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more space available hostInfo[\"disk_info\"].append(", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"7\", \"type\" : \"ext4\",", "'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb')", "{ \"properties\": { \"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\": { \"properties\":", "is not used\", \"level\": \"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result)", "} } } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'],", "this work for additional information regarding copyright ownership. The ASF", "} ], \"configurations\": configurations } # only 1 partition, enough", "{ \"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name': 'default' } }, \"yarn-site\":", "= [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations = { \"zoo.cfg\":", "] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations = { \"storm-site\": {", "= [ {\"message\": \"At least 3 Ganglia Server components should", "services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit properties\") def test_recommendHDFSConfigurations(self):", "'*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts':", "\"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\"", "'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env': {", "[\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\":", "expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already installed slaves are", "!= None) self.assertEquals({'message': 'It is not recommended to use root", "\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space available hostInfo[\"disk_info\"].append(", "\"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\":", "= configurations expected[\"hdfs-site\"] = { 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved':", "None) # unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts)", "\"oozie-env\": { \"properties\": { \"oozie_user\": \"oozie\" } }, \"falcon-env\": {", "self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {\"message\": \"Value", "\"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\":", "= {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties,", "\"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } } recommendedDefaults = { \"mapred-site\":", "\"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Ganglia", "\"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False,", "= 512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] =", "'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' :", "enough disk space host['Hosts']['disk_info'] = [ { \"available\" : '1',", "\"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name': 'default' } }, \"yarn-site\": {", "}, \"ranger-site\": { \"properties\": { \"http.enabled\": \"false\", \"https.service.port\": \"8888\", }", "\"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 } expected = {", "[{ 'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2' }] } } \"\"\"", "\"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\": {", ": \"ext4\", \"mountpoint\" : \"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "\"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum':", "self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components = []", "{ \"properties\": { \"policymgr_external_url\": \"http://host1:7777\" } } } recommendedConfigurations =", "License, Version 2.0 (the \"License\"); you may not use this", "[] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems = [ { 'message': 'Value", "[] self.assertEquals(res, expected) properties['metrics.reporter.register'] = '' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults,", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] =", "expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components = [] hosts", "{ \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, ],", "\"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'},", "\"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False,", "}, }] }], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData =", ": \"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more", "def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096)", "\"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]} ]", "} } } services = { \"services\": [ { \"StackServices\":", "None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\":", "__exit__(self, exc_type, exc_val, exc_tb): pass def __enter__(self): return self exists_mock.return_value", "for componentName in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName]", ": \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" :", "componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def", "}, { \"StackServices\": { \"service_name\": \"FALCON\" }, \"components\": [] },", "[], \"display_name\": \"Oozie Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\",", "MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo = [ { \"name\":", "host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\",", "components, None) self.assertEquals(result, expected) # Test - Cluster data with", "empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE is placed", "] } ], \"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\":", "self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1, l2): if not len(l1) ==", "self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components = []", "\"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\":", "'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*',", "\"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo =", "self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Host is not used\",", "'Value is less than the recommended minimum of 0.8 ',", "1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\")", "services, None) expected = [] self.assertEquals(res, expected) properties['metrics.reporter.register'] = ''", "\"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, ], \"configurations\": {", "{\"service_name\" : \"HDFS\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\",", "{\"mountpoint\" : \"/vagrant\"} ] } } hosts = { \"items\"", "\"tmpfs\", \"mountpoint\" : \"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot", "= actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1, l2): if not", "result) def test_validationCardinalityAtLeast(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY", "def assertValidationResult(self, expectedItems, result): actualItems = [] for item in", "'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } } recommendedConfigurations =", "'message': 'Consider not using / partition for storing metrics data.", "\"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\",", "'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users',", "component in hostGroup[\"components\"]: componentName = component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError,", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [", "{ 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2' }] }", "'type': 'configuration' }, { 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR',", "= {\"property1\": \"file:///var/dir\"} # only / mountpoint - no warning", "\"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" }", "{\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]},", "] }, \"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\",", "{ \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ] } ],", "\"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666", "space host['Hosts']['disk_info'] = [ { \"available\" : '1', \"type\" :", "} ] } ] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations", "None # substitute method in the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid", "expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"]", "{ \"storm-site\": { \"properties\": { } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None,", "\"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576,", "\"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\",", "\"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\":", "clusterData = { \"totalAvailableRam\": 2048 } ambariHostName = socket.getfqdn() expected", "} ], \"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\",", "raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self, expectedItems, result): actualItems =", "partition is already used as hbase.rootdir to store metrics data',", "used\", \"host\": \"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self):", "installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self):", "'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res =", "\"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Between", "for i in range(1, 300)] } services = { \"services\"", "expected) def test_validateHDFSConfigurations(self): configurations = {} services = '' hosts", "import imp, os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py')", "\"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\",", "\"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services,", "\"hostnames\": [\"host2\", \"host1\"]} ] } ] services = self.prepareServices(servicesInfo) hosts", "\"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def", "'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' }, {", "\"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test - Cluster data with 1", "self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations = { \"storm-site\": { \"properties\":", "3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 }", "\"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\": True,", "expected = { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080' }", "{ \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" } }, \"oozie-env\": { \"properties\":", "}, \"hbase-env\": { \"properties\": { \"hbase_user\": \"hbase123\" } } }", "services, hosts) expected = [ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site',", "data with 2 hosts - pick minimum memory servicesList.append(\"YARN\") services", "\"host_name\" : \"host1\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\"", "\"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\"", "= { \"storm-site\": { \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } },", "170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result, expected)", "], \"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", }", "in distributed mode properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' :", "services, hosts) self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode =", "{\"property1\": \"value1\"} recommendedDefaults = {} expected = {'level': 'ERROR', 'message':", "warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) # More preferable", "= {} recommendedDefaults = {\"property1\": \"value2\"} expected = {'level': 'ERROR',", "should be set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value should", "def test_getServicesSiteProperties(self): import imp, os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath =", "hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services =", "self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self): # no", "test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg = \"Ambari Metrics disk space", "\"services\" : [ { \"StackServices\" : { \"service_name\" : \"HDFS\"", "not met. \\n\" \\ \"Recommended disk space for partition /", "[\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations = { \"zoo.cfg\": {", "\"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\",", "'message': 'In distributed mode hbase.rootdir should point to HDFS.', 'type':", "using / partition for storing metrics data. ' '/ is", "res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) #", "expected, \"Test Recommend LDAP values\") # Test Ranger Audit properties", "\"components\": components, \"cpu\": 6, \"disk\": 6, \"ram\": 48, \"reservedRam\": 6,", "'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' : '300'} res_expected = [] res", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"2\", \"type\" :", "of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law", "self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services =", "is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE is", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]} ] } ] services =", "\"services\": [ ], \"configurations\": configurations } expected = { \"storm-site\":", "\"items\" : [ { \"Hosts\" : { \"cpu_count\" : 8,", "result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self):", "storing metrics data. ' '/ is already used by datanode", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo = [", "services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\"", "} try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = []", "# non-local FS, HDFS properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1',", "'300', 'namenode_opt_maxnewsize' : '300'} res_expected = [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties,", "None) self.assertEquals(recommendedConfigurations, expected, \"Test for not existing DB_FLAVOR and http", "'c6401.ambari.apache.org' }], 'name': 'host-group-2' }] } } \"\"\" # Assert", "'rb') as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb',", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "\"Host is not used\", \"level\": \"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems,", "services, None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData", "= [] components = [] hosts = { \"items\" :", "items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems = [ {", "or not sorted(l1) == sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def", "}, \"falcon-env\": { \"properties\": { \"falcon_user\": \"falcon\" } } }", "{ \"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" } }, \"oozie-env\":", "def test_validationHostIsNotUsed(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", "'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations = {}", "\"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] } }, {", "self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes, hosts[\"items\"]) datanode =", "test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties,", "\"proxyuser_group\": \"users\" } }, \"hive-env\": { \"properties\": { \"webhcat_user\": \"webhcat\",", "may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless", "}, \"dependencies\":[ ] } ], }], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"]", "} } services[\"services\"] = [] for serviceInfo in servicesInfo: nextService", "} hosts = { \"items\" : [host_item for i in", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo = [", "self.assertEquals(recommendedConfigurations, expected, \"Test for not existing DB_FLAVOR and http enabled,", "'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': {", "\"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }, \"components\": [ { \"StackServiceComponents\": {", "host = { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\"", "open_mock): class MagicFile(object): def read(self): return \"\"\" #test line UID_MIN", "component in serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\": { \"component_name\": component[\"name\"],", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] }", "2048 } ambariHostName = socket.getfqdn() expected = {'oozie-env': {'properties': {'oozie_user':", "\"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\":", "[ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\",", "services = { \"Versions\" : { \"stack_version\" : \"2.3\", },", "\"mountpoint\" : \"/\" } ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations,", "'blueprint': { 'host_groups': [{ 'name': 'host-group-1', 'components': [] }, {", "} } } expected = { 'hbase-site': { 'properties': {", "for serviceInfo in servicesInfo: nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"]", "{\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\":", "\"properties\": { \"falcon_user\": \"falcon\" } } } hosts = {", "\"authentication.ldap.bindAnonymously\" : \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\"", "under the License is distributed on an \"AS IS\" BASIS,", "= hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for binding in bindings if", "'mapreduce.task.io.sort.mb', 'type': 'configuration' }, { 'message': 'Value is less than", "'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user':", "{ \"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ]", ": { \"cpu_count\" : 1, \"host_name\" : \"host1\", \"os_arch\" :", "\"NAMENODE\", services, hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not installed", "\"6\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } ) self.assertEquals([\"/grid/0\",", "[] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\",", "{ \"available\" : \"2\", \"type\" : \"ext4\", \"mountpoint\" : \"/\"", "\"Hosts\" : { \"cpu_count\" : 8, \"total_mem\" : 6291456, \"disk_info\"", "'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\":", "The ASF licenses this file to you under the Apache", "'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } },", "'type': 'configuration' } ] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations =", "file distributed with this work for additional information regarding copyright", "\"items\" : [host_item for i in range(1, 300)] } services", "the recommended default of 1024', 'type': 'configuration', 'config-name': 'namenode_heapsize', 'level':", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"7\", \"type\"", "= {\"message\": item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"] = item[\"host\"] except", "result = self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self):", "\"ext4\", \"mountpoint\" : \"/\" } ] recommendedDefaults = { 'hbase.rootdir':", "'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter',", "recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties =", "stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName =", "the recommended maximum of 2047 ', 'level': 'WARN', 'config-type': 'mapred-site',", "\"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\",", "cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo =", "\"name\": \"YARN\", \"components\": [] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"]", "} expected = { \"yarn-env\": { \"properties\": { \"min_user_id\": \"500\",", "[host_item for i in range(1, 300)] } services = {", "this file except in compliance with the License. You may", "\"StackServices\" : { \"service_name\" : \"HDFS\" }, \"components\" : [", "[ {\"message\": \"Exactly 2 Ganglia Monitor components should be installed", "os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName", "hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes),", "result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self):", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\",", "\"cpu_count\" : 8, \"total_mem\" : 6291456, \"disk_info\" : [ {\"mountpoint\"", "}, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self):", "self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData = {} # Recommend for", "test_validateHDFSConfigurations(self): configurations = {} services = '' hosts = ''", "] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo = [ { \"name\":", "'property1', hostInfo) == None) # More preferable /grid/0 mountpoint -", "] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"])", "[{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False}] } ]", "to be deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster']", "\"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}] }", "} ] services = self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts =", "[ \"c6401.ambari.apache.org\" ] } } ] } ] } hosts", "\"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat", "] }, { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [", "\"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host2\", \"rack_info\"", "{ \"service_name\": \"HIVE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": {", "services, hosts) self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address is recommended to", "= {'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "}, ] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes),", "\"hostnames\": [\"host1\"] } } ] } ], \"configurations\": configurations }", "{\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected,", "\"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\":", ": '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations,", "for installed components should match the existing layout \"\"\" services", "recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] = '255' res_expected = [{'config-type':", "l1, l2): if not len(l1) == len(l2) or not sorted(l1)", "self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit properties\")", "for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self): import imp,", "1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\":", "file except in compliance with the License. You may obtain", "[ {\"message\": \"Host is not used\", \"host\": \"host1\", \"level\": \"ERROR\"}", "'ERROR'}, {\"message\": \"Value should be integer\", \"level\": \"ERROR\"}, {\"message\": \"Value", "self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = [ {'config-name': 'metrics.reporter.register',", "self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space available", "\"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) # unknown component unknown_component =", ") self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space", "crosscheck + root partition + hbase.rootdir == hbase.tmp.dir warnings properties", "\"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations,", "ORACLE and https enabled, HDP-2.2 configurations = { \"admin-properties\": {", "{ 'clientPort': \"2183\" } } } services = { \"services\":", "{ \"items\" : [ { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" :", "None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit properties\") def test_recommendHDFSConfigurations(self): configurations", "\"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"],", "\"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"At", "{ \"properties\": { \"hbase.superuser\": \"hbase\" } }, \"hbase-env\": { \"properties\":", "OR CONDITIONS OF ANY KIND, either express or implied. See", "= {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) #", "} } } } expected = { 'hbase-site': { 'properties':", "the cluster before \"\"\" servicesInfo = [ { \"name\": \"GANGLIA\",", "\"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } } recommendedDefaults", "= {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Ranger", "services = { \"services\": [ { \"StackServices\": { \"service_name\": \"HDFS\"", "}, { 'message': 'Value is less than the recommended minimum", "{\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"} # only / mountpoint", "configurations = {} services = { \"services\": [ { \"StackServices\":", "\"http://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services,", "} \"\"\" # Assert that the list is empty for", "exc_val, exc_tb): pass def __enter__(self): return self exists_mock.return_value = True", "'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration' } ] self.assertEquals(expectedItems,", "import socket from unittest import TestCase from mock.mock import patch,", "hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" :", ": '256', 'namenode_opt_maxnewsize' : '256'} properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize'", "def prepareHosts(self, hostsNames): hosts = { \"items\": [] } for", "'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations,", "= [ {\"message\": \"Between 0 and 1 Ganglia Server components", "the metrics to Ambari Metrics service.', 'type': 'configuration' } ]", "l2): if not len(l1) == len(l2) or not sorted(l1) ==", "\"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data',", "for hostGroup in blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"]", "Recommend for DB_FLAVOR ORACLE and https enabled, HDP-2.2 configurations =", "hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes", "{\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ]", "'*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes':", "= {} services = { \"services\": [ ], \"configurations\": configurations", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"2\", \"type\"", "testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor',", "be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the metrics to", "self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations =", "\"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" : \"true\",", "\"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\",", "\"property1\"), expected) properties = {} recommendedDefaults = {\"property1\": \"value2\"} expected", "Verify dfs.namenode.rpc-address is recommended to be deleted when NN HA", "namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1])", "= { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self):", "\"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\": {", "range(1, 300)] } services = { \"services\" : [ ],", "\"properties\": { \"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\": {\"properties\": {}} }", "prepareServices(self, servicesInfo): services = { \"Versions\" : { \"stack_name\" :", "{ \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\": { \"properties\":", "\"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\",", "hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected)", "self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations = {} services = {\"configurations\":", "= [info[\"fqdn\"] for info in hostsInfos] for component in hostGroup[\"components\"]:", "= self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message': errorMsg,", "'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] =", "2, \"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\":", "512\", \"level\": \"WARN\"}, {'message': 'Value should be set for yarn.nodemanager.linux-container-executor.group',", "\"host2\" ] }, \"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\",", "regarding copyright ownership. The ASF licenses this file to you", "file to you under the Apache License, Version 2.0 (the", "}, \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\":", "values\") # Test Ranger Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"] =", "= [] self.assertEquals(res, expected) # dfs.dir & hbase.rootdir crosscheck +", "{ \"storm-site\": { \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } }", "'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using / partition for", "'1', \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ] res", "{ 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'} } } }", "\"str\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems =", "actualComponentHostsMap[componentName] self.checkEqual(expectedHosts, actualHosts) def checkEqual(self, l1, l2): if not len(l1)", "'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete':", "\"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\"", "self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address is", "\"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] }, \"dependencies\":[ ] }, ],", "}, \"components\" : [ { \"StackServiceComponents\" : { \"cardinality\" :", "] } } ] } ] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\",", "hosts = [info[\"fqdn\"] for info in hostsInfos] for component in", "[ { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } },", "is less than the recommended minimum of 0.8 ', 'level':", "namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] = '255'", "{ 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties =", "[] for host in hosts: if host not in actualComponentHostsMap[componentName]:", "Server components should be installed in cluster.\", \"level\": \"ERROR\"} ]", "services, None) self.assertEquals(configurations, expected) # with AMS configurations = {}", "properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] = '255' res_expected = [{'config-type': 'hadoop-env',", "to Ambari Metrics service.', 'type': 'configuration' } ] self.assertEquals(res, expected)", "recommended to use root partition for property1', 'level': 'WARN'}, warn)", "on all hosts in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result)", "{ \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\":", "4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] = 256", "\"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\",", "\"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ]", "[\"host1\"] } }, { \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"]", "\"components\": [] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\":", "expected, \"Test Ranger Audit properties\") def test_recommendHDFSConfigurations(self): configurations = {", "'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env': { 'properties':", "not existing DB_FLAVOR and http enabled, HDP-2.3\") # Recommend for", "= {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) def", "512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\":", "\"value1\"} recommendedDefaults = {} expected = {'level': 'ERROR', 'message': 'Value", "{ \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\":", "6, \"disk\": 6, \"ram\": 48, \"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\":", "'host_groups': [{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }], 'name': 'host-group-1' },", "set to true for distributed mode', 'type': 'configuration' } ]", "# local FS, no enough space hostInfo = {\"disk_info\": [", "\"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{", "= os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor'", "bindings if binding[\"name\"] == hostGroupName][0] hosts = [info[\"fqdn\"] for info", "hosts) # host2 self.assertEquals(namenode, hosts[\"items\"][1]) # not installed nodemanager =", "[{ \"size\": '8', \"mountpoint\": \"/\" }] } }, { \"href\":", "recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations =", "None) # non-local FS, WASB properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties,", "\"host_name\" : \"host2\", \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\"", "'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'It is not recommended to", "\"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } } } } expected =", "no enough disk space host['Hosts']['disk_info'] = [ { \"available\" :", "res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\": { \"properties\": {", "= {\"disk_info\": [ { \"available\" : \"2\", \"type\" : \"ext4\",", "self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components = []", "'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir':", "[\"host1\"] } } ] }, { \"StackServices\": { \"service_name\": \"HDFS\"", "2.0 (the \"License\"); you may not use this file except", "\"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services,", "{ \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": { \"properties\":", "expected) # incorrect hbase.rootdir in distributed mode properties = {", "\"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152 } }, {", "\"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\":", "self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations = { \"mapred-site\": { \"properties\":", "2) self.assertEquals(datanodes, hosts[\"items\"]) datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode,", ") self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace", "except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def", "\"validateTezConfigurations2.2\"} } expected = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"},", "test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []}", "set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo =", "\"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }]", "= {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties,", "# 15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" },", "result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"]", "\"StackServices\": { \"service_name\": \"FALCON\" }, \"components\": [] }, { \"StackServices\":", "\"type\" : \"vboxsf\", \"mountpoint\" : \"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "6291456, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"},", "MagicFile(object): def read(self): return \"\"\" #test line UID_MIN 200 UID_MIN", "user /var mountpoint, which is non-root , but not preferable", "{ \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\",", "[] hosts = { \"items\" : [ { \"Hosts\" :", "'ams-hbase-site', 'level': 'WARN', 'message': 'In distributed mode hbase.rootdir should point", "use this file except in compliance with the License. You", "return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "[\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ {", "hosts (not having any component installed) as part of recommendation", "512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test - Cluster", "next[\"host\"] = item[\"host\"] except KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems)", "the existing layout \"\"\" services = { \"services\" : [", "{'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName,", "{ \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\":", "'*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups':", "[{ 'name': 'DATANODE' }] }] }, 'blueprint_cluster_binding': { 'host_groups': [{", "{} clusterData = { \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54", "for item in result[\"items\"]: next = {\"message\": item[\"message\"], \"level\": item[\"level\"]}", "}, 'ranger-env': {'properties': {}}, 'usersync-properties': { 'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636',", "services, None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations = {} services", "\"2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] }", "{ 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not", "}, 'blueprint_cluster_binding': { 'host_groups': [{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }],", "expected) # Test - Cluster data with 2 hosts -", "}, 'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED':", "\"total_mem\" : 500000, \"host_name\" : \"host2\", \"disk_info\" : [ {\"mountpoint\"", "= self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts =", "\"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\": True,", "\"hostnames\": [\"host1\"] } }, { \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\":", "\"/\" }] } }, ]} services = { \"services\": [", "space, no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "= { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:7777\" } }", "- no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) #", "recommendedDefaults, \"property1\"), None) properties = {\"property1\": \"value1\"} recommendedDefaults = {\"property1\":", "#Value is begger then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties", "used by datanode to store HDFS data', 'type': 'configuration' }", "'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'In distributed mode hbase.rootdir", "= [ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN', 'message': 'Should", "{'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties':", "# /boot with more space available hostInfo[\"disk_info\"].append( { \"available\" :", "warning hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"ext4\", \"mountpoint\"", "'DATANODE' }] }] }, 'blueprint_cluster_binding': { 'host_groups': [{ 'hosts': [{", "set value value2 for property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults,", "HDP-2.3 services = { \"Versions\" : { \"stack_version\" : \"2.3\",", "\"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"] = { 'properties': { 'dfs.datanode.data.dir':", "recommendedDefaults, 'property1', hostInfo) == None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576", "= [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems = [ { 'message':", "], \"configurations\": {} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected =", "= { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"POSTGRES\", } },", "test_validateHDFSConfigurationsEnv(self): configurations = {} # 1) ok: namenode_heapsize > recommended", "{\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected = { \"HDFS\":", "'256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) #", "{ \"available\" : \"6\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\"", "binding in bindings if binding[\"name\"] == hostGroupName][0] hosts = [info[\"fqdn\"]", "'Value is less than the recommended default of 256', 'type':", "configurations } # positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services,", "\"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\":", "} ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected", "hbase.rootdir should point to HDFS.', 'type': 'configuration' }, { 'config-name':", "\"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\": True}] } ] services", "res_expected) # 2) fail: namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] =", "= { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties", ": [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" :", "= self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {\"message\":", "less than the recommended minimum of 0.8 ', 'level': 'WARN',", "= imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) ) with", "\"/\" } ] recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase',", "[ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\":", "\"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\",", "\"configurations\": {} } hosts = { \"items\" : [ {", "\"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\",", "1048576 } }, ] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services,", "\"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False}] } ] services", "\"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems", "in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo", "\"properties\": { \"policymgr_external_url\": \"https://host1:7777\" } } } recommendedConfigurations = {}", "\"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"]", "expected) properties['metrics.reporter.register'] = '' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services,", "(the \"License\"); you may not use this file except in", "\"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators,", "\"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\",", "not used\", \"level\": \"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result) def", "{ \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" : 1,", "\"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\",", "[] } for hostName in hostsNames: nextHost = {\"Hosts\":{\"host_name\" :", "'dfs.namenode.rpc-address': { 'delete': 'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services,", "test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def", "\"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } }", "'*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete':", "{'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups':", "result) def test_validationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "GB \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" }, { \"available\"", "\"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\",", "and https enabled, HDP-2.3\") # Recommend for DB_FLAVOR ORACLE and", "{ \"properties\": { \"falcon_user\": \"falcon\" } } } hosts =", "Recommend for DB_FLAVOR POSTGRES and https enabled, HDP-2.3 configurations =", "'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari Metrics disk space requirements", "result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [ { \"name\": \"HDFS\", \"components\":", "errorMsg, 'level': 'WARN'}, warn) # non-local FS, HDFS properties =", "} ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more space available", "components, None) self.assertEquals(result, expected) def test_recommendStormConfigurations(self): # no AMS configurations", "\"2.0.6\" } } services[\"services\"] = [] for serviceInfo in servicesInfo:", "nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] = [] for component", "' '/ is already used by datanode to store HDFS", "\"mountpoint\" : \"/grid/0\" } ) recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn", ": \"2.3\", }, \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\",", "48, \"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\":", "}, \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\"", "], \"configurations\": configurations } # only 1 partition, enough disk", "than the recommended minimum of 0.8 ', 'level': 'WARN', 'config-type':", "test_getHostNamesWithComponent(self): services = { \"services\": [ { \"StackServices\": { \"service_name\":", "\"size\": '8', \"mountpoint\": \"/\" }] } }, ]} services =", "\"href\" : \"/api/v1/hosts/host2\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\"", "expected = { \"storm-site\": { \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" }", "{'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res)", "the Apache License, Version 2.0 (the \"License\"); you may not", "or implied. See the License for the specific language governing", "None, None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components", "\"service_name\": \"ZOOKEEPER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_SERVER\",", "KIND, either express or implied. See the License for the", "{} for hostGroup in blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos =", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"]", "} services = { \"services\": [ { \"StackServices\": { \"service_name\":", ": \"/default-rack\", \"total_mem\" : 2097152 } }, { \"href\" :", "] } ], \"configurations\": configurations } result = self.stackAdvisor.getZKHostPortString(services) expected", "= self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) #Value is less", "[{ 'name': 'host-group-1', 'components': [] }, { 'name': 'host-group-2', 'components':", "hosts) self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\",", "[ host ] } services = { \"services\": [ {", "{ \"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\": { \"properties\": { \"http.enabled\":", "{} recommendedDefaults = {\"property1\": \"value2\"} expected = {'level': 'ERROR', 'message':", "\"custom_commands\": [], \"display_name\": \"Hive Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\":", "partition / is 1G\" # local FS, enough space hostInfo", "hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services = { \"services\": [", "\"Value is less than the recommended default of 512\", \"level\":", "[] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected =", "\"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\":", "partition for property1', 'level': 'WARN'}, warn) # Set by user", "\"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } }", "] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo = [ { \"name\":", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\",", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "nextHost = {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return hosts def prepareServices(self,", "}, { \"StackServices\": { \"service_name\": \"HIVE\" }, \"components\": [{ \"href\":", "\"SERVICE\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\":", "[ { \"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } }", ": 2097152 } }, { \"href\" : \"/api/v1/hosts/host2\", \"Hosts\" :", "'/ partition is already used as hbase.rootdir to store metrics", "\"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": {", "\"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\",", "}, { 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider", "self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ { \"name\": \"YARN\",", "{ \"properties\": { \"oozie_user\": \"oozie\" } }, \"falcon-env\": { \"properties\":", "{'minimum': '0.8'} } } } items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults,", "{\"service_name\" : \"YARN\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{", "self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData = {", "{ \"policymgr_external_url\": \"https://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations,", "self.assertValidationResult(expectedItems, result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems = [] result =", "] recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false'", "than the recommended default of 512\", \"level\": \"WARN\"}, {'message': 'Value", "= services = {\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\" :", "you under the Apache License, Version 2.0 (the \"License\"); you", "services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations = {} # 1)", "\"hBaseInstalled\": True, \"components\": components, \"cpu\": 6, \"disk\": 6, \"ram\": 48,", "host in hosts: if host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for", "\"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\": \"true\",", "{ \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }, \"components\": [ { \"StackServiceComponents\":", "\"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] },", "def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", "\"ram\": 6, \"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072,", "= hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] =", "services[\"services\"] = [] for serviceInfo in servicesInfo: nextService = {\"StackServices\":{\"service_name\"", "result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "ORACLE and https enabled, HDP-2.2\") # Test Recommend LDAP values", "'http://host1:6080', } }, 'ranger-env': {'properties': {}}, 'usersync-properties': { 'properties': {", "{ \"available\" : \"5\", \"type\" : \"vboxsf\", \"mountpoint\" : \"/vagrant\"", "http enabled, HDP-2.3 services = { \"Versions\" : { \"stack_version\"", "not added to any free hosts (not having any component", "\"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\"", "= [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\":", "ownership. The ASF licenses this file to you under the", "\"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} }", "\"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] }", "hostName in hostsNames: nextHost = {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return", "'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations,", "hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"ext4\", \"mountpoint\" :", "for additional information regarding copyright ownership. The ASF licenses this", "clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR POSTGRES and", "the License for the specific language governing permissions and limitations", "\"webhcat\", \"hive_user\": \"hive\" } }, \"oozie-env\": { \"properties\": { \"oozie_user\":", "= {\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\" : \"2.6.0.2.2\" },", "# 1 partition, no enough disk space host['Hosts']['disk_info'] = [", "} self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo = None", "def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components = [] hosts =", "in the cluster before \"\"\" servicesInfo = [ { \"name\":", "hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData = {} # Recommend", "\"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result,", "implied. See the License for the specific language governing permissions", "hosts: if host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"6\", \"type\" : \"ext4\",", "}, \"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" } } }", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "Recommend for not existing DB_FLAVOR and http enabled, HDP-2.3 services", "\"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList =", "\"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", } } } services['configurations'] = configurations", "= self.prepareServices(servicesInfo) localhost = socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"]) result", "\"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False,", "exists_mock, open_mock): class MagicFile(object): def read(self): return \"\"\" #test line", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" } }", "\"hadoop-env\": { \"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\" } },", "hostInfo = {\"disk_info\": [ { \"available\" : \"1048578\", \"type\" :", "hosts) expectedItems = [ {\"message\": \"Host is not used\", \"level\":", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"5\", \"type\" : \"vboxsf\",", "\"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }], \"configurations\": configurations,", "\"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\": 512,", "'to report the metrics to Ambari Metrics service.', 'type': 'configuration'", "= [] hosts = { \"items\" : [] } result", "self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations = { \"hdfs-site\": { \"properties\":", "\"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } parentValidators = { \"HDFS\":", "GB \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ] recommendedDefaults", "\"properties\": { \"oozie_user\": \"oozie\" } }, \"falcon-env\": { \"properties\": {", "\"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\":", "{'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env':", "\"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]} ] } ]", ") self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo = {\"disk_info\":", "= {\"property1\": \"value2\"} expected = {'level': 'ERROR', 'message': 'Value should", "'message': 'Value should be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"),", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] }", ": \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } hosts =", "not recommended to use root partition for property1', 'level': 'WARN'},", "self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE is placed on host-group-2 self.assertEquals(recommendations['blueprint']['host_groups'][1]['components'][0]['name'],", "{ \"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations } expected", "exc_tb): pass def __enter__(self): return self exists_mock.return_value = True open_mock.return_value", ": \"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\",", "} ] self.assertEquals(res, expected) def test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\":", "} } } expected = { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\",", "be integer\", \"level\": \"ERROR\"}, {\"message\": \"Value should be set\", \"level\":", "\"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None)", "} } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"] =", "expectedItems = [ {\"message\": \"Host is not used\", \"host\": \"host2\",", "hostGroup in blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for", "recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) # 2) fail: namenode_heapsize,", "} }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) def", "\"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152, \"disk_info\": [ {", "self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) # host2", "for property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties", "\"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems =", "\"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\", \"category\":", "writing, software distributed under the License is distributed on an", "= self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object):", "\"is_master\": True, \"hostnames\": [\"host2\"]} ] } ] services = self.prepareServices(servicesInfo)", "} # positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None)", "\"reduceMemory\": 170.66666666666666, \"amMemory\": 170.66666666666666 } self.assertEquals(result, expected) def prepareHosts(self, hostsNames):", "\"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\",", "should be set to true for distributed mode', 'type': 'configuration'", "\"custom_commands\": [], \"display_name\": \"WebHCat Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\":", "self.assertEquals({'message': 'It is not recommended to use root partition for", "{ \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] } } ] } ],", "{ \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" } } } recommendedDefaults =", "{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}", "True, \"hostnames\": [\"host1\", \"host2\"]} ] } ] services = self.prepareServices(servicesInfo)", "in compliance with the License. You may obtain a copy", "nextService[\"components\"] = [] for component in serviceInfo[\"components\"]: nextComponent = {", "} ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more", "'message': 'Value should be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"),", "\"display_name\":\"NodeManager\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ]", "} services = { \"services\" : [ ], \"configurations\": {", "\"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [ { \"StackServiceComponents\": {", "'properties': { 'SYNC_LDAP_URL': 'ldaps://c6403.ambari.apache.org:636', 'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid'", "self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators =", "'name': 'host-group-2' }] } } \"\"\" # Assert that the", "properties['namenode_opt_maxnewsize'] = '255' res_expected = [{'config-type': 'hadoop-env', 'message': 'Value is", ": \"ext4\", \"mountpoint\" : \"/grid/1\" } ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"],", "}, { \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } }", "default of 256', 'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations,", "] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ { \"name\":", "= \"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"] = { 'properties': {", "\"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } }", "= 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected", ": \"YARN\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\",", "\"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\":", "'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties':", "\"DB_FLAVOR\": \"ORACLE\", } }, \"ranger-site\": { \"properties\": { \"http.enabled\": \"false\",", "self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\":", "{ \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } } ] } ],", "'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level':", ": \"host1\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" :", "# Test - Cluster data with 2 hosts - pick", "'256'} properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' :", "'/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir'", ": \"/vagrant\"} ] } } ] } expected = {", "= [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with low space", "= 1048576 errorMsg = \"Ambari Metrics disk space requirements not", "\"value1\"} recommendedDefaults = {\"property1\": \"value2\"} expected = {'message': 'It is", "\"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\":", "\"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\":", "'1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services,", "'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration' } ] self.assertEquals(expectedItems, items)", "ok: namenode_heapsize > recommended recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize' :", "\"1048578\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]} properties", "test_validationMinMax(self): configurations = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\",", "{ \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": {", "requirements not met. \\n\" \\ \"Recommended disk space for partition", "{'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari Metrics disk", "5, \"ramPerContainer\": 256 } expected = { \"yarn-env\": { \"properties\":", "{ \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\": { \"properties\":", "{ \"properties\": { \"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\": { \"properties\":", "clusterData, services, None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {}", "self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems = [] result = self.stackAdvisor.validateConfigurations(services, hosts)", "345.6666666666666, \"amMemory\": 123.54 } expected = { \"mapred-site\": { \"properties\":", "hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations = {} # 1) ok:", "], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ]", "\"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } } recommendedDefaults = {", "None) # local FS, no enough space hostInfo = {\"disk_info\":", "result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {'message': 'Queue is", "either express or implied. See the License for the specific", "available hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\"", "{'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env':", "\"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat Server\",", "\"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"},", "\"License\"); you may not use this file except in compliance", "\"min_user_id\": \"500\", 'service_check.queue.name': 'default' } }, \"yarn-site\": { \"properties\": {", "store metrics data', 'type': 'configuration' }, { 'config-name': 'hbase.rootdir', 'config-type':", "\"properties\": { \"hbase.superuser\": \"hbase\" } }, \"hbase-env\": { \"properties\": {", "not preferable - no warning hostInfo[\"disk_info\"].append( { \"available\" : \"1\",", "\"hbase-env\": { \"properties\": { \"hbase_user\": \"hbase123\" } } } }", "'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed property should be", "test_recommendationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\",", "{\"message\": \"Host is not used\", \"host\": \"host1\", \"level\": \"ERROR\"} ]", "License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed", "'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts':", "\"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",", "\"/vagrant\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more", "'1022' properties['namenode_opt_maxnewsize'] = '255' res_expected = [{'config-type': 'hadoop-env', 'message': 'Value", "} ] } expected = { \"hBaseInstalled\": True, \"components\": components,", "self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [] self.assertEquals(res, expected)", "mountpoint, which is non-root , but not preferable - no", "'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY':", "= { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" :", "{ \"service_name\" : \"HDFS\" }, \"components\" : [ { \"StackServiceComponents\"", "\"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, { \"StackServices\":", "hosts) expectedItems = [ {'message': 'Queue is not exist, or", "'*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved':", "= {\"configurations\": configurations, \"services\": []} clusterData = { \"containers\" :", "= {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"),", "'2047'}, 'some_float_value': {'minimum': '0.8'} } } } items = []", "Recommend LDAP values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\"", "hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"tmpfs\", \"mountpoint\" :", "self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Exactly 2 Ganglia Monitor", "# proper mountpoint with more space available hostInfo[\"disk_info\"].append( { \"available\"", ": '1', \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]", "imp, os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor", "{\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\"", "componentName in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts = actualComponentHostsMap[componentName] self.checkEqual(expectedHosts,", "next = {\"message\": item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"] = item[\"host\"]", "== None) # More preferable /grid/0 mountpoint - warning hostInfo[\"disk_info\"].append(", "\"value1\"} recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties", "recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '512'} res =", "Metrics service.', 'type': 'configuration' } ] self.assertEquals(res, expected) def test_getHostsWithComponent(self):", "Ranger Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\": {", "hostInfo, reqiuredDiskSpace) == None) # local FS, no enough space", "fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb') as", "{ \"Versions\" : { \"stack_version\" : \"2.3\", }, \"services\": [", "\"disk\": 6, \"ram\": 48, \"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\": 2048,", "} } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def", "{\"message\": \"Value should be set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result)", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\":", "expectedItems = [ {\"message\": \"Host is not used\", \"host\": \"host1\",", "[\"HBASE\"] components = [] hosts = { \"items\" : [", "[ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "{ } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected)", "\"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat Server\", \"is_client\":", "clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData,", "'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user':", "testDirectory = os.path.dirname(os.path.abspath(__file__)) stackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory,", "governing permissions and limitations under the License. ''' import socket", "self.assertEquals(res, expected) # incorrect hbase.rootdir in distributed mode properties =", "= [ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message':", "], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\"", "\"ext4\", \"mountpoint\" : \"/\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs", "hosts = { \"items\": [] } for hostName in hostsNames:", "'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari Metrics disk space requirements not", "clusterData, services, hosts) self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services = {", "\"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\",", "nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService)", "} hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\"", "\"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]}, {\"name\": \"GANGLIA_SERVER\", \"cardinality\":", "0, \"disk\": 0, \"ram\": 0, \"reservedRam\": 1, \"hbaseRam\": 1, \"minContainerSize\":", "\"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\" }, { \"available\" :", ": \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" :", ": [ host ] } services = { \"services\": [", "\"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\", \"host2\"]},", "\"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"2\", \"category\": \"MASTER\", \"is_master\": True,", "test_getZKHostPortString(self): configurations = { \"zoo.cfg\": { \"properties\": { 'clientPort': \"2183\"", "'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env', 'level': 'WARN', 'message': 'Value is", "is greater than the recommended maximum of 2047 ', 'level':", "recommendedDefaults = {\"property1\": \"file:///var/dir\"} # only / mountpoint - no", "} ] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services,", "def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"]", "expected) def test_recommendStormConfigurations(self): # no AMS configurations = {} services", "[\"host1\"] } } ] } ], \"configurations\": { \"admin-properties\": {", "under one or more contributor license agreements. See the NOTICE", "be set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo", ": [ { \"Hosts\" : { \"cpu_count\" : 6, \"total_mem\"", "} recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false'", "{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]}", "\"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\",", ": [ { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\"", "} ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) def test_validatorEnoughDiskSpace(self):", "\"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": { \"properties\": {} } }", "} hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" : 4,", ": { \"cardinality\" : \"1+\", \"component_category\" : \"SLAVE\", \"component_name\" :", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo = {\"disk_info\": [ { \"available\" :", "\"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[", "\"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\":", "hosts) self.assertEquals(nodemanager, None) # unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\",", "{ \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\": { \"properties\":", "'It is not recommended to use root partition for hbase.rootdir',", "\"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" } } ],", "& hbase.rootdir crosscheck + root partition + hbase.rootdir == hbase.tmp.dir", "{} expected = {'level': 'ERROR', 'message': 'Value should be recommended", "class MagicFile(object): def read(self): return \"\"\" #test line UID_MIN 200", "[{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}]", "# not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager,", "the recommended default of 256', 'type': 'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties,", "{\"message\": \"Ganglia Monitor component should be installed on all hosts", "\"yarn.scheduler.maximum-allocation-mb\": \"1280\" } } } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations,", "from mock.mock import patch, MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self): import", ": 1, \"host_name\" : \"host2\", \"os_arch\" : \"x86_64\", \"os_type\" :", "\"0.5.0\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\":", "= self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes,", "{ \"hBaseInstalled\": True, \"components\": components, \"cpu\": 6, \"disk\": 6, \"ram\":", "\"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\"", "# Test Ranger Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"] = {", "\"properties\": {} } } expected = { 'admin-properties': { 'properties':", "\"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } }, { \"StackServiceComponents\": { \"component_name\": \"METRICS_MONITOR\",", "\"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive Server\", \"is_client\": \"false\", \"is_master\":", "data. ' '/ is already used by datanode to store", "'256', 'namenode_opt_maxnewsize' : '256'} properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize' :", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space available hostInfo[\"disk_info\"].append( { \"available\"", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" }", "not recommended to use root partition for hbase.rootdir', 'type': 'configuration'", "open_mock.return_value = MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo = [", "\"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\",", "partition, no enough disk space host['Hosts']['disk_info'] = [ { \"available\"", "self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None) # unknown service unknown_component", "\"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]} ] } ] services =", "\"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\":", "'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*',", "\"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\": False,", "\"ranger-hdfs-plugin-properties\": { \"properties\": {} } } expected = { 'admin-properties':", "expected) def prepareHosts(self, hostsNames): hosts = { \"items\": [] }", "Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\":", "\"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 } expected = { \"mapred-site\": {", "is non-root , but not preferable - no warning hostInfo[\"disk_info\"].append(", "} hosts = { \"items\": [ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\":", "'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}},", "Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]}", "not met. ' '\\nRecommended disk space for partition / is", "hostInfo) self.assertTrue(warn != None) self.assertEquals({'message': 'It is not recommended to", "item[\"level\"]} try: next[\"host\"] = item[\"host\"] except KeyError, err: pass actualItems.append(next)", "configurations } expected = { \"storm-site\": { \"properties\": { }", "{ \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [ { \"StackServiceComponents\":", "{} services = { \"services\": [ { \"StackServices\": { \"service_name\":", "\"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, { \"StackServices\":", "'message': 'Should be set to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the", "hosts for cardinality ALL even if the component has been", "\"component_name\": \"ZOOKEEPER_SERVER\", \"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\": { \"component_name\":", "\"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"},", "= [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\",", "should be as below: { 'blueprint': { 'host_groups': [{ 'name':", "\"2\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\":", "\"disk_info\": [ { \"available\": str(15<<30), # 15 GB \"type\": \"ext4\",", "\"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] }, \"dependencies\":[ ] },", "read(self): return \"\"\" #test line UID_MIN 200 UID_MIN 500 \"\"\"", "\"component_name\" : \"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\" ] } }", "def test_validationYARNServicecheckQueueName(self): servicesInfo = [ { \"name\": \"YARN\", \"components\": []", "services = { \"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\"", "{ \"policymgr_external_url\": \"http://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations,", "] } ], \"configurations\": configurations } # only 1 partition,", "'2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' : '300'} res_expected = []", "= self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services,", "for DB_FLAVOR POSTGRES and https enabled, HDP-2.3 configurations = {", "\"ext4\", \"mountpoint\" : \"/grid/0\" } ) recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"}", "not existing DB_FLAVOR and http enabled, HDP-2.3 services = {", "available hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"tmpfs\", \"mountpoint\"", "{ \"properties\": { \"http.enabled\": \"false\", \"https.service.port\": \"8888\", } } }", "{ \"properties\": { \"policymgr_external_url\": \"https://host1:7777\" } } } recommendedConfigurations =", "{ \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" },", "self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) #Value is less then", "} } items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems =", "'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env': { 'properties': {", "deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\"", "recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '2048'} res =", "\"c6402.ambari.apache.org\"] }, }] }], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData", "{'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}}", "property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {\"property1\": \"value1\"} recommendedDefaults", "'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData,", "self.assertEquals(configurations, expected) def test_getHostNamesWithComponent(self): services = { \"services\": [ {", "\"oozie\" } }, \"falcon-env\": { \"properties\": { \"falcon_user\": \"falcon\" }", "used\", \"host\": \"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self):", "\"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }}] }, { \"StackServices\": {", "}, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\",", "} ] self.assertEquals(res, expected) # incorrect hbase.rootdir in distributed mode", "\"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\" } } } recommendedDefaults", "received during Add service operation. For already installed services, recommendation", "}, \"dependencies\":[ ] }, ], }], \"configurations\": {} } hosts", "configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData = { \"totalAvailableRam\": 2048 }", "'level': 'WARN', 'message': 'In distributed mode hbase.rootdir should point to", "expected) def test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\",", "be installed in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def", "\"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo,", "recommendation received during Add service operation. For already installed services,", "HDP-2.2 configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"ORACLE\",", "for partition / is 10G', 'type': 'configuration' } ] self.assertEquals(res,", "in blueprintMapping: hostGroupName = hostGroup[\"name\"] hostsInfos = [binding[\"hosts\"] for binding", "result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ { \"name\": \"YARN\", \"components\":", "\"host\": \"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList", "LDAP values\") # Test Ranger Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"]", "] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\",", "{\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators) def test_getProperMountPoint(self): hostInfo", "'host-group-1' }, { 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }], 'name': 'host-group-2'", "\"Hosts\" : { \"cpu_count\" : 1, \"host_name\" : \"host2\", \"os_arch\"", "\"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\",", "def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\",", "self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object): def", "\"services\": []} clusterData = { \"containers\" : 5, \"ramPerContainer\": 256", "\"host2\", \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"},", ": \"4\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" } )", "properties = {'namenode_heapsize': '2048', 'namenode_opt_newsize' : '300', 'namenode_opt_maxnewsize' : '300'}", "the Apache Software Foundation (ASF) under one or more contributor", "\"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\"", "'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs',", "'ERROR', 'message': 'Value should be recommended for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults,", "{ \"properties\": { } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None)", "been installed in the cluster before \"\"\" servicesInfo = [", "os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = { \"services\":", "NOTICE file distributed with this work for additional information regarding", "recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '1024'} res =", "== None) # local FS, no enough space hostInfo =", "\"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666,", "\"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\"", "test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\": { \"properties\": { \"hdfs_user\": \"hdfs\",", "\"host_name\" : \"host2\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\"", "[ {\"message\": \"Host is not used\", \"level\": \"ERROR\", \"host\": \"host2\"}", "{ 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\", \"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\":", "''' Licensed to the Apache Software Foundation (ASF) under one", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo = [ {", "500000, \"host_name\" : \"host2\", \"disk_info\" : [ {\"mountpoint\" : \"/\"},", "hosts def prepareServices(self, servicesInfo): services = { \"Versions\" : {", "componentName = component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName] =", "False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\",", "\"service_name\": \"HIVE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\":", "} } recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", "for storing metrics temporary data. ' '/ partition is already", "]} properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"} #", "any free hosts (not having any component installed) as part", "= None # substitute method in the instance self.get_system_min_uid_real =", "for distributed mode', 'type': 'configuration' } ] self.assertEquals(res, expected) def", "}, \"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\":", "use root partition for property1', 'level': 'WARN'}, warn) # Set", "\"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}] } ] services", "= self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = [ {'config-name':", "component has been installed in the cluster before \"\"\" servicesInfo", "\"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected)", "'config-type': 'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed property should be set", "} ] self.assertEquals(res, expected) # 2 partitions host['Hosts']['disk_info'] = [", "[\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]),", "parentValidators) def test_getProperMountPoint(self): hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo =", "\"ext4\", \"mountpoint\" : \"/\" } ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1',", "{ \"items\" : [ { \"Hosts\" : { \"cpu_count\" :", ": { \"stack_version\" : \"2.3\", }, \"services\": [ { \"StackServices\":", "\"/\" }] } }, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\":", "\"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]},", "}, \"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" }", ": \"2\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/dev/shm\" } )", "\"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\",", "__enter__(self): return self exists_mock.return_value = True open_mock.return_value = MagicFile() return", "\"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } hosts = {", "\"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\":", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ {", "} ambariHostName = socket.getfqdn() expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}},", "\"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\",", "None) expected = { \"hBaseInstalled\": False, \"components\": components, \"cpu\": 0,", "= changedConfigurations services['configurations'] = configurations expected = {'oozie-env': {'properties': {'oozie_user':", "[{'config-type': 'hadoop-env', 'message': 'Value is less than the recommended default", "\"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}] } ] services", "{ \"properties\": { \"mapreduce.task.io.sort.mb\": \"4096\", \"some_float_value\": \"0.5\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }", "] }, \"dependencies\":[ ] } ], }], \"configurations\": {} }", "= '1022' properties['namenode_opt_maxnewsize'] = '255' res_expected = [{'config-type': 'hadoop-env', 'message':", "for DB_FLAVOR ORACLE and https enabled, HDP-2.2 configurations = {", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint with low space available hostInfo[\"disk_info\"].append(", "def test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\": { \"properties\": { \"hdfs_user\":", "\"service_name\": \"FALCON\" }, \"components\": [] }, { \"StackServices\": { \"service_name\":", "} properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", ") recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1',", "[ { \"available\": str(15<<30), # 15 GB \"type\" : \"ext4\",", "= 170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] =", "}, \"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", }", "\"disk\": 8, \"ram\": 6, \"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\": 512,", "added to any free hosts (not having any component installed)", "} result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) def", "servicesInfo = [ { \"name\": \"YARN\", \"components\": [] } ]", "} expected = { \"storm-site\": { \"properties\": { } },", "{ \"services\" : [ ], \"configurations\": { \"hbase-site\": { \"properties\":", "hbase.rootdir', 'type': 'configuration' }, { 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level':", "} } ] }, ], \"configurations\": { \"admin-properties\": { \"properties\":", "'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\"", "= {'level': 'ERROR', 'message': 'Value should be set for property1'}", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"5\", \"type\" :", "\"HDFS\" }, \"components\": [] }, { \"StackServices\": { \"service_name\": \"FALCON\"", "\"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\",", "\"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations } # positive", "'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir':", "\"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\"", "\"2\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]} properties", "= self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) # unknown component", "self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected = { \"hBaseInstalled\": False, \"components\":", "} } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None)", ": \"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more", "{ 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not", "value value2 for property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"),", "\"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\":", "'configuration' } ] self.assertEquals(res, expected) def test_validateStormSiteConfigurations(self): configurations = {", "\"total_mem\" : 6291456, \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\"", "expectedItems = [] result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def", "imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName)", "services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR POSTGRES and https", "\"display_name\": \"Oozie Server\", \"is_client\": \"false\", \"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\":", "{ \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo", "applicable law or agreed to in writing, software distributed under", "servicesInfo): services = { \"Versions\" : { \"stack_name\" : \"HDP\",", "# unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager,", "hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation", "\"configurations\": configurations } result = self.stackAdvisor.getZKHostPortString(services) expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result,", "in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo", "], \"configurations\": configurations } expected = { \"storm-site\": { \"properties\":", "incorrect hbase.rootdir in distributed mode properties = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase',", "to org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter ' 'to report the metrics to Ambari Metrics", "hosts = { \"items\" : [] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList,", "\"host1\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1,", "in hostsInfos] for component in hostGroup[\"components\"]: componentName = component[\"name\"] try:", "test_validationHostIsNotUsed(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "}] } }, ]} services = { \"services\": [ {", "{ \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\":", "then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '512'}", "properties['metrics.reporter.register'] = '' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None)", "}, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"]", "\"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\",", "= {'message': 'It is recommended to set value value2 for", "\"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]} ]", "} } services = { \"services\": [ { \"StackServices\": {", "stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already", "\"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators = {", "1024', 'type': 'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type':", "'SYNC_LDAP_BIND_DN': 'uid=hdfs,ou=people,ou=dev,dc=apache,dc=org', 'SYNC_LDAP_USER_OBJECT_CLASS': 'posixAccount', 'SYNC_LDAP_USER_NAME_ATTRIBUTE': 'uid' } } } recommendedConfigurations", "\"dependencies\":[ ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\",", "self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations", ": \"false\", \"authentication.ldap.baseDn\" : \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" :", "} }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) #", "\"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations'] = configurations expected =", "\"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ]", "{ \"properties\": { \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None,", "self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}]", "self.assertEquals(res, expected) # 1 partition, no enough disk space host['Hosts']['disk_info']", "'configuration' }, { 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message':", "\"type\" : \"tmpfs\", \"mountpoint\" : \"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "{\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\":", "[\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]),", "\"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False}]", "\"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts) expectedItems", "{} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected,", "enough disk space, no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations,", "# 15 GB \"type\" : \"ext4\", \"mountpoint\" : \"/\" }", "test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already installed slaves are not added", "expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def", "8, \"ram\": 6, \"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\":", "\"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None)", "\"properties\": { } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations,", "host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys(): expectedHosts", "than the recommended default of 256', 'type': 'configuration'}] res =", "} hosts = { \"items\" : [ host ] }", "result) def test_validationCardinalityExactAmount(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "license agreements. See the NOTICE file distributed with this work", "datanode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes =", "OF ANY KIND, either express or implied. See the License", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\":", "\"mountpoint\": \"/\" }] } }, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\": {", "self.assertValidationResult(expectedItems, result) def test_validationCardinalityAtLeast(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "\"host2\" ] }, \"dependencies\":[ ] } ], }], \"configurations\": {}", "mode hbase.rootdir should point to HDFS.', 'type': 'configuration' }, {", "memory servicesList.append(\"YARN\") services = services = {\"services\": [{\"StackServices\": {\"service_name\" :", "services, hosts) expected = [] self.assertEquals(res, expected) # 1 partition,", "= self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts)", ": \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs with", "installed on all hosts in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems,", "}, { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } }", "in bindings if binding[\"name\"] == hostGroupName][0] hosts = [info[\"fqdn\"] for", "# Test Recommend LDAP values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" :", "[] }, { \"StackServices\": { \"service_name\": \"HIVE\" }, \"components\": [{", "} } recommendedDefaults = { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\":", "clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR ORACLE and", "{ \"StackServices\": { \"service_name\": \"HIVE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\",", "\"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"},", "greater than the recommended maximum of 2047 ', 'level': 'WARN',", "} } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations,", "'512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertTrue(res) #Value", "expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData = { \"mapMemory\":", "begger then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved':", "used\", \"level\": \"ERROR\", \"host\": \"host2\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self):", "self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\",", "\"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}] } ] services =", "} self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations", "\"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\",", "actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName] = [] for host in", "{ \"service_name\": \"HDFS\" }, \"components\": [] }, { \"StackServices\": {", "{'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties':", "\"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"] }}, { \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\":", "root mountpoint with low space available hostInfo[\"disk_info\"].append( { \"available\" :", "] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-env\":{\"properties\":{\"service_check.queue.name\": \"default\"}}, \"capacity-scheduler\":{\"properties\":{\"capacity-scheduler\": \"yarn.scheduler.capacity.root.queues=ndfqueue\\n\"}}}", "\"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\" ] } } ] }", "than the recommended maximum of 2047 ', 'level': 'WARN', 'config-type':", "self.assertValidationResult(expectedItems, result) def test_validationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services,", "\"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\": False}] } ] services =", "'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%' } } } recommendedConfigurations", ": [ { \"Hosts\" : { \"cpu_count\" : 8, \"total_mem\"", "'WARN', 'message': 'Consider not using / partition for storing metrics", "\"mountpoint\" : \"/grid/0\" } ) self.assertEquals([\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper", "actualItems) def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations = {} components", "[ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN', 'message': 'Should be", "to true for distributed mode', 'type': 'configuration' } ] self.assertEquals(res,", "{ \"available\": str(15<<30), # 15 GB \"type\": \"ext4\", \"mountpoint\": \"/\"", "'configuration'}] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected)", "recommendedDefaults, configurations, services, hosts) self.assertTrue(res) #Value is begger then expected", "{ \"items\": [] } for hostName in hostsNames: nextHost =", "\"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } }, { \"StackServiceComponents\": { \"component_name\":", "= { \"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" } },", "[ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"5\", \"type\"", "\"Ganglia Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\",", "\"mountpoint\" : \"/\" } ] recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase',", "\"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.usernameAttribute\" : \"uid\",", "\"hBaseInstalled\": True, \"components\": components, \"cpu\": 8, \"disk\": 8, \"ram\": 6,", "hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1) #", ": 500000, \"host_name\" : \"host2\", \"disk_info\" : [ {\"mountpoint\" :", "'configuration' } ] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [", "[ { \"Hosts\" : { \"cpu_count\" : 6, \"total_mem\" :", "blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"] bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for", "\"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie Server\", \"is_client\":", "{ \"yarn-env\": { \"properties\": { \"min_user_id\": \"500\", 'service_check.queue.name': 'default' }", "\"items\" : [ host ] } services = { \"services\":", "= [] for host in hosts: if host not in", "self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]),", "} ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\":", "nextComponent[\"StackServiceComponents\"][\"hostnames\"] = [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"]", "'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase',", "= { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\":", "{\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] = [] for component in serviceInfo[\"components\"]:", "{\"disk_info\": [ { \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\"", "} } ] }, { \"StackServices\": { \"service_name\": \"HDFS\" },", "Recommend on all hosts for cardinality ALL even if the", "'blueprint_cluster_binding': { 'host_groups': [{ 'hosts': [{ 'fqdn': 'c6402.ambari.apache.org' }], 'name':", "'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties,", "{\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\":", "def test_recommendYARNConfigurations(self): configurations = {} services = {\"configurations\": configurations, \"services\":", "\"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\",", "\"hostnames\": [\"host1\"] } } ] }, ], \"configurations\": { \"admin-properties\":", "[] self.assertEquals(res, expected) # 1 partition, no enough disk space", "= {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties,", "self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn != None) self.assertEquals({'message': 'It is", "'properties': { 'hbase.superuser': 'hbase123' } }, \"hbase-env\": { \"properties\": {", "\"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{", "'message': 'Value is less than the recommended minimum of 0.8", ": \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] }", "recommended to use root partition for hbase.rootdir', 'type': 'configuration' },", "= self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [] self.assertEquals(res,", "] self.assertValidationResult(expectedItems, result) def test_validationYARNServicecheckQueueName(self): servicesInfo = [ { \"name\":", "'XAAUDIT.DB.IS_ENABLED': 'true' } }, 'ranger-env': { 'properties': { 'xasecure.audit.destination.hdfs.dir': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%'", "3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None)", "[] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected)", "def test_validationCardinalityAtLeast(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [", "has been installed in the cluster before \"\"\" servicesInfo =", "components should match the existing layout \"\"\" services = {", "\"type\" : \"ext4\", \"mountpoint\" : \"/\" } ] recommendedDefaults =", "hosts) self.assertEquals(configurations, expected) # Verify dfs.namenode.rpc-address is recommended to be", "# tmpfs with more space available hostInfo[\"disk_info\"].append( { \"available\" :", "\"available\" : \"2\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" }", "recommendedDefaults, configurations, services, hosts) expected = [] self.assertEquals(res, expected) #", "\"FALCON\" }, \"components\": [] }, { \"StackServices\": { \"service_name\": \"HIVE\"", "= imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl,", "recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' }", "Foundation (ASF) under one or more contributor license agreements. See", "('.py', 'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath, 'rb') as fp: self.stack_advisor_impl", "\"METRICS_MONITOR\", \"hostnames\": [\"host1\"] } } ] }, { \"StackServices\": {", "# Set by user /var mountpoint, which is non-root ,", "expected = [ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN', 'message':", "'message': 'hbase.cluster.distributed property should be set to true for distributed", "None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR ORACLE and https enabled,", "configurations expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups':", "expected) def test_getHostNamesWithComponent(self): services = { \"services\": [ { \"StackServices\":", "{ \"zoo.cfg\": { \"properties\": { 'clientPort': \"2183\" } } }", "root partition + hbase.rootdir == hbase.tmp.dir warnings properties = {", "- warning hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"ext4\",", "any component installed) as part of recommendation received during Add", "clazz() self.maxDiff = None # substitute method in the instance", "= { \"items\": [ { \"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\":", "maximum of 2047 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb',", "Apache License, Version 2.0 (the \"License\"); you may not use", "not exist, or not corresponds to existing YARN leaf queue',", "= component[\"name\"] nextService[\"components\"].append(nextComponent) services[\"services\"].append(nextService) return services def assertHostLayout(self, componentsHostsMap, recommendation):", "[\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"])", "{ \"http.enabled\": \"false\", \"https.service.port\": \"8888\", } } } services['configurations'] =", "\"service_name\": \"OOZIE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\":", "{ \"hBaseInstalled\": True, \"components\": components, \"cpu\": 8, \"disk\": 8, \"ram\":", "[{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ {", "\"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] }, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{", "del services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\": { \"properties\": { \"fs.defaultFS\":", "[ {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"},", "hdp206StackAdvisorPath) services = { \"services\": [ { \"StackServices\": { \"service_name\":", "'WARN', 'message': 'Value is less than the recommended default of", "test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\" :", "# unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager,", "for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE is placed on", "\"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"DATANODE\", \"custom_commands\":[ ],", "'Ambari Metrics disk space requirements not met. ' '\\nRecommended disk", "configurations, services, hosts) expected = [] self.assertEquals(res, expected) # dfs.dir", "{ \"available\" : \"2\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/dev/shm\"", "{ \"available\": str(15<<30), # 15 GB \"type\" : \"ext4\", \"mountpoint\"", "\"Between 0 and 1 Ganglia Server components should be installed", "self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]) recommendations = self.stackAdvisor.createComponentLayoutRecommendations(services, hosts) \"\"\" Recommendation received should", "hostInfo = None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []} self.assertEquals([\"/\"],", "{ \"items\" : [host_item for i in range(1, 300)] }", "'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host = { \"href\"", "'property1', hostInfo) self.assertTrue(warn != None) self.assertEquals({'message': 'It is not recommended", ": {\"newserviceconf\": \"abc2.3\"} } parentValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\",", "\"hostnames\": [\"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts =", "unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None)", "self.assertEquals(recommendedConfigurations, expected, \"Test Ranger Audit properties\") def test_recommendHDFSConfigurations(self): configurations =", "{'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '1024'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults,", "]} services = { \"services\": [ { \"StackServices\": { \"service_name\":", "{ 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'It is", "hosts) expectedItems = [ {\"message\": \"Host is not used\", \"host\":", "\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo = {\"disk_info\": [ { \"available\"", "}], 'name': 'host-group-1' }, { 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }],", "virtualbox fs with more space available hostInfo[\"disk_info\"].append( { \"available\" :", "\"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\":", "HDP-2.3 configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"POSTGRES\",", "{ \"service_name\": \"ZOOKEEPER\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "[] for item in result[\"items\"]: next = {\"message\": item[\"message\"], \"level\":", ": \"7\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/1\" } )", "\"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo = {\"disk_info\": [ {", "{ \"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] } } ]", "checkEqual(self, l1, l2): if not len(l1) == len(l2) or not", "fail: namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] =", "6, \"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\": 11, \"ramPerContainer\":", "\"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"}", "} expected = { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties", "'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env':", "self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '') self.assertEquals(res, res_expected) # 2) fail:", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"4\", \"type\" : \"tmpfs\",", "\"is_master\": \"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\",\"c6402.ambari.apache.org\"]", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]} ] } ] services", ": \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152, \"disk_info\": [", "} } ] } ] } hosts = self.prepareHosts([\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"])", ": 2097152, \"disk_info\": [ { \"available\": str(15<<30), # 15 GB", "} self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations", "} ]} properties = {\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"}", "\"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations = {} services =", "\"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": { \"properties\": {}", "\"property1\"), expected) def test_getServicesSiteProperties(self): import imp, os testDirectory = os.path.dirname(os.path.abspath(__file__))", "services[\"services\"].append(nextService) return services def assertHostLayout(self, componentsHostsMap, recommendation): blueprintMapping = recommendation[\"recommendations\"][\"blueprint\"][\"host_groups\"]", "ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts':", "'property1', hostInfo, reqiuredDiskSpace) == None) # local FS, no enough", "[ {'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Ambari Metrics", "\"dependencies\":[ ] } ], }], \"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] =", "POSTGRES and https enabled, HDP-2.3\") # Recommend for DB_FLAVOR ORACLE", "], \"configurations\": configurations } # positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults,", ": \"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\" ]", "hostGroupName][0] hosts = [info[\"fqdn\"] for info in hostsInfos] for component", "method in the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic", "services = { \"services\" : [ ], \"configurations\": { \"hbase-site\":", "configurations, '', '') self.assertEquals(res, res_expected) def test_validateAmsHbaseSiteConfigurations(self): configurations = {", "\"hostnames\": [\"host1\"]}, {\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True,", "10G', 'type': 'configuration' } ] self.assertEquals(res, expected) # 2 partitions", "\"mountpoint\" : \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) ==", "\"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"} # only / mountpoint -", "datanode to store HDFS data', 'type': 'configuration' } ] self.assertEquals(res,", "\"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"},", "= [] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] =", "{ 'hbase-site': { 'properties': { 'hbase.superuser': 'hbase123' } }, \"hbase-env\":", "cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo =", "'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations,", "'hbase.cluster.distributed property should be set to true for distributed mode',", ": \"ext4\", \"mountpoint\" : \"/\" } ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties,", "'property_attributes': { 'dfs.namenode.rpc-address': { 'delete': 'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations,", "}, ], }], \"configurations\": {} } hosts = { \"items\"", "{ \"service_name\": \"AMBARI_METRICS\" } } ], \"configurations\": configurations } #", "expected, \"Test for not existing DB_FLAVOR and http enabled, HDP-2.3\")", "\"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\": {", "recommendedDefaults = {\"property1\": \"value2\"} expected = {'level': 'ERROR', 'message': 'Value", "\"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\",", "self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"hdfs:///hdfs_path\", [\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self):", "{'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize':", "\"hostnames\":[ \"host2\" ] }, \"dependencies\":[ ] }, ], }], \"configurations\":", "= [ {\"message\": \"Host is not used\", \"host\": \"host1\", \"level\":", "} datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(len(datanodes), 2) self.assertEquals(datanodes,", ": { \"stack_name\" : \"HDP\", \"stack_version\" : \"2.0.6\" } }", "\"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"},", "\"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\",", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" : \"tmpfs\",", "}, ], \"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\",", "\"rack_info\": \"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\"", "result): actualItems = [] for item in result[\"items\"]: next =", "return \"\"\" #test line UID_MIN 200 UID_MIN 500 \"\"\" def", "\"/dev/shm\"}, {\"mountpoint\" : \"/vagrant\"} ] } } ] } expected", "{ \"href\": \"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\":", "170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] = 0", "\"AMBARI_METRICS\" } } ], \"configurations\": configurations } expected = {", "0.8 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration'", "], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ]", "\"\"\" #test line UID_MIN 200 UID_MIN 500 \"\"\" def __exit__(self,", "\"level\": item[\"level\"]} try: next[\"host\"] = item[\"host\"] except KeyError, err: pass", "0 expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] = 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList,", "{ \"cardinality\" : \"1+\", \"component_category\" : \"SLAVE\", \"component_name\" : \"DATANODE\",", "expected = { \"storm-site\": { \"properties\": { } }, }", "{ \"StackServiceComponents\": { \"component_name\": \"NAMENODE\", \"hostnames\": [\"host1\"] } } ]", "{ \"falcon_user\": \"falcon\" } } } hosts = { \"items\":", "expectedItems = [ {\"message\": \"Exactly 2 Ganglia Monitor components should", "cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo =", "data. ' '/ partition is already used as hbase.rootdir to", "pass def __enter__(self): return self exists_mock.return_value = True open_mock.return_value =", "'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = {", ": [ \"c6401.ambari.apache.org\" ] } } ] } ] }", "\"HDFS\", \"components\": [ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\":", "\"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\",", "\"HDP\", \"stack_version\" : \"2.0.6\" } } services[\"services\"] = [] for", "\"AMBARI_METRICS\" } } ], \"configurations\": configurations } # positive res", "self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) def test_getServicesSiteProperties(self): import imp, os testDirectory", "{ \"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/var\"", "'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize': '256'}}} self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts)", "[ { \"name\": \"HDFS\", \"components\": [ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\",", "namenode_heapsize > recommended recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256',", "\"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\",", "\"components\": [] }, { \"StackServices\": { \"service_name\": \"HIVE\" }, \"components\":", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationCardinalityExactAmount(self): servicesInfo = [ {", "hbase.tmp.dir warnings properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase',", "\"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\":", "= { \"Versions\" : { \"stack_version\" : \"2.3\", }, \"services\":", "= { \"hadoop-env\": { \"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\": \"users\"", "= {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) #", "POSTGRES and https enabled, HDP-2.3 configurations = { \"admin-properties\": {", "True open_mock.return_value = MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self): servicesInfo =", "'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}},", "\"configurations\": {} } result = self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"]", "\"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ]", "'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups': '*',", "local FS, no enough space hostInfo = {\"disk_info\": [ {", "\"advertise_version\":\"true\", \"cardinality\":\"1-2\", \"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\",", "received should be as below: { 'blueprint': { 'host_groups': [{", "\"hostnames\" : [ \"c6401.ambari.apache.org\" ] } } ] } ]", "= \"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\" : 4, \"total_mem\" :", "'1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address': {", "recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' }", "# Recommend for DB_FLAVOR ORACLE and https enabled, HDP-2.2 configurations", "self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\": \"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([])", "{ \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ]", "test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "\"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"ALL\", \"category\": \"MASTER\", \"is_master\": True}] }", "test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components = [] hosts = {", "\"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\": { \"properties\": {", ": 1, \"public_host_name\" : \"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\" :", "self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn) # non-local FS, HDFS properties", "\"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia", "\"totalAvailableRam\": 3072, \"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\": 512,", "hosts, components, services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"]", "\"StackServices\": { \"service_name\": \"OOZIE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\":", "{ \"hbase.superuser\": \"hbase\" } }, \"hbase-env\": { \"properties\": { \"hbase_user\":", "'*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups':", "\"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive Server\", \"is_client\": \"false\",", "configurations = { \"zoo.cfg\": { \"properties\": { 'clientPort': \"2183\" }", "{'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org',", "'type': 'configuration' }, { 'config-name': 'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN',", "should point to HDFS.', 'type': 'configuration' }, { 'config-name': 'hbase.cluster.distributed',", "}, \"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\"", "errorMsg = \"Ambari Metrics disk space requirements not met. \\n\"", "os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services", "\"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb':", "imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) ) with open(hdp206StackAdvisorPath,", "3072, \"containers\": 6, \"ramPerContainer\": 512, \"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\":", "expected = { 'hbase-site': { 'properties': { 'hbase.superuser': 'hbase123' }", "bindings = recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for hostGroup in blueprintMapping:", "\"service_version\": \"0.5.0\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\",", "{ \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] }, {", "2 partitions host['Hosts']['disk_info'] = [ { \"available\": str(15<<30), # 15", "1, \"hbaseRam\": 1, \"minContainerSize\": 256, \"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\":", "{ \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } } ]", "minimum memory servicesList.append(\"YARN\") services = services = {\"services\": [{\"StackServices\": {\"service_name\"", "\"configurations\": configurations } expected = { \"storm-site\": { \"properties\": {", "= {\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value2\"} expected = {'message':", "{\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"0-1\", \"category\": \"MASTER\", \"is_master\":", "\"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{ \"size\": '8',", "'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir':", "installed in the cluster before \"\"\" servicesInfo = [ {", "[\"host1\"] } } ] } ], \"configurations\": configurations } #", "'ams-hbase-site', 'level': 'ERROR', 'message': 'hbase.cluster.distributed property should be set to", "substitute method in the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid =", "= self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected = { \"hBaseInstalled\": False,", "{ \"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\":", "} }, ] } datanodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"DATANODE\", services, hosts)", "res_expected = [] res = self.stackAdvisor.validateHDFSConfigurationsEnv(properties, recommendedDefaults, configurations, '', '')", "temporary data. ' '/ partition is already used as hbase.rootdir", "= recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for hostGroup in blueprintMapping: hostGroupName", "} items = [] self.stackAdvisor.validateMinMax(items, recommendedDefaults, configurations) expectedItems = [", "test_validationCardinalityALL(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "= {\"Hosts\":{\"host_name\" : hostName}} hosts[\"items\"].append(nextHost) return hosts def prepareServices(self, servicesInfo):", "\"services\" : [ ], \"configurations\": { \"hbase-site\": { \"properties\": {", "self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self):", "} } ] } ], \"configurations\": configurations } result =", "'/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties,", "\"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152 } }, { \"href\"", "self.assertEquals(nodemanager, None) # unknown service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services,", "\"mountpoint\" : \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # virtualbox fs", "\"AMBARI_METRICS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\":", ": \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\" :", "\"0\", \"yarn.scheduler.minimum-allocation-mb\": \"str\"}}} hosts = self.prepareHosts([]) result = self.stackAdvisor.validateConfigurations(services, hosts)", "self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1)", "= [ { \"name\": \"HDFS\", \"components\": [ {\"name\": \"NAMENODE\", \"cardinality\":", "{ 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode']", "\"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected)", "\"true\", \"service_name\": \"HIVE\", \"stack_name\": \"HDP\", \"stack_version\": \"2.0.6\", \"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"]", "None) def test_round_to_n(self): self.assertEquals(self.stack_advisor_impl.round_to_n(0), 0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097),", "self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap", "the NOTICE file distributed with this work for additional information", "'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res", "\"false\", \"https.service.port\": \"8888\", } } } services['configurations'] = configurations expected", "\"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[ ] } ], }],", "the recommended minimum of 0.8 ', 'level': 'WARN', 'config-type': 'mapred-site',", "\"cpu\": 8, \"disk\": 8, \"ram\": 6, \"reservedRam\": 2, \"hbaseRam\": 1,", "{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\":", "services, hosts) self.assertEquals(nodemanager, None) # unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\",", "= {\"property1\": \"value2\"} expected = {'message': 'It is recommended to", "\"/default-rack\", \"total_mem\": 1048576, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }]", "\"users\" } }, \"hive-env\": { \"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\":", "[ { \"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] } }", "Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\":", "'', '') self.assertEquals(res, res_expected) # 2) fail: namenode_heapsize, namenode_opt_maxnewsize <", "hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn)", "Recommendation received should be as below: { 'blueprint': { 'host_groups':", "and limitations under the License. ''' import socket from unittest", "to any free hosts (not having any component installed) as", "self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertTrue(res) #Value is begger then", "{ \"oozie_user\": \"oozie\" } }, \"falcon-env\": { \"properties\": { \"falcon_user\":", "default of 512\", \"level\": \"WARN\"}, {'message': 'Value should be set", "to the Apache Software Foundation (ASF) under one or more", "'message': 'Consider not using / partition for storing metrics temporary", "\"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None,", ": [] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) expected", "configurations = {} services = {\"configurations\": configurations, \"services\": []} clusterData", "expected) def test_recommendRangerConfigurations(self): clusterData = {} # Recommend for not", "\"service_name\": \"SERVICE\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"COMPONENT\",", "} ], \"configurations\": configurations } result = self.stackAdvisor.getZKHostPortString(services) expected =", "[ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\":", "https enabled, HDP-2.2\") # Test Recommend LDAP values services[\"ambari-server-properties\"] =", "software distributed under the License is distributed on an \"AS", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"7\", \"type\" :", "host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) # Assert that DATANODE is placed on host-group-2", "= {} # Recommend for not existing DB_FLAVOR and http", "\"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", } } } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList,", "= [{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations'] = configurations", "\"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" }", "None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList = [] components =", "err: pass actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"]", "= { \"containers\" : 5, \"ramPerContainer\": 256 } expected =", "@patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object): def read(self):", "enabled, HDP-2.3 configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\":", "LDAP values services[\"ambari-server-properties\"] = { \"ambari.ldap.isConfigured\" : \"true\", \"authentication.ldap.bindAnonymously\" :", "= { 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080' } },", "1, \"host_name\" : \"host1\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\",", "\"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\" ] }, \"dependencies\":[ {", "== None) # non-local FS, WASB properties = {\"property1\": \"wasb://h1\"}", "\"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive Server\", \"is_client\": \"false\", \"is_master\": \"true\",", "{ \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } }", "'host-group-2', 'components': [{ 'name': 'DATANODE' }] }] }, 'blueprint_cluster_binding': {", "hostInfo, reqiuredDiskSpace) == None) # non-local FS, WASB properties =", "res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertTrue(res) #Value is", "properties = {\"property1\": \"value1\"} recommendedDefaults = {} expected = {'level':", "hosts) expected = [] self.assertEquals(res, expected) # dfs.dir & hbase.rootdir", "Licensed to the Apache Software Foundation (ASF) under one or", "}, \"hive-env\": { \"properties\": { \"webhcat_user\": \"webhcat\", \"hive_user\": \"hive\" }", "is already used by datanode to store HDFS data', 'type':", "with AMS configurations = {} services = { \"services\": [", "\"\"\" def __exit__(self, exc_type, exc_val, exc_tb): pass def __enter__(self): return", "with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"6\", \"type\"", "\"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\", \"category\": \"SLAVE\", \"is_master\":", "configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"] = { 'properties':", "self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties = {\"property1\": \"value1\"}", "} expected = { 'hbase-site': { 'properties': { 'hbase.superuser': 'hbase123'", "in serviceInfo[\"components\"]: nextComponent = { \"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\":", "\"OOZIE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/OOZIE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\",", "= { \"storm-site\": { \"properties\": { } }, } self.stackAdvisor.recommendStormConfigurations(configurations,", "\"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) def", "{\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) def test_round_to_n(self):", "partition for storing metrics temporary data. ' '/ partition is", "self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\",", "[ { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": [] },", "{ \"StackServices\": { \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" }, \"components\": [", "{} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP", "{'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups': '*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*',", "self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [ {'config-name': 'hbase.rootdir',", "'It is not recommended to use root partition for property1',", "as fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE))", "} self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations, expected) def test_getConfigurationClusterSummary_noHostsWithoutHBase(self): servicesList", "component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"hostnames\"]", "{ 'name': 'host-group-2', 'components': [{ 'name': 'DATANODE' }] }] },", "fp: self.stack_advisor_impl = imp.load_module('stack_advisor_impl', fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz", "enabled, HDP-2.2\") # Test Recommend LDAP values services[\"ambari-server-properties\"] = {", "< recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize'] = '255' res_expected =", "the License. ''' import socket from unittest import TestCase from", "default of 1024', 'type': 'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name':", "\"os_type\" : \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host1\", \"rack_info\"", ": { \"cpu_count\" : 6, \"total_mem\" : 50331648, \"disk_info\" :", "[\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [", "set for yarn.nodemanager.linux-container-executor.group', 'level': 'ERROR'}, {\"message\": \"Value should be integer\",", "1, \"public_host_name\" : \"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 1048576", "fp: stack_advisor = imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)", "Apache Software Foundation (ASF) under one or more contributor license", "256 expected[\"reduceMemory\"] = 170.66666666666666 expected[\"ram\"] = 0 expected[\"ramPerContainer\"] = 170.66666666666666", "\"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\": False,", "11, \"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\":", "clusterData = { \"mapMemory\": 567, \"reduceMemory\": 345.6666666666666, \"amMemory\": 123.54 }", "\"mapreduce.task.io.sort.mb\": \"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None) self.assertEquals(configurations,", "self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]),", "[ { \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\", \"hostnames\": [\"host1\"] } },", "{ 'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties': { 'properties': { 'XAAUDIT.HDFS.IS_ENABLED':", "2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\",", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\" },", "None) self.assertEquals(recommendedConfigurations, expected, \"Test Recommend LDAP values\") # Test Ranger", "\"3+\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] }", "HDFS.', 'type': 'configuration' }, { 'config-name': 'hbase.cluster.distributed', 'config-type': 'ams-hbase-site', 'level':", "False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\",", "{ \"available\" : \"1048578\", \"type\" : \"ext4\", \"mountpoint\" : \"/\"", ": \"ext4\", \"mountpoint\" : \"/grid/0\" }, { \"available\" : str(15<<30),", "\"1+\", \"component_category\" : \"SLAVE\", \"component_name\" : \"DATANODE\", \"hostnames\" : [", "hostInfo[\"disk_info\"].append( { \"available\" : \"7\", \"type\" : \"ext4\", \"mountpoint\" :", "3072, \"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\": 3072, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] }", "space available hostInfo[\"disk_info\"].append( { \"available\" : \"1\", \"type\" : \"ext4\",", "}, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ],", "{ 'message': 'Value is less than the recommended minimum of", "\"category\": \"SLAVE\", \"is_master\": False}] } ] services = self.prepareServices(servicesInfo) hosts", "\"component_name\":\"DATANODE\", \"custom_commands\":[ ], \"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[", "cardinality ALL even if the component has been installed in", "installed) as part of recommendation received during Add service operation.", "\"is_master\": True, \"hostnames\": [\"host1\"]} ] } ] services = self.prepareServices(servicesInfo)", "services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations = [{\"type\":\"hadoop-env\",", "{ 'host_groups': [{ 'name': 'host-group-1', 'components': [] }, { 'name':", "{ \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\", \"component_category\":\"SLAVE\", \"component_name\":\"NODEMANAGER\", \"custom_commands\":[ ], \"display_name\":\"NodeManager\", \"is_client\":\"false\",", "'level': 'WARN', 'message': 'Value is less than the recommended default", "} } ] } ], \"configurations\": { \"admin-properties\": { \"properties\":", "[ { \"StackServices\": { \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" }, \"components\":", "Test - Cluster data with 1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList,", "200 UID_MIN 500 \"\"\" def __exit__(self, exc_type, exc_val, exc_tb): pass", "https enabled, HDP-2.3\") # Recommend for DB_FLAVOR ORACLE and https", "hostInfo[\"disk_info\"].append( { \"available\" : \"6\", \"type\" : \"ext4\", \"mountpoint\" :", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\", \"host2\"]} ] } ] services", "below: { 'blueprint': { 'host_groups': [{ 'name': 'host-group-1', 'components': []", "{'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user': 'falcon'}},", "and http enabled, HDP-2.3\") # Recommend for DB_FLAVOR POSTGRES and", "{ \"Hosts\" : { \"cpu_count\" : 6, \"total_mem\" : 50331648,", "stack_advisor = imp.load_source('stack_advisor', hdp206StackAdvisorPath) services = { \"services\": [ {", "= { \"hBaseInstalled\": True, \"components\": components, \"cpu\": 8, \"disk\": 8,", "/ is 1G\" # local FS, enough space hostInfo =", "{'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' : '256'} properties =", "for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {\"property1\": \"value1\"}", "expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"]", "False, \"components\": components, \"cpu\": 0, \"disk\": 0, \"ram\": 0, \"reservedRam\":", "} ] }, ], \"configurations\": { \"admin-properties\": { \"properties\": {", "None) self.assertEquals(result, expected) # Test - Cluster data with 2", "if host not in actualComponentHostsMap[componentName]: actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys():", "'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = {", "1 partition, no enough disk space host['Hosts']['disk_info'] = [ {", "components, None) expected = { \"hBaseInstalled\": False, \"components\": components, \"cpu\":", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space available hostInfo[\"disk_info\"].append(", "] } } hosts = { \"items\" : [ host", "\"available\" : \"7\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/1\" }", "= self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [ {'config-name':", "= 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as fp: stack_advisor = imp.load_module(", "# Verify dfs.namenode.rpc-address is recommended to be deleted when NN", "{'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize':", "{ 'message': 'Value is greater than the recommended maximum of", "= { \"items\" : [ { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\"", "self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo = {\"disk_info\": [", "= 4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] =", "def test_getHostsWithComponent(self): services = {\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\"", "WASB properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) ==", "installed services, recommendation for installed components should match the existing", "is recommended to set value value2 for property property1', 'level':", "Cluster data with 1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components,", ": \"/\" } ]} properties = {\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1',", "\"containers\": 11, \"ramPerContainer\": 3072, \"mapMemory\": 3072, \"reduceMemory\": 3072, \"amMemory\": 3072,", "{\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}", "\"reservedRam\": 6, \"hbaseRam\": 8, \"minContainerSize\": 2048, \"totalAvailableRam\": 34816, \"containers\": 11,", "actualComponentHostsMap[componentName].append(host) for componentName in componentsHostsMap.keys(): expectedHosts = componentsHostsMap[componentName] actualHosts =", "recommendedDefaults = {\"property1\": \"file:///grid/0/var/dir\"} warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo)", "space requirements not met. ' '\\nRecommended disk space for partition", "= [] for item in result[\"items\"]: next = {\"message\": item[\"message\"],", "{'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults,", "@patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object): def read(self): return", "\"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive Server\", \"is_client\":", "= {} components = [] host_item = { \"Hosts\" :", "hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff = None # substitute method", "\"MASTER\", \"is_master\": True}] } ] services = self.prepareServices(servicesInfo) localhost =", "\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ {", "= { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"http://host1:7777\" } }", "HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] = configurations", "def test_validateHDFSConfigurationsEnv(self): configurations = {} # 1) ok: namenode_heapsize >", "\"/grid/0\" }, { \"available\" : str(15<<30), # 15 GB \"type\"", "already used as hbase.rootdir to store metrics data', 'type': 'configuration'", "\"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\":", "{\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\":", "specific language governing permissions and limitations under the License. '''", ": [host_item for i in range(1, 300)] } services =", "'*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts': '*', 'hadoop.proxyuser.webhcat.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.hosts': '*', 'hadoop.proxyuser.webhcat.groups':", "\"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" } ]} warn", "more space available hostInfo[\"disk_info\"].append( { \"available\" : \"3\", \"type\" :", "self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "= { \"hBaseInstalled\": False, \"components\": components, \"cpu\": 0, \"disk\": 0,", "not sorted(l1) == sorted(l2): raise AssertionError(\"list1={0}, list2={1}\".format(l1, l2)) def assertValidationResult(self,", "expected[\"ramPerContainer\"] = 170.66666666666666 expected[\"reservedRam\"] = 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts,", "\"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/WEBHCAT_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\":", "\"HDFS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\":", "\"components\" : [ { \"StackServiceComponents\" : { \"cardinality\" : \"1+\",", "configurations } expected = { \"storm-site\": { \"properties\": { \"metrics.reporter.register\":", "} ] }, { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\":", "\"dependencies\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE/dependencies/HDFS_CLIENT\", \"Dependencies\":{ \"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" }", "'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env': {'properties':", "} } } recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties", "for DB_FLAVOR POSTGRES and https enabled, HDP-2.3\") # Recommend for", "{ \"DB_FLAVOR\": \"NOT_EXISTING\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\":", "configurations expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:7777\"", "= socket.getfqdn() expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties':", "warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected =", "\"StackServiceComponents\": { \"component_name\": \"RANGER_ADMIN\", \"hostnames\": [\"host1\"] } } ] },", "to in writing, software distributed under the License is distributed", "{ 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties =", "expected) # 2 partitions host['Hosts']['disk_info'] = [ { \"available\": str(15<<30),", "in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo", "using / partition for storing metrics temporary data. ' '/", "{ \"metrics.reporter.register\": \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None)", "self.assertTrue(warn != None) self.assertEquals({'message': 'It is not recommended to use", "True, \"hostnames\": [\"host1\"]}] } ] services = self.prepareServices(servicesInfo) hosts =", "self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [ { 'config-name':", "'hbase.tmp.dir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using /", "servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_SERVER\", \"cardinality\":", "res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services, hosts) expected = [", "set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {\"property1\":", "} services['configurations'] = configurations expected = { \"admin-properties\": { \"properties\":", "MagicMock class TestHDP206StackAdvisor(TestCase): def setUp(self): import imp import os testDirectory", "\"/default-rack\", \"total_mem\" : 2097152, \"disk_info\": [ { \"available\": str(15<<30), #", "\"host2\" ] }, \"dependencies\":[ ] }, ], }], \"configurations\": {}", "\"0.8\", \"no_min_or_max_attribute_property\": \"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value':", "\"core-site\": { \"properties\": { \"fs.defaultFS\": \"hdfs://host1:8080\", } }, \"ranger-env\": {", "configurations = { \"hadoop-env\": { \"properties\": { \"hdfs_user\": \"hdfs\", \"proxyuser_group\":", "None) expected = [ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level': 'WARN',", "parentValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\":", "def test_recommendationIsNotPreferableOnAmbariServer(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [{\"name\":", "\"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\", \"yarn.scheduler.maximum-allocation-mb\": \"1280\"", "self.assertEquals(res, expected) # 2 partitions host['Hosts']['disk_info'] = [ { \"available\":", "expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:8888\" }", "{ \"StackServices\": { \"service_name\": \"SERVICE\" }, \"components\": [ { \"StackServiceComponents\":", "{ 'dfs.namenode.rpc-address': { 'delete': 'true' } } } self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData,", "\"items\" : [ { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : {", "\"YARN\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\",", "warn = self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn != None) self.assertEquals({'message':", "\"StackServices\": { \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" }, \"components\": [ {", "{\"tez-site\": \"validateTezConfigurations2.2\"} } expected = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\":", "} # Test - Cluster data with 1 host result", "hostInfo[\"disk_info\"].append( { \"available\" : \"2\", \"type\" : \"tmpfs\", \"mountpoint\" :", "the component has been installed in the cluster before \"\"\"", "= {} # 1) ok: namenode_heapsize > recommended recommendedDefaults =", "{ \"available\" : \"3\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/boot/grub\"", "with this work for additional information regarding copyright ownership. The", "\"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" } }, \"core-site\": { \"properties\": {", "servicesList = [\"HBASE\"] configurations = {} components = [] host_item", "hosts, components, None) self.assertEquals(result, expected) # Test - Cluster data", "\"Hosts\": { \"cpu_count\" : 4, \"total_mem\" : 500000, \"host_name\" :", "{ \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\":", "\"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6402.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\":", "= self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result) def test_validationMinMax(self): configurations = {", "'') self.assertEquals(res, res_expected) # 2) fail: namenode_heapsize, namenode_opt_maxnewsize < recommended", "expected) # 1 partition, no enough disk space host['Hosts']['disk_info'] =", "{\"configurations\": configurations, \"services\": []} clusterData = { \"containers\" : 5,", "for the specific language governing permissions and limitations under the", "enough space hostInfo = {\"disk_info\": [ { \"available\" : \"1048578\",", ": \"centos6\", \"ph_cpu_count\" : 1, \"public_host_name\" : \"host1\", \"rack_info\" :", "{\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"},", "\"type\" : \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"] components = [] hosts = {", "= { \"mapred-site\": { \"properties\": { 'mapreduce.job.queuename': 'default', \"yarn.app.mapreduce.am.resource.mb\": \"123\",", "result[\"items\"]: next = {\"message\": item[\"message\"], \"level\": item[\"level\"]} try: next[\"host\"] =", "reqiuredDiskSpace) self.assertTrue(warn != None) self.assertEquals({'message': errorMsg, 'level': 'WARN'}, warn) #", "{\"mountpoint\" : \"/\"}, {\"mountpoint\" : \"/dev/shm\"}, {\"mountpoint\" : \"/\"}, {\"mountpoint\"", "available hostInfo[\"disk_info\"].append( { \"available\" : \"4\", \"type\" : \"tmpfs\", \"mountpoint\"", "self.stackAdvisor.getHostWithComponent(\"HDFS\", \"DATANODE\", services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\",", "0) self.assertEquals(self.stack_advisor_impl.round_to_n(1000), 1024) self.assertEquals(self.stack_advisor_impl.round_to_n(2000), 2048) self.assertEquals(self.stack_advisor_impl.round_to_n(4097), 4096) def test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\",", "] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo = [ { \"name\":", "\"Test for DB_FLAVOR POSTGRES and https enabled, HDP-2.3\") # Recommend", "'*', 'hadoop.proxyuser.ambari_user.hosts': ambariHostName, 'hadoop.proxyuser.oozie.groups': '*', 'hadoop.proxyuser.hive.groups': '*', 'hadoop.proxyuser.hdfs1.groups': '*', 'hadoop.proxyuser.hdfs1.hosts':", "= self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) def test_mergeValidators(self): childValidators", "Test - Cluster data with 2 hosts - pick minimum", "= '255' res_expected = [{'config-type': 'hadoop-env', 'message': 'Value is less", "\"no_min_or_max_attribute_property\": \"STRING_VALUE\" } } } recommendedDefaults = { \"mapred-site\": {", "services = { \"services\": [ { \"StackServices\": { \"service_name\": \"SERVICE\"", "{\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"newconf\": \"new2.3\"}, \"NEWSERVICE\" : {\"newserviceconf\":", "'../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath, 'rb') as fp: stack_advisor", "{\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\", \"category\": \"SLAVE\", \"is_master\":", "try: next[\"host\"] = item[\"host\"] except KeyError, err: pass actualItems.append(next) self.checkEqual(expectedItems,", "\"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\", \"category\":", "configurations expected = { \"admin-properties\": { \"properties\": { \"policymgr_external_url\": \"https://host1:8888\"", "\"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] }, \"dependencies\":[", "{\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # non-local", ": \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None)", "configurations, \"services\": []} clusterData = { \"containers\" : 5, \"ramPerContainer\":", "def test_getHostNamesWithComponent(self): services = { \"services\": [ { \"StackServices\": {", "Metrics disk space requirements not met. ' '\\nRecommended disk space", "'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users',", "}], \"configurations\": {} } hosts = { \"items\" : [", "\"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\" } }, \"ranger-hdfs-plugin-properties\": { \"properties\": {} } } expected", "partition for storing metrics data. ' '/ is already used", "'/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env':", "[\"/var\", \"/\"]), None) self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"relative/path\", [\"/var\", \"/\"]), None) def test_getValidatorEqualsToRecommendedItem(self): properties", "{ \"services\" : [ { \"StackServices\" : { \"service_name\" :", "\"items\" : [] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None)", "storing metrics temporary data. ' '/ partition is already used", "integer\", \"level\": \"ERROR\"}, {\"message\": \"Value should be set\", \"level\": \"ERROR\"}", "\"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\",", "} }, \"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\", \"xasecure.audit.destination.hdfs.dir\":\"hdfs://localhost:8020/ranger/audit/%app-type%/%time:yyyyMMdd%\"", "item in result[\"items\"]: next = {\"message\": item[\"message\"], \"level\": item[\"level\"]} try:", "'mapred-site', 'config-name': 'some_float_value', 'type': 'configuration' } ] self.assertEquals(expectedItems, items) def", "recommendation[\"recommendations\"][\"blueprint_cluster_binding\"][\"host_groups\"] actualComponentHostsMap = {} for hostGroup in blueprintMapping: hostGroupName =", "{ \"service_name\": \"RANGER\", \"service_version\": \"0.5.0\" }, \"components\": [ { \"StackServiceComponents\":", "recommended to be deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\"", "\"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationWarnMessagesIfLessThanDefault(self): servicesInfo = [ {", "\"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\", \"category\":", "256, \"totalAvailableRam\": 512, \"containers\": 3, \"ramPerContainer\": 170.66666666666666, \"mapMemory\": 170, \"reduceMemory\":", "self.stackAdvisor.validateConfigurations(services, hosts) expectedItems = [ {\"message\": \"Value is less than", "= [] self.assertEquals(res, expected) properties['metrics.reporter.register'] = '' res = self.stackAdvisor.validateStormConfigurations(properties,", "{\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\", \"service_version\" : \"2.6.0.2.2\" }, \"components\":[", "point to HDFS.', 'type': 'configuration' }, { 'config-name': 'hbase.cluster.distributed', 'config-type':", "= self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Between 0 and", "] } }) expected[\"referenceHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"referenceNodeManagerHost\"] = hosts[\"items\"][1][\"Hosts\"] expected[\"amMemory\"]", "'level': 'WARN', 'message': 'It is not recommended to use root", "self.stackAdvisor.getHostNamesWithComponent(\"SERVICE\",\"COMPONENT\", services) expected = [\"host1\",\"host2\",\"host3\"] self.assertEquals(result, expected) def test_getZKHostPortString(self): configurations", "= {'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts)", "} parentValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\":", "self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace =", "\"configurations\": {} } hosts[\"items\"][0][\"Hosts\"][\"host_name\"] = \"host1\" hosts[\"items\"].append({ \"Hosts\": { \"cpu_count\"", "= { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties", "expected = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\":", "least 3 Ganglia Server components should be installed in cluster.\",", "to use root partition for property1', 'level': 'WARN'}, warn) #", "\"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } } } }", "1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152, \"disk_info\": [{ \"size\":", "https enabled, HDP-2.3 configurations = { \"admin-properties\": { \"properties\": {", "= { \"services\": [ ], \"configurations\": configurations } expected =", "\"properties\": { \"policymgr_external_url\": \"http://host1:7777\" } } } recommendedConfigurations = {}", "= self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None) # unknown service", "{'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved':", "expected = { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties =", "unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None)", "\"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", } }", "\"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected = {", "is not used\", \"host\": \"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result)", "Cluster data with 2 hosts - pick minimum memory servicesList.append(\"YARN\")", "test_getMountPointForDir(self): self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\",", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo = [", "tmpfs with more space available hostInfo[\"disk_info\"].append( { \"available\" : \"2\",", "servicesInfo: nextService = {\"StackServices\":{\"service_name\" : serviceInfo[\"name\"]}} nextService[\"components\"] = [] for", "+ hbase.rootdir == hbase.tmp.dir warnings properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase',", "'1024'} properties = {'dfs.datanode.du.reserved': '2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations,", "[\"/\"]), \"/\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"/var/log\", [\"/var\", \"/\"]), \"/var\") self.assertEquals(self.stack_advisor_impl.getMountPointForDir(\"file:///var/log\", [\"/var\", \"/\"]), \"/var\")", "'' res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected =", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"ALL\",", "be deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices'] = \"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] =", "recommendedDefaults, configurations, services, hosts) expected = [ { 'config-name': 'hbase.rootdir',", "reqiuredDiskSpace) == None) # non-local FS, WASB properties = {\"property1\":", "'/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services,", "\"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] } }", "{ 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'In distributed", "[{\"type\":\"hadoop-env\", \"name\":\"hdfs_user\", \"old_value\":\"hdfs\"}] services[\"changed-configurations\"] = changedConfigurations services['configurations'] = configurations expected", ": hostName}} hosts[\"items\"].append(nextHost) return hosts def prepareServices(self, servicesInfo): services =", "}, \"ranger-admin-site\": { \"properties\": { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", }", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"1+\",", "hosts - pick minimum memory servicesList.append(\"YARN\") services = services =", "= 1 result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, services) self.assertEquals(result, expected)", "[ {\"message\": \"At least 3 Ganglia Server components should be", "\"containers\" : 5, \"ramPerContainer\": 256 } expected = { \"yarn-env\":", "'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user': 'webhcat'}}, 'hadoop-env': {'properties':", "{'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'} } } } items =", "\"name\": \"HDFS\", \"components\": [ {\"name\": \"NAMENODE\", \"cardinality\": \"1-2\", \"category\": \"MASTER\",", "'Consider not using / partition for storing metrics temporary data.", "already used by datanode to store HDFS data', 'type': 'configuration'", "# Assert that the list is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components'])", "metrics data. ' '/ is already used by datanode to", "self.assertEquals(configurations, expected) # with AMS configurations = {} services =", "expected = {'message': 'It is recommended to set value value2", "component[\"category\"], \"is_master\": component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] = component[\"hostnames\"] except", "actualItems.append(next) self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations =", "\"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\",", "HDFS properties = {\"property1\": \"hdfs://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) ==", "for property1', 'level': 'WARN'}, warn) # Set by user /var", "\"memberUid\", \"authentication.ldap.groupObjectClass\" : \"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] =", "'ERROR', 'message': 'hbase.cluster.distributed property should be set to true for", "\"component_name\":\"JOURNALNODE\", \"custom_commands\":[ ], \"display_name\":\"JournalNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[", "], \"configurations\": { \"hbase-site\": { \"properties\": { \"hbase.superuser\": \"hbase\" }", "components, services) self.assertEquals(result, expected) def test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components", "Assert that the list is empty for host-group-1 self.assertFalse(recommendations['blueprint']['host_groups'][0]['components']) #", "= { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir' : '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' }", "not using / partition for storing metrics data. ' '/", "= { \"items\" : [host_item for i in range(1, 300)]", "\"Versions\" : { \"stack_version\" : \"2.3\", }, \"services\": [ {", "'hadoop.proxyuser.webhcat.groups': '*', 'hadoop.proxyuser.hdfs.groups': '*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org',", "hostInfo[\"disk_info\"].append( { \"available\" : \"4\", \"type\" : \"tmpfs\", \"mountpoint\" :", "', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name': 'mapreduce.task.io.sort.mb', 'type': 'configuration' },", "{ \"name\": \"YARN\", \"components\": [] } ] services = self.prepareServices(servicesInfo)", "{ \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] }", "\"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {} expected = { 'admin-properties': {", "= self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) def test_validateHDFSConfigurationsEnv(self): configurations", "component[\"name\"] try: actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName] = [] for", "{ 'admin-properties': { 'properties': { 'policymgr_external_url': 'http://host1:6080' } }, 'ranger-hdfs-plugin-properties':", "'2048'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations, services, hosts) self.assertFalse(res) def", "ALL even if the component has been installed in the", "configurations = { \"hdfs-site\": { \"properties\": { 'dfs.datanode.data.dir': \"/hadoop/data\" }", "'/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } properties = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir'", "self.assertEquals(res, expected) # dfs.dir & hbase.rootdir crosscheck + root partition", "\"display_name\":\"DataNode\", \"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ]", "[\"host1\", \"host2\"]} ] } ] services = self.prepareServices(servicesInfo) hosts =", "\"posixGroup\", \"authentication.ldap.managerDn\" : \"uid=hdfs,ou=people,ou=dev,dc=apache,dc=org\" } services[\"configurations\"] = {} expected =", "\"YARN\", \"components\": [] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"] =", "the recommended default of 512\", \"level\": \"WARN\"}, {'message': 'Value should", "\"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\": \"Oozie Server\",", "\"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\":", "= clazz() self.maxDiff = None # substitute method in the", "'255' res_expected = [{'config-type': 'hadoop-env', 'message': 'Value is less than", "Test Ranger Audit properties del services[\"ambari-server-properties\"] services[\"configurations\"] = { \"core-site\":", "} recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services,", "\"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } # Test -", "contributor license agreements. See the NOTICE file distributed with this", "hosts) expectedItems = [ {\"message\": \"At least 3 Ganglia Server", "\"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space", "License for the specific language governing permissions and limitations under", "expected[\"amMemory\"] = 170.66666666666666 expected[\"containers\"] = 3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"]", "None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations = {} services =", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with more space available hostInfo[\"disk_info\"].append( {", "\"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\": configurations", "already installed slaves are not added to any free hosts", "= { \"services\" : [ { \"StackServices\" : { \"service_name\"", "] self.assertEquals(res, expected) # 2 partitions host['Hosts']['disk_info'] = [ {", "}, \"ranger-env\": {\"properties\": {}} } recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] =", "\"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected", "\"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for DB_FLAVOR", "\"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\"", "\"Ganglia Monitor component should be installed on all hosts in", "\"storm-site\": { \"properties\": { } }, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services,", "1048576, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] } },", "= \"Ambari Metrics disk space requirements not met. \\n\" \\", "True, \"hostnames\": [\"host2\", \"host1\"]} ] } ] services = self.prepareServices(servicesInfo)", "host['Hosts']['disk_info'] = [ { \"available\" : '1', \"type\" : \"ext4\",", "host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected) #", "\"cardinality\": \"3+\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ]", "\"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] } ]", "all hosts in cluster.\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def", "DB_FLAVOR ORACLE and https enabled, HDP-2.2 configurations = { \"admin-properties\":", "\"STRING_VALUE\" }, \"property_attributes\": { 'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'}", "\"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat Server\", \"is_client\": \"false\", \"is_master\":", "\"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\": {\"properties\": {}} } recommendedConfigurations =", "\"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [], \"display_name\":", "def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations = {} components =", "\"2183\" } } } services = { \"services\": [ {", "recommended maximum of 2047 ', 'level': 'WARN', 'config-type': 'mapred-site', 'config-name':", "\"yarn-site\": { \"properties\": { \"yarn.nodemanager.linux-container-executor.group\": \"hadoop\", \"yarn.nodemanager.resource.memory-mb\": \"1280\", \"yarn.scheduler.minimum-allocation-mb\": \"256\",", "'type': 'configuration' } ] self.assertEquals(res, expected) def test_getHostsWithComponent(self): services =", "Recommend LDAP values\") # Test Ranger Audit properties del services[\"ambari-server-properties\"]", "\"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [],", "\"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.2\", \"hive-site\": \"validateHiveConfigurations2.2\",", "\"-Xmx277m\", \"mapreduce.task.io.sort.mb\": \"227\" } } } self.stackAdvisor.recommendMapReduce2Configurations(configurations, clusterData, None, None)", "\"HIVE\" }, \"components\": [{ \"href\": \"/api/v1/stacks/HDP/versions/2.0.6/services/HIVE/components/HIVE_SERVER\", \"StackServiceComponents\": { \"advertise_version\": \"true\",", "\"fs.defaultFS\": \"hdfs://c6401.ambari.apache.org:8020\" } }, \"ams-site\": { \"properties\": { \"timeline.metrics.service.operation.mode\": \"embedded\"", "test_recommendStormConfigurations(self): # no AMS configurations = {} services = {", "{ \"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\": \"8192\", } } }", "'configuration' } ] self.assertEquals(res, expected) # incorrect hbase.rootdir in distributed", ": \"DATANODE\", \"hostnames\" : [ \"c6401.ambari.apache.org\" ] } } ]", "all hosts for cardinality ALL even if the component has", "'8', \"mountpoint\": \"/\" }] } }, ]} services = {", "recommended to set value value2 for property property1', 'level': 'WARN'}", "'hadoop-env', 'level': 'WARN', 'message': 'Value is less than the recommended", "\"ndfqueue\" expectedItems = [] result = self.stackAdvisor.validateConfigurations(services, hosts) self.assertValidationResult(expectedItems, result)", "instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def", "= { \"StackServiceComponents\": { \"component_name\": component[\"name\"], \"cardinality\": component[\"cardinality\"], \"component_category\": component[\"category\"],", "partition, enough disk space, no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults,", "- Cluster data with 1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts,", "test_getConfigurationClusterSummary_withHBaseAnd48gbRam(self): servicesList = [\"HBASE\"] components = [] hosts = {", "self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for not existing", ": \"ext4\", \"mountpoint\" : \"/\" } ] recommendedDefaults = {", "# More preferable /grid/0 mountpoint - warning hostInfo[\"disk_info\"].append( { \"available\"", "\"ranger-admin-site\") self.assertEquals(siteProperties, expected) def test_createComponentLayoutRecommendations_addService_1freeHost(self): \"\"\" Test that already installed", "} clusterData = { \"totalAvailableRam\": 2048 } ambariHostName = socket.getfqdn()", "- Cluster data with 2 hosts - pick minimum memory", "def test_recommendOnAllHosts(self): \"\"\" Recommend on all hosts for cardinality ALL", "{ 'properties': { 'XAAUDIT.HDFS.IS_ENABLED': 'false', 'XAAUDIT.HDFS.DESTINATION_DIRECTORY': 'hdfs://host1:8080/ranger/audit/%app-type%/%time:yyyyMMdd%', 'XAAUDIT.DB.IS_ENABLED': 'true' }", "'name': 'host-group-1' }, { 'hosts': [{ 'fqdn': 'c6401.ambari.apache.org' }], 'name':", "= [\"HBASE\"] components = [] hosts = { \"items\" :", "= { \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo", "\"services\": [ { \"StackServices\": { \"service_name\": \"HDFS\" }, \"components\": []", "\"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"} } clusterData = { \"totalAvailableRam\": 2048", "properties = {\"property1\": \"wasb://h1\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None)", "recommendedDefaults = { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } properties = { 'metrics.reporter.register':", "{ \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo =", "\"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\": \"/default-rack\", \"total_mem\": 2097152,", "= None self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo = {\"some_key\": []} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo))", "}, } self.stackAdvisor.recommendStormConfigurations(configurations, None, services, None) self.assertEquals(configurations, expected) # with", "self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root mountpoint", "''' import socket from unittest import TestCase from mock.mock import", "]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn != None)", "property1', 'level': 'WARN'}, warn) # Set by user /var mountpoint,", "\"is_master\":\"true\", \"service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] }, \"dependencies\":[ ]", "FS, enough space hostInfo = {\"disk_info\": [ { \"available\" :", "\"mycluster\" configurations[\"hdfs-site\"][\"properties\"]['dfs.ha.namenodes.mycluster'] = \"nn1,nn2\" services['configurations'] = configurations expected[\"hdfs-site\"] = {", "\"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\":", "\"Host is not used\", \"host\": \"host2\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems,", "\"public_host_name\" : \"host2\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 1048576 }", "= self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap,", "free hosts (not having any component installed) as part of", "} ) self.assertEquals([\"/grid/1\", \"/grid/0\", \"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) def test_validateNonRootFs(self): hostInfo =", "\"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"},", "servicesInfo = [ { \"name\": \"HDFS\", \"components\": [ {\"name\": \"NAMENODE\",", "= [ { \"name\": \"GANGLIA\", \"components\": [{\"name\": \"GANGLIA_MONITOR\", \"cardinality\": \"ALL\",", "\"hostnames\": [\"c6401.ambari.apache.org\", \"c6402.ambari.apache.org\"] }, }] }], \"configurations\": configurations, \"ambari-server-properties\": {\"ambari-server.user\":\"ambari_user\"}", "'1024'} properties = {'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults, configurations,", "] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/JOURNALNODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"0+\", \"component_category\":\"SLAVE\", \"component_name\":\"JOURNALNODE\", \"custom_commands\":[", "partition / is 10G', 'type': 'configuration' } ] self.assertEquals(res, expected)", "{\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\": \"validateHiveServer2Configurations2.3\",", "\"https.service.port\": \"8888\", } } } services['configurations'] = configurations expected =", ": \"ext4\", \"mountpoint\" : \"/\" } ] res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties,", "'level': 'WARN', 'message': 'Consider not using / partition for storing", ": \"dc=apache,dc=org\", \"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" :", "{ 'properties': { 'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024', 'dfs.internal.nameservices': 'mycluster', 'dfs.ha.namenodes.mycluster':", "{'properties': {'hdfs_user': 'hdfs', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256', 'namenode_opt_newsize':", "= { \"services\": [ { \"StackServices\": { \"service_name\": \"AMBARI_METRICS\" },", "\"ext4\", \"mountpoint\": \"/\" } ] } } hosts = {", ": 8, \"total_mem\" : 6291456, \"disk_info\" : [ {\"mountpoint\" :", "\"available\" : \"1\", \"type\" : \"ext4\", \"mountpoint\" : \"/\" }", "'some_float_value', 'type': 'configuration' } ] self.assertEquals(expectedItems, items) def test_validationHostIsNotUsedForNonValuableComponent(self): servicesInfo", "} }, \"oozie-env\": { \"properties\": { \"oozie_user\": \"oozie\" } },", "/ mountpoint - no warning self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) ==", "ambariHostName = socket.getfqdn() expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site':", "'hbase.superuser': 'hbase123' } }, \"hbase-env\": { \"properties\": { \"hbase_master_heapsize\": \"4096\",", "\"is_client\":\"false\", \"is_master\":\"false\", \"service_name\":\"YARN\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\", \"hostnames\":[ \"host1\", \"host2\" ] },", "= {'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize' : '256'} properties", "\"total_mem\": 1048576, \"disk_info\": [{ \"size\": '8', \"mountpoint\": \"/\" }] }", "\"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\": 6,", "{}} } recommendedConfigurations = {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData,", "configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"ORACLE\", }", "'components': [{ 'name': 'DATANODE' }] }] }, 'blueprint_cluster_binding': { 'host_groups':", "hosts = self.prepareHosts([\"host1\", \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap =", "\"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"OOZIE_SERVER\", \"custom_commands\": [],", "self.checkEqual(expectedItems, actualItems) def test_recommendHbaseConfigurations(self): servicesList = [\"HBASE\"] configurations = {}", "dfs.namenode.rpc-address is recommended to be deleted when NN HA configurations[\"hdfs-site\"][\"properties\"]['dfs.internal.nameservices']", "space for partition / is 10G', 'type': 'configuration' } ]", "{\"message\": \"Between 0 and 1 Ganglia Server components should be", "result) services[\"configurations\"][\"yarn-env\"][\"properties\"][\"service_check.queue.name\"] = \"ndfqueue\" expectedItems = [] result = self.stackAdvisor.validateConfigurations(services,", "\"properties\": { \"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\": { \"properties\": {", "existing DB_FLAVOR and http enabled, HDP-2.3 services = { \"Versions\"", "'mycluster', 'dfs.ha.namenodes.mycluster': 'nn1,nn2' }, 'property_attributes': { 'dfs.namenode.rpc-address': { 'delete': 'true'", ": \"tmpfs\", \"mountpoint\" : \"/dev/shm\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "\"stack_version\":\"2.2\", \"hostnames\":[ \"host2\" ] }, \"dependencies\":[ ] }, ], }],", "space requirements not met. \\n\" \\ \"Recommended disk space for", "'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}}, 'falcon-env': {'properties': {'falcon_user':", "= self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) self.assertTrue(warn != None) self.assertEquals({'message': 'It", "{ 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = { \"services\": [ {", "\"host2\", \"os_arch\" : \"x86_64\", \"os_type\" : \"centos6\", \"ph_cpu_count\" : 1,", "{\"name\": \"SECONDARY_NAMENODE\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host1\"]}]", "} } } } expected = { \"admin-properties\": { \"properties\":", "'property1', hostInfo) == None) def test_validatorEnoughDiskSpace(self): reqiuredDiskSpace = 1048576 errorMsg", "limitations under the License. ''' import socket from unittest import", "{\"property1\": \"file:///var/dir\"} self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # local", "[] }, { \"StackServices\": { \"service_name\": \"FALCON\" }, \"components\": []", "\"StackServiceComponents\": { \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\",", "property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {}", "def test_recommendStormConfigurations(self): # no AMS configurations = {} services =", "'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts':", "configurations, services, hosts) self.assertTrue(res) #Value is begger then expected recommendedDefaults", "} } hosts = { \"items\": [ { \"href\": \"/api/v1/hosts/host1\",", "None, services, None) self.assertEquals(configurations, expected) def test_recommendYARNConfigurations(self): configurations = {}", "value2 for property property1', 'level': 'WARN'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected)", "\"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators) self.assertEquals(expected, parentValidators)", "\"type\" : \"ext4\", \"mountpoint\" : \"/var\" } ) self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults,", "DB_FLAVOR POSTGRES and https enabled, HDP-2.3 configurations = { \"admin-properties\":", "= {} expected = { 'admin-properties': { 'properties': { 'policymgr_external_url':", "\"authentication.ldap.usernameAttribute\" : \"uid\", \"authentication.ldap.dnAttribute\" : \"dn\", \"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\"", "= { \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\",", "= { \"items\" : [] } result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts,", "\"authentication.ldap.useSSL\" : \"true\", \"authentication.ldap.managerPassword\" : \"/etc/ambari-server/conf/ldap-password.dat\", \"authentication.ldap.groupMembershipAttr\" : \"memberUid\", \"authentication.ldap.groupObjectClass\"", "{\"property1\": \"value2\"} expected = {'message': 'It is recommended to set", "use root partition for hbase.rootdir', 'type': 'configuration' }, { 'config-name':", "\"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"}, \"NEWSERVICE\" : {\"newserviceconf\": \"abc2.3\"} } self.stackAdvisor.mergeValidators(parentValidators, childValidators)", "stack_advisor = imp.load_module( 'stack_advisor', fp, stackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE) )", "\"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"]", "} } } recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase',", "class TestHDP206StackAdvisor(TestCase): def setUp(self): import imp import os testDirectory =", "[\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_recommendOnAllHosts(self): \"\"\" Recommend on", "\"configurations\": { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"NOT_EXISTING\", } },", "\"StackServiceComponents\": { \"component_name\": \"DATANODE\", \"hostnames\": [\"host1\"] } } ] }", "servicesList.append(\"YARN\") services = services = {\"services\": [{\"StackServices\": {\"service_name\" : \"YARN\",", "by applicable law or agreed to in writing, software distributed", "socket.getfqdn() expected = {'oozie-env': {'properties': {'oozie_user': 'oozie'}}, 'core-site': {'properties': {'hadoop.proxyuser.ambari_user.groups':", "= { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"},", "{ \"mapred-site\": { \"properties\": { \"mapreduce.task.io.sort.mb\": \"2047\", \"some_float_value\": \"0.8\", \"no_min_or_max_attribute_property\":", "\"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def test_getConfigurationClusterSummary_withHBaseAnd6gbRam(self): servicesList = [\"HBASE\"]", "'/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } host = { \"href\" : \"/api/v1/hosts/host1\",", "self.stackAdvisor.recommendComponentLayout(services, hosts) expectedComponentsHostsMap = { \"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result)", "\"validateMapReduce2Configurations2.2\"}, \"TEZ\": {\"tez-site\": \"validateTezConfigurations2.2\"} } expected = { \"HDFS\": {\"hdfs-site\":", "\"hostnames\": [\"host1\"] } } ] } ], \"configurations\": { \"admin-properties\":", "\"/api/v1/hosts/host2\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6402.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\":", "[] host_item = { \"Hosts\" : { \"cpu_count\" : 6,", "self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts) self.assertEquals(len(namenodes), 1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]])", "as part of recommendation received during Add service operation. For", "\"false\", } } } services['configurations'] = configurations expected = {", "\"service_name\": \"AMBARI_METRICS\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\": \"METRICS_COLLECTOR\",", "properties\") def test_recommendHDFSConfigurations(self): configurations = { \"hadoop-env\": { \"properties\": {", "test_validationCardinalityAtLeast(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\": [ {\"name\":", "15 GB \"type\": \"ext4\", \"mountpoint\": \"/\" } ] } }", "= self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock,", "'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}, 'property_attributes': {'hadoop.proxyuser.hdfs.groups': {'delete': 'true'}, 'hadoop.proxyuser.hdfs.hosts': {'delete': 'true'}}},", "] }, ], }], \"configurations\": {} } hosts = {", "self.assertTrue(self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) == None) # non-local FS, WASB", "nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) # unknown", "services, hosts) self.assertEquals(datanode, hosts[\"items\"][0]) namenodes = self.stackAdvisor.getHostsWithComponent(\"HDFS\", \"NAMENODE\", services, hosts)", "{\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\", \"newconf\": \"new2.3\"}, \"MAPREDUCE2\": {\"mapred-site\": \"validateMapReduce2Configurations2.2\"}, \"TEZ\":", "def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self): configurations = {} clusterData = { \"mapMemory\": 567,", "component[\"cardinality\"], \"component_category\": component[\"category\"], \"is_master\": component[\"is_master\"] } } try: nextComponent[\"StackServiceComponents\"][\"hostnames\"] =", "Monitor components should be installed in cluster.\", \"level\": \"ERROR\"} ]", "'../../../../../main/resources/stacks/stack_advisor.py') hdp206StackAdvisorPath = os.path.join(testDirectory, '../../../../../main/resources/stacks/HDP/2.0.6/services/stack_advisor.py') hdp206StackAdvisorClassName = 'HDP206StackAdvisor' with open(stackAdvisorPath,", "# substitute method in the instance self.get_system_min_uid_real = self.stackAdvisor.get_system_min_uid self.stackAdvisor.get_system_min_uid", "hosts) expectedComponentsHostsMap = { \"GANGLIA_MONITOR\": [\"host1\", \"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result)", "line UID_MIN 200 UID_MIN 500 \"\"\" def __exit__(self, exc_type, exc_val,", "is not recommended to use root partition for hbase.rootdir', 'type':", "} ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space", "\"public_host_name\" : \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152 }", "\"services\": [ { \"StackServices\": { \"service_name\": \"SERVICE\" }, \"components\": [", "\"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\":", "\"component_category\":\"MASTER\", \"component_name\":\"NAMENODE\", \"custom_commands\":[ \"DECOMMISSION\", \"REBALANCEHDFS\" ], \"display_name\":\"NameNode\", \"is_client\":\"false\", \"is_master\":\"true\", \"service_name\":\"HDFS\",", "{'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hive-env': {'properties': {'hive_user': 'hive', 'webhcat_user':", "\"type\": \"ext4\", \"mountpoint\": \"/\" } ] } } hosts =", "' '/ partition is already used as hbase.rootdir to store", "\"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\": [], \"display_name\": \"WebHCat Server\", \"is_client\": \"false\",", "expected = [] self.assertEquals(res, expected) # 1 partition, no enough", ": \"host2\", \"disk_info\" : [ {\"mountpoint\" : \"/\"}, {\"mountpoint\" :", "= { \"ranger.service.http.port\": \"7777\", \"ranger.service.http.enabled\": \"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services,", "installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) #", "hosts = '' #Default configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties", "'host-group-1', 'components': [] }, { 'name': 'host-group-2', 'components': [{ 'name':", "\"host2\"]) result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Host", "\"5\", \"type\" : \"vboxsf\", \"mountpoint\" : \"/vagrant\" } ) self.assertEquals([\"/\"],", "{\"message\": \"Host is not used\", \"host\": \"host2\", \"level\": \"ERROR\"} ]", "distributed mode hbase.rootdir should point to HDFS.', 'type': 'configuration' },", "{ \"min_user_id\": \"500\", 'service_check.queue.name': 'default' } }, \"yarn-site\": { \"properties\":", "'/ is already used by datanode to store HDFS data',", "{ \"policymgr_external_url\": \"https://host1:8888\" } }, \"ranger-env\": {\"properties\": {}} } recommendedConfigurations", "\"RANGER\", \"service_version\": \"0.5.0\" }, \"components\": [ { \"StackServiceComponents\": { \"component_name\":", "1) ok: namenode_heapsize > recommended recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize'", "positive res = self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected =", "self.stackAdvisor.validateStormConfigurations(properties, recommendedDefaults, configurations, services, None) expected = [] self.assertEquals(res, expected)", "= [ {\"message\": \"Host is not used\", \"level\": \"ERROR\", \"host\":", "{ \"properties\": { \"ranger.service.https.port\": \"7777\", \"ranger.service.http.enabled\": \"false\", } } }", "'ERROR', 'message': 'Value should be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults,", "\"validateHiveServer2Configurations2.3\", \"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.3\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\",", "\"services\": [ { \"StackServices\": { \"service_name\": \"RANGER\" }, \"components\": [", "[] components = [] hosts = { \"items\" : []", "self.assertTrue(self.stackAdvisor.validatorNotRootFs(properties, recommendedDefaults, 'property1', hostInfo) == None) # More preferable /grid/0", "{ \"href\": \"/api/v1/hosts/host1\", \"Hosts\": { \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\":", "{ \"service_name\": \"FALCON\" }, \"components\": [] }, { \"StackServices\": {", "part of recommendation received during Add service operation. For already", "= { 'metrics.reporter.register': 'org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter', } services = { \"services\": [", "expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '512'} res", ": \"/api/v1/hosts/host1\", \"Hosts\" : { \"cpu_count\" : 1, \"host_name\" :", "self.stackAdvisor.getPreferredMountPoints(hostInfo)) # tmpfs with more space available hostInfo[\"disk_info\"].append( { \"available\"", "{} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for not", "expected) def test_getServicesSiteProperties(self): import imp, os testDirectory = os.path.dirname(os.path.abspath(__file__)) hdp206StackAdvisorPath", "\"authentication.ldap.groupNamingAttr\" : \"cn\", \"authentication.ldap.primaryUrl\" : \"c6403.ambari.apache.org:636\", \"authentication.ldap.userObjectClass\" : \"posixAccount\", \"authentication.ldap.secondaryUrl\"", "\"/\" } ]} warn = self.stackAdvisor.validatorEnoughDiskSpace(properties, 'property1', hostInfo, reqiuredDiskSpace) self.assertTrue(warn", "'' #Default configuration recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved':", "'mapreduce.task.io.sort.mb': {'maximum': '2047'}, 'some_float_value': {'minimum': '0.8'} } } } items", "\"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\":", "serviceInfo[\"name\"]}} nextService[\"components\"] = [] for component in serviceInfo[\"components\"]: nextComponent =", "expected = [ { 'config-name': 'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN',", "\"GANGLIA_SERVER\": [\"host2\"] } self.assertHostLayout(expectedComponentsHostsMap, result) def test_validationNamenodeAndSecondaryNamenode2Hosts_noMessagesForSameHost(self): servicesInfo = [", "with the License. You may obtain a copy of the", "not used\", \"host\": \"host1\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems, result) def", "in range(1, 300)] } services = { \"services\" : [", "def test_recommendRangerConfigurations(self): clusterData = {} # Recommend for not existing", "1 partition, enough disk space, no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties,", "for DB_FLAVOR ORACLE and https enabled, HDP-2.2\") # Test Recommend", "} ] recommendedDefaults = { 'hbase.rootdir': 'file:///grid/0/var/lib/ambari-metrics-collector/hbase', 'hbase.tmp.dir': '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed':", "\"stack_version\":\"2.2\" } } ] }, { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/NAMENODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1-2\",", "{ \"hbase-site\": { \"properties\": { \"hbase.superuser\": \"hbase\" } }, \"hbase-env\":", "512 expected[\"mapMemory\"] = 170 expected[\"minContainerSize\"] = 256 expected[\"reduceMemory\"] = 170.66666666666666", "} } ], \"configurations\": configurations } expected = { \"storm-site\":", "unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services, hosts) self.assertEquals(nodemanager, None) # unknown", "\"hive-site\": \"validateHiveConfigurations2.2\", \"hive-env\": \"validateHiveConfigurationsEnv2.2\"}, \"HBASE\": {\"hbase-site\": \"validateHBASEConfigurations2.2\", \"hbase-env\": \"validateHBASEEnvConfigurations2.2\"}, \"MAPREDUCE2\":", "1 host result = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(result, expected)", "\"policymgr_external_url\": \"http://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData,", "[\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"1-2\", \"category\": \"MASTER\",", "\"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ] } ], \"configurations\":", "mountpoint with low space available hostInfo[\"disk_info\"].append( { \"available\" : \"1\",", ": '/var/lib/ambari-metrics-collector/hbase', 'hbase.cluster.distributed': 'false' } configurations['ams-site']['properties']['timeline.metrics.service.operation.mode'] = 'distributed' res =", "hostsInfos] for component in hostGroup[\"components\"]: componentName = component[\"name\"] try: actualComponentHostsMap[componentName]", "= self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Host is not", "for binding in bindings if binding[\"name\"] == hostGroupName][0] hosts =", "\"available\" : \"4\", \"type\" : \"tmpfs\", \"mountpoint\" : \"/mnt/external_hdd\" }", "'message': 'Value is less than the recommended default of 256',", "'8', \"mountpoint\": \"/\" }] } }, { \"href\": \"/api/v1/hosts/host2\", \"Hosts\":", "\"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] } ] services =", "} services[\"configurations\"] = {} expected = { 'admin-properties': { 'properties':", "{ 'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env': {'properties': {}}, 'usersync-properties': {", "def test_validateStormSiteConfigurations(self): configurations = { \"storm-site\": { \"properties\": { 'metrics.reporter.register':", "Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\", \"is_master\": False, \"hostnames\": [\"host1\"]}, {\"name\":", "self.stackAdvisor.recommendHDFSConfigurations(configurations, clusterData, services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations", "result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "localhost = socket.getfqdn() hosts = self.prepareHosts([localhost, \"host2\"]) result = self.stackAdvisor.recommendComponentLayout(services,", "= \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations, expected, \"Test for", "services = { \"services\": [ ], \"configurations\": configurations } expected", "\"hdfs://host1:8080\", } }, \"ranger-env\": { \"properties\": { \"xasecure.audit.destination.db\": \"true\", \"xasecure.audit.destination.hdfs\":\"false\",", "\"1\", \"component_category\": \"MASTER\", \"component_name\": \"HIVE_SERVER\", \"custom_commands\": [], \"display_name\": \"Hive Server\",", "{ \"advertise_version\": \"true\", \"cardinality\": \"1\", \"component_category\": \"MASTER\", \"component_name\": \"WEBHCAT_SERVER\", \"custom_commands\":", "services = {\"services\": [{\"StackServices\": {\"service_name\" : \"HDFS\", \"service_version\" : \"2.6.0.2.2\"", "Set by user /var mountpoint, which is non-root , but", "{ 'properties': { 'policymgr_external_url': 'http://host1:6080', } }, 'ranger-env': {'properties': {}},", "'level': 'WARN'}, warn) # non-local FS, HDFS properties = {\"property1\":", "\"ERROR\"}, {\"message\": \"Value should be set\", \"level\": \"ERROR\"} ] self.assertValidationResult(expectedItems,", "self.assertEquals(nodemanager, None) # unknown component unknown_component = self.stackAdvisor.getHostWithComponent(\"YARN\", \"UNKNOWN\", services,", "for partition / is 1G\" # local FS, enough space", "\"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\":", "existing DB_FLAVOR and http enabled, HDP-2.3\") # Recommend for DB_FLAVOR", "get_system_min_uid_magic(self, exists_mock, open_mock): class MagicFile(object): def read(self): return \"\"\" #test", "\"STRING_VALUE\" } } } recommendedDefaults = { \"mapred-site\": { \"properties\":", "6, \"reservedRam\": 2, \"hbaseRam\": 1, \"minContainerSize\": 512, \"totalAvailableRam\": 3072, \"containers\":", "self.assertEquals(result, expected) def test_recommendStormConfigurations(self): # no AMS configurations = {}", "\"yarn.app.mapreduce.am.command-opts\": \"-Xmx99m\", \"mapreduce.map.memory.mb\": \"567\", \"mapreduce.reduce.memory.mb\": \"345\", \"mapreduce.map.java.opts\": \"-Xmx454m\", \"mapreduce.reduce.java.opts\": \"-Xmx277m\",", "\"Test for not existing DB_FLAVOR and http enabled, HDP-2.3\") #", "} } expected = { 'hbase-site': { 'properties': { 'hbase.superuser':", "\"mountpoint\" : \"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # /boot with", "\"true\", } } } } expected = { \"ranger.service.http.port\": \"7777\",", "clusterData, services, hosts) self.assertEquals(configurations, expected) configurations[\"hadoop-env\"][\"properties\"]['hdfs_user'] = \"hdfs1\" changedConfigurations =", "'hive', 'webhcat_user': 'webhcat'}}, 'hdfs-site': {'properties': {'dfs.datanode.data.dir': '/hadoop/hdfs/data', 'dfs.datanode.du.reserved': '1024'}}, 'hadoop-env':", "disk space, no warnings res = self.stackAdvisor.validateAmsHbaseSiteConfigurations(properties, recommendedDefaults, configurations, services,", "def test_mergeValidators(self): childValidators = { \"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.3\"}, \"HIVE\": {\"hiveserver2-site\":", "} } ] } expected = { \"hBaseInstalled\": True, \"components\":", "{\"property1\": \"value1\"} recommendedDefaults = {\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None)", "hosts) self.assertTrue(res) #Value is begger then expected recommendedDefaults = {'dfs.datanode.du.reserved':", "} host = { \"href\" : \"/api/v1/hosts/host1\", \"Hosts\" : {", "\"https://host1:8888\" } }, \"ranger-env\": {\"properties\": {}} } recommendedConfigurations = {}", "self.stackAdvisor.get_system_min_uid = self.get_system_min_uid_magic @patch('__builtin__.open') @patch('os.path.exists') def get_system_min_uid_magic(self, exists_mock, open_mock): class", "'type': 'configuration' } ] self.assertEquals(res, expected) # 2 partitions host['Hosts']['disk_info']", "\"service_version\" : \"2.6.0.2.2\" }, \"components\":[ { \"href\":\"/api/v1/stacks/HDP/versions/2.2/services/HDFS/components/DATANODE\", \"StackServiceComponents\":{ \"advertise_version\":\"true\", \"cardinality\":\"1+\",", "open(stackAdvisorPath, 'rb') as fp: stack_advisor = imp.load_module( 'stack_advisor', fp, stackAdvisorPath,", "exists_mock.return_value = True open_mock.return_value = MagicFile() return self.get_system_min_uid_real() def test_recommendationCardinalityALL(self):", "clusterData, services, hosts) self.assertEquals(configurations, expected) def test_recommendRangerConfigurations(self): clusterData = {}", "{ \"cpu_count\": 1, \"host_name\": \"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\":", "{ \"properties\": { 'metrics.reporter.register': \"org.apache.hadoop.metrics2.sink.storm.StormTimelineMetricsReporter\" } } } recommendedDefaults =", "\"component_name\":\"HDFS_CLIENT\", \"dependent_component_name\":\"JOURNALNODE\", \"dependent_service_name\":\"HDFS\", \"stack_name\":\"HDP\", \"stack_version\":\"2.2\" } } ] }, {", "\"HDFS\": {\"hdfs-site\": \"validateHDFSConfigurations2.2\", \"hadoop-env\": \"validateHDFSConfigurationsEnv2.2\"}, \"YARN\": {\"yarn-env\": \"validateYARNEnvConfigurations2.2\"}, \"HIVE\": {\"hiveserver2-site\":", "which is non-root , but not preferable - no warning", "{\"message\": \"Value is less than the recommended default of 512\",", "self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None) self.assertEquals(clusterData['hbaseRam'], 8) self.stackAdvisor.recommendHbaseConfigurations(configurations, clusterData, services, hosts)", "less then expected recommendedDefaults = {'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved':", "'*', 'hadoop.proxyuser.hdfs.hosts': '*', 'hadoop.proxyuser.hive.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.oozie.hosts': 'c6401.ambari.apache.org,c6402.ambari.apache.org', 'hadoop.proxyuser.falcon.groups': '*'}}, 'falcon-env':", "] self.assertValidationResult(expectedItems, result) def test_validationCardinality01TwoHostsAssigned(self): servicesInfo = [ { \"name\":", "2) fail: namenode_heapsize, namenode_opt_maxnewsize < recommended properties['namenode_heapsize'] = '1022' properties['namenode_opt_maxnewsize']", "\"1\", \"category\": \"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\"]} ] } ]", "\"8888\", } } } services['configurations'] = configurations expected = {", "[ { \"StackServiceComponents\" : { \"cardinality\" : \"1+\", \"component_category\" :", "\"8192\", } } } clusterData = self.stackAdvisor.getConfigurationClusterSummary(servicesList, hosts, components, None)", ": \"host1\", \"rack_info\" : \"/default-rack\", \"total_mem\" : 2097152 } },", "\"Hosts\" : { \"cpu_count\" : 6, \"total_mem\" : 50331648, \"disk_info\"", "not installed nodemanager = self.stackAdvisor.getHostWithComponent(\"YARN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None)", "match the existing layout \"\"\" services = { \"services\" :", "fp, hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor", "\"is_master\": True}] } ] services = self.prepareServices(servicesInfo) localhost = socket.getfqdn()", "\"zoo.cfg\": { \"properties\": { 'clientPort': \"2183\" } } } services", "> recommended recommendedDefaults = {'namenode_heapsize': '1024', 'namenode_opt_newsize' : '256', 'namenode_opt_maxnewsize'", "\"components\": [ { \"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] }", "import TestCase from mock.mock import patch, MagicMock class TestHDP206StackAdvisor(TestCase): def", "= { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"ORACLE\", } },", "\"policymgr_external_url\": \"https://host1:7777\" } } } recommendedConfigurations = {} self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData,", "} } self.stackAdvisor.recommendYARNConfigurations(configurations, clusterData, services, None) self.assertEquals(configurations, expected) def test_recommendMapReduce2Configurations_mapMemoryLessThan2560(self):", "\"MASTER\", \"is_master\": True, \"hostnames\": [\"host2\", \"host1\"]} ] } ] services", "False, \"hostnames\": [\"host1\"]}, {\"name\": \"GANGLIA_SERVER\", \"display_name\": \"Ganglia Server\", \"cardinality\": \"2\",", "= {} services['services'][0]['StackServices']['service_version'] = \"0.4.0\" self.stackAdvisor.recommendRangerConfigurations(recommendedConfigurations, clusterData, services, None) self.assertEquals(recommendedConfigurations,", ": \"tmpfs\", \"mountpoint\" : \"/boot/grub\" } ) self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) #", "} ] } ], \"configurations\": configurations } # only 1", "\"service_name\" : \"HDFS\" }, \"components\" : [ { \"StackServiceComponents\" :", ") self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # proper mountpoint with more space available", "\"mapMemory\": 512, \"reduceMemory\": 512, \"amMemory\": 512, \"referenceHost\": hosts[\"items\"][0][\"Hosts\"] } #", "'type': 'configuration', 'config-name': 'namenode_heapsize', 'level': 'WARN'}, {'config-name': 'namenode_opt_maxnewsize', 'config-type': 'hadoop-env',", "clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor = clazz() self.maxDiff = None", "\"c6401.ambari.apache.org\", \"os_arch\": \"x86_64\", \"os_type\": \"centos6\", \"ph_cpu_count\": 1, \"public_host_name\": \"c6401.ambari.apache.org\", \"rack_info\":", "More preferable /grid/0 mountpoint - warning hostInfo[\"disk_info\"].append( { \"available\" :", "{\"property1\": \"value1\"} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), None) properties = {\"property1\": \"value1\"}", "2097152, \"disk_info\": [ { \"available\": str(15<<30), # 15 GB \"type\":", "result = self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"Host is", "\"hostnames\": [\"zk.host1\",\"zk.host2\",\"zk.host3\"] } }, { \"StackServiceComponents\": { \"component_name\": \"ZOOKEEPER_CLIENT\", \"hostnames\":", "services, None) expected = [ {'config-name': 'metrics.reporter.register', 'config-type': 'storm-site', 'level':", "be set for property1'} self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties =", "\"ranger.service.http.enabled\": \"true\", } siteProperties = stack_advisor.getServicesSiteProperties(services, \"ranger-admin-site\") self.assertEquals(siteProperties, expected) def", "\"StackServiceComponents\": { \"component_name\": \"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ] }", ": \"5\", \"type\" : \"vboxsf\", \"mountpoint\" : \"/vagrant\" } )", "\"components\": [] } ] services = self.prepareServices(servicesInfo) services[\"configurations\"] = {\"yarn-site\":{\"properties\":{\"yarn.nodemanager.resource.memory-mb\":", "1) # [host2] self.assertEquals(namenodes, [hosts[\"items\"][1]]) namenode = self.stackAdvisor.getHostWithComponent(\"HDFS\", \"NAMENODE\", services,", "\"components\": [ {\"name\": \"GANGLIA_SERVER\", \"cardinality\": \"1\", \"category\": \"MASTER\", \"is_master\": True,", "configurations = { \"admin-properties\": { \"properties\": { \"DB_FLAVOR\": \"POSTGRES\", }", ": \"/grid/0\" }, { \"available\" : str(15<<30), # 15 GB", "\"NAMENODE\", \"hostnames\": [\"host1\"] } } ] } ], \"configurations\": {", "\"host1\", \"host2\" ] }, \"dependencies\":[ ] } ], }], \"configurations\":", "service unknown_component = self.stackAdvisor.getHostWithComponent(\"UNKNOWN\", \"NODEMANAGER\", services, hosts) self.assertEquals(nodemanager, None) def", "self.assertValidationResult(expectedItems, result) def test_validationHostIsNotUsed(self): servicesInfo = [ { \"name\": \"GANGLIA\",", "'WARN'}, warn) # Set by user /var mountpoint, which is", "hdp206StackAdvisorPath, ('.py', 'rb', imp.PY_SOURCE)) clazz = getattr(self.stack_advisor_impl, hdp206StackAdvisorClassName) self.stackAdvisor =", "[ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia Monitor\", \"cardinality\": \"2\", \"category\": \"SLAVE\",", "'hbase123' } }, \"hbase-env\": { \"properties\": { \"hbase_master_heapsize\": \"4096\", \"hbase_regionserver_heapsize\":", "{ \"services\": [ { \"StackServices\": { \"service_name\": \"ZOOKEEPER\" }, \"components\":", "str(15<<30), # 15 GB \"type\": \"ext4\", \"mountpoint\": \"/\" } ]", "expected, \"Test for DB_FLAVOR POSTGRES and https enabled, HDP-2.3\") #", "self.assertEquals(self.stackAdvisor.validatorEqualsToRecommendedItem(properties, recommendedDefaults, \"property1\"), expected) properties = {} recommendedDefaults = {\"property1\":", "= self.stackAdvisor.validateComponentLayout(services, hosts) expectedItems = [ {\"message\": \"At least 3", "License. You may obtain a copy of the License at", "'name': 'host-group-2', 'components': [{ 'name': 'DATANODE' }] }] }, 'blueprint_cluster_binding':", "{ \"available\" : \"3\", \"type\" : \"ext4\", \"mountpoint\" : \"/grid/0\"", "'hbase.rootdir', 'config-type': 'ams-hbase-site', 'level': 'WARN', 'message': 'Consider not using /", "expected[\"containers\"] = 3.0 expected[\"cpu\"] = 4 expected[\"totalAvailableRam\"] = 512 expected[\"mapMemory\"]", "[] hosts = { \"items\" : [] } result =", "[]} self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) hostInfo[\"disk_info\"] = [] self.assertEquals([\"/\"], self.stackAdvisor.getPreferredMountPoints(hostInfo)) # root", "[] try: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"display_name\"] except KeyError: nextComponent[\"StackServiceComponents\"][\"display_name\"] = component[\"name\"]", "[ { \"name\": \"GANGLIA\", \"components\": [ {\"name\": \"GANGLIA_MONITOR\", \"display_name\": \"Ganglia", "= {\"property1\": \"file:///var/dir\"} recommendedDefaults = {\"property1\": \"file:///var/dir\"} # only /", "{'dfs.datanode.du.reserved': '1024'} properties = {'dfs.datanode.du.reserved': '512'} res = self.stackAdvisor.validateHDFSConfigurations(properties, recommendedDefaults,", "\"timeline.metrics.service.operation.mode\": \"embedded\" } } } recommendedDefaults = { 'hbase.rootdir': 'file:///var/lib/ambari-metrics-collector/hbase',", "\"is_master\": False}] } ] services = self.prepareServices(servicesInfo) hosts = self.prepareHosts([\"host1\",", "\"ranger.service.http.enabled\": \"true\", } } } } expected = { \"ranger.service.http.port\":", "try: actualComponentHostsMap[componentName] except KeyError, err: actualComponentHostsMap[componentName] = [] for host", "\"DB_FLAVOR\": \"POSTGRES\", } }, \"ranger-admin-site\": { \"properties\": { \"ranger.service.https.port\": \"7777\",", "Monitor component should be installed on all hosts in cluster.\",", "expected = \"zk.host1:2183,zk.host2:2183,zk.host3:2183\" self.assertEquals(result, expected) def test_validateHDFSConfigurations(self): configurations = {}", "\"COMPONENT\", \"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ] } ], \"configurations\": {}", "\"Recommended disk space for partition / is 1G\" # local", "should match the existing layout \"\"\" services = { \"services\"", "hosts) expected = [] self.assertEquals(res, expected) # 1 partition, no", "cluster before \"\"\" servicesInfo = [ { \"name\": \"GANGLIA\", \"components\":", "'config-type': 'hadoop-env', 'level': 'WARN', 'message': 'Value is less than the", "'hadoop-env': {'properties': {'hdfs_user': 'hdfs1', 'namenode_heapsize': '1024', 'proxyuser_group': 'users', 'namenode_opt_maxnewsize': '256',", "disk space for partition / is 10G', 'type': 'configuration' }", "\"hostnames\": [\"host1\",\"host2\",\"host3\"] } } ] } ], \"configurations\": {} }" ]
[ "time from pudb.remote import set_trace def worker(worker_id): \"\"\" Simple worker", "0 while i < 10: if worker_id == 1: #", "process\"\"\" i = 0 while i < 10: if worker_id", "10: if worker_id == 1: # debug process with id", "range(2): # 2 worker processes p = mp.Process(target=worker, args=(p_id,)) p.start()", "debug process with id 1 set_trace(term_size=(80, 24)) time.sleep(1) # represents", "encoding: utf-8 -*- import multiprocessing as mp import time from", "# debug process with id 1 set_trace(term_size=(80, 24)) time.sleep(1) #", "import set_trace def worker(worker_id): \"\"\" Simple worker process\"\"\" i =", "if __name__ == '__main__': processes = [] for p_id in", "for p_id in range(2): # 2 worker processes p =", "# represents some work print('In Process {}, i:{}'.format(worker_id, i)) i", "i < 10: if worker_id == 1: # debug process", "processes p = mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p) for p in", "i:{}'.format(worker_id, i)) i = i + 1 if __name__ ==", "== 1: # debug process with id 1 set_trace(term_size=(80, 24))", "some work print('In Process {}, i:{}'.format(worker_id, i)) i = i", "[] for p_id in range(2): # 2 worker processes p", "# 2 worker processes p = mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p)", "def worker(worker_id): \"\"\" Simple worker process\"\"\" i = 0 while", "2 worker processes p = mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p) for", "from pudb.remote import set_trace def worker(worker_id): \"\"\" Simple worker process\"\"\"", "1 if __name__ == '__main__': processes = [] for p_id", "# -*- encoding: utf-8 -*- import multiprocessing as mp import", "pudb.remote import set_trace def worker(worker_id): \"\"\" Simple worker process\"\"\" i", "< 10: if worker_id == 1: # debug process with", "= mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p) for p in processes: p.join()", "as mp import time from pudb.remote import set_trace def worker(worker_id):", "multiprocessing as mp import time from pudb.remote import set_trace def", "worker processes p = mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p) for p", "i = 0 while i < 10: if worker_id ==", "if worker_id == 1: # debug process with id 1", "import multiprocessing as mp import time from pudb.remote import set_trace", "set_trace(term_size=(80, 24)) time.sleep(1) # represents some work print('In Process {},", "= 0 while i < 10: if worker_id == 1:", "in range(2): # 2 worker processes p = mp.Process(target=worker, args=(p_id,))", "+ 1 if __name__ == '__main__': processes = [] for", "-*- encoding: utf-8 -*- import multiprocessing as mp import time", "print('In Process {}, i:{}'.format(worker_id, i)) i = i + 1", "i)) i = i + 1 if __name__ == '__main__':", "processes = [] for p_id in range(2): # 2 worker", "worker_id == 1: # debug process with id 1 set_trace(term_size=(80,", "worker process\"\"\" i = 0 while i < 10: if", "mp import time from pudb.remote import set_trace def worker(worker_id): \"\"\"", "id 1 set_trace(term_size=(80, 24)) time.sleep(1) # represents some work print('In", "set_trace def worker(worker_id): \"\"\" Simple worker process\"\"\" i = 0", "i = i + 1 if __name__ == '__main__': processes", "== '__main__': processes = [] for p_id in range(2): #", "process with id 1 set_trace(term_size=(80, 24)) time.sleep(1) # represents some", "\"\"\" Simple worker process\"\"\" i = 0 while i <", "1: # debug process with id 1 set_trace(term_size=(80, 24)) time.sleep(1)", "represents some work print('In Process {}, i:{}'.format(worker_id, i)) i =", "utf-8 -*- import multiprocessing as mp import time from pudb.remote", "-*- import multiprocessing as mp import time from pudb.remote import", "Simple worker process\"\"\" i = 0 while i < 10:", "time.sleep(1) # represents some work print('In Process {}, i:{}'.format(worker_id, i))", "while i < 10: if worker_id == 1: # debug", "24)) time.sleep(1) # represents some work print('In Process {}, i:{}'.format(worker_id,", "{}, i:{}'.format(worker_id, i)) i = i + 1 if __name__", "'__main__': processes = [] for p_id in range(2): # 2", "__name__ == '__main__': processes = [] for p_id in range(2):", "1 set_trace(term_size=(80, 24)) time.sleep(1) # represents some work print('In Process", "= [] for p_id in range(2): # 2 worker processes", "i + 1 if __name__ == '__main__': processes = []", "p_id in range(2): # 2 worker processes p = mp.Process(target=worker,", "p = mp.Process(target=worker, args=(p_id,)) p.start() processes.append(p) for p in processes:", "work print('In Process {}, i:{}'.format(worker_id, i)) i = i +", "Process {}, i:{}'.format(worker_id, i)) i = i + 1 if", "= i + 1 if __name__ == '__main__': processes =", "worker(worker_id): \"\"\" Simple worker process\"\"\" i = 0 while i", "import time from pudb.remote import set_trace def worker(worker_id): \"\"\" Simple", "with id 1 set_trace(term_size=(80, 24)) time.sleep(1) # represents some work" ]
[ "the breakpoint self.line = line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"])", "testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test", "__future__ import print_function import lldb from lldbsuite.test.decorators import * from", "structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import print_function import lldb", "Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import print_function import lldb from", "test(self): \"\"\"Test typedeffed untagged struct arguments for function call expressions\"\"\"", "Test calling user defined functions using expression evaluation. This test", "import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import *", "calling user defined functions using expression evaluation. This test checks", "* from lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__)", "for typedefs of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__", "expression evaluation. This test checks that typesystem lookup works correctly", "# Find the breakpoint self.line = line_number('main.cpp', '// lldb testsuite", "expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1,", "TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) # Find the breakpoint self.line =", "breakpoint self.line = line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll(", "lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) #", "lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from", "defined functions using expression evaluation. This test checks that typesystem", "lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir", "using expression evaluation. This test checks that typesystem lookup works", "= line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'],", "'// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def", "call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line,", "import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil", "for function call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self,", "function call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\",", "lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self):", "import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest", "@expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed untagged struct", "self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True )", "lookup works correctly for typedefs of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790", "archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed untagged struct arguments for", "untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import print_function import", "Find the breakpoint self.line = line_number('main.cpp', '// lldb testsuite break')", "evaluation. This test checks that typesystem lookup works correctly for", "\"\"\"Test typedeffed untagged struct arguments for function call expressions\"\"\" self.build()", "lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import", "works correctly for typedefs of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\"", "break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed", "self.line = line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'],", "@expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed untagged", "\"\"\" Test calling user defined functions using expression evaluation. This", "import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self)", "\"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\",", "TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) # Find the", "TestBase.setUp(self) # Find the breakpoint self.line = line_number('main.cpp', '// lldb", "https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import print_function import lldb from lldbsuite.test.decorators", "from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test", "num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED) self.expect(\"expr multiply(&s)\", substrs=['$0 = 1'])", "typesystem lookup works correctly for typedefs of untagged structures. Ticket:", "oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed untagged struct arguments", "print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import", "def test(self): \"\"\"Test typedeffed untagged struct arguments for function call", "mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) # Find the breakpoint", "\"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED) self.expect(\"expr multiply(&s)\", substrs=['$0", "line_number('main.cpp', '// lldb testsuite break') @expectedFailureAll(oslist=[\"windows\"]) @expectedFailureAll( oslist=['linux'], archs=['arm'], bugnumber=\"llvm.org/pr27868\")", "lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self):", "\"\"\" from __future__ import print_function import lldb from lldbsuite.test.decorators import", "class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) # Find", "arguments for function call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line(", "import * from lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir =", "functions using expression evaluation. This test checks that typesystem lookup", "struct arguments for function call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET)", "correctly for typedefs of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from", "lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED) self.expect(\"expr", "from lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase): mydir = TestBase.compute_mydir(__file__) def", "typedefs of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import", "from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestExprLookupAnonStructTypedef(TestBase):", "test checks that typesystem lookup works correctly for typedefs of", "self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED) self.expect(\"expr multiply(&s)\",", "<filename>lldb/packages/Python/lldbsuite/test/expression_command/anonymous-struct/TestCallUserAnonTypedef.py \"\"\" Test calling user defined functions using expression evaluation.", "self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED) self.expect(\"expr multiply(&s)\", substrs=['$0 =", "bugnumber=\"llvm.org/pr27868\") def test(self): \"\"\"Test typedeffed untagged struct arguments for function", "from __future__ import print_function import lldb from lldbsuite.test.decorators import *", "setUp(self): TestBase.setUp(self) # Find the breakpoint self.line = line_number('main.cpp', '//", "user defined functions using expression evaluation. This test checks that", "that typesystem lookup works correctly for typedefs of untagged structures.", "This test checks that typesystem lookup works correctly for typedefs", "* from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class", "def setUp(self): TestBase.setUp(self) # Find the breakpoint self.line = line_number('main.cpp',", "untagged struct arguments for function call expressions\"\"\" self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"),", "checks that typesystem lookup works correctly for typedefs of untagged", "self.build() self.runCmd(\"file \"+self.getBuildArtifact(\"a.out\"), CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True", "of untagged structures. Ticket: https://llvm.org/bugs/show_bug.cgi?id=26790 \"\"\" from __future__ import print_function", "typedeffed untagged struct arguments for function call expressions\"\"\" self.build() self.runCmd(\"file", "CURRENT_EXECUTABLE_SET) lldbutil.run_break_set_by_file_and_line( self, \"main.cpp\", self.line, num_expected_locations=-1, loc_exact=True ) self.runCmd(\"run\", RUN_SUCCEEDED)", "= TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) # Find the breakpoint self.line" ]
[ "amount (0-100): \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH():", "int(input(\"Specify height: \")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT():", "factor = float(input(\"Specify sharpening amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png')", "enhancer = ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness amount: \")) im_output", "= enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img = input(\"Insert the", "mode == \"BRIGHTNESS\": BRIGHTNESS() if mode == \"SHARPEN\": SHARPEN() def", "example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify", "enhancer = ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening amount: \")) im_output", "STRETCH(): img = input(\"Insert the name of an image found", "im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() if __name__ == \"__main__\": main()", "im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img = input(\"Insert", "= float(input(\"Specify sharpening amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show()", "== \"INVERT\": INVERT() if mode == \"BRIGHTNESS\": BRIGHTNESS() if mode", "= ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry amount (0-100): \")) im_output", "ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry amount (0-100): \")) im_output =", "= float(input(\"Specify deepfry amount (0-100): \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png')", "= input(\"Specify image editing mode. Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN,", "im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img = input(\"Insert", "sharpening amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() if __name__", "STRETCH() if mode == \"INVERT\": INVERT() if mode == \"BRIGHTNESS\":", "input(\"Specify image editing mode. Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or", "float(input(\"Specify deepfry amount (0-100): \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show()", "enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img = input(\"Insert the name", "def INVERT(): img = input(\"Insert the name of an image", "mode == \"STRETCH\": STRETCH() if mode == \"INVERT\": INVERT() if", "height: \")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img", "Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness amount:", "\")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img =", "SHARPEN, or INVERT: \") if mode == \"DEEPFRY\": DEEPFRY() if", "== \"DEEPFRY\": DEEPFRY() if mode == \"STRETCH\": STRETCH() if mode", "Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify width:", "im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify width: \")) factor2", "editing mode. Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or INVERT: \")", "Image, ImageEnhance user_account_name = \"Thomas.Li26\" def main(): mode = input(\"Specify", "float(input(\"Specify brightness amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def", "im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im) factor = float(input(\"Specify", "brightness amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN():", "== \"STRETCH\": STRETCH() if mode == \"INVERT\": INVERT() if mode", "\")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img =", "img)) enhancer = ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def", "example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im)", "the name of an image found in the Downloads folder", "= Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify width: \")) factor2 =", "mode == \"SHARPEN\": SHARPEN() def DEEPFRY(): img = input(\"Insert the", "im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img = input(\"Insert the name of", "= int(input(\"Specify height: \")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def", "or INVERT: \") if mode == \"DEEPFRY\": DEEPFRY() if mode", "== \"BRIGHTNESS\": BRIGHTNESS() if mode == \"SHARPEN\": SHARPEN() def DEEPFRY():", "mode = input(\"Specify image editing mode. Type DEEPFRY, STRETCH, BRIGHTNESS,", "Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) factor", "INVERT(): img = input(\"Insert the name of an image found", "im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img = input(\"Insert the name of", "width: \")) factor2 = int(input(\"Specify height: \")) im_output = im.resize((factor,factor2))", "STRETCH, BRIGHTNESS, SHARPEN, or INVERT: \") if mode == \"DEEPFRY\":", "\") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) im_output =", "im_output.show() def BRIGHTNESS(): img = input(\"Insert the name of an", "name of an image found in the Downloads folder (for", "\")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img =", "im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img = input(\"Insert the name of", "im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img = input(\"Insert", "if mode == \"BRIGHTNESS\": BRIGHTNESS() if mode == \"SHARPEN\": SHARPEN()", "img = input(\"Insert the name of an image found in", "im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1)", "BRIGHTNESS(): img = input(\"Insert the name of an image found", "im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img = input(\"Insert the name of", "\") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im) factor =", "Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or INVERT: \") if mode", "Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry amount", "mode == \"INVERT\": INVERT() if mode == \"BRIGHTNESS\": BRIGHTNESS() if", "= Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry", "= Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening", "mode == \"DEEPFRY\": DEEPFRY() if mode == \"STRETCH\": STRETCH() if", "import Image, ImageEnhance user_account_name = \"Thomas.Li26\" def main(): mode =", "def STRETCH(): img = input(\"Insert the name of an image", "enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img = input(\"Insert the name", "\") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify width: \"))", "image editing mode. Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or INVERT:", "int(input(\"Specify width: \")) factor2 = int(input(\"Specify height: \")) im_output =", "= ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img", "factor = float(input(\"Specify deepfry amount (0-100): \")) im_output = enhancer.enhance(factor)", "def main(): mode = input(\"Specify image editing mode. Type DEEPFRY,", "main(): mode = input(\"Specify image editing mode. Type DEEPFRY, STRETCH,", "= ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness amount: \")) im_output =", "\"SHARPEN\": SHARPEN() def DEEPFRY(): img = input(\"Insert the name of", "\"BRIGHTNESS\": BRIGHTNESS() if mode == \"SHARPEN\": SHARPEN() def DEEPFRY(): img", "= enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img = input(\"Insert the", "enhancer = ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS():", "= \"Thomas.Li26\" def main(): mode = input(\"Specify image editing mode.", "= im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img = input(\"Insert the", "img)) enhancer = ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening amount: \"))", "amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() if __name__ ==", "def SHARPEN(): img = input(\"Insert the name of an image", "if mode == \"STRETCH\": STRETCH() if mode == \"INVERT\": INVERT()", "ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness amount: \")) im_output = enhancer.enhance(factor)", "of an image found in the Downloads folder (for example:", "(0-100): \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def STRETCH(): img", "if mode == \"SHARPEN\": SHARPEN() def DEEPFRY(): img = input(\"Insert", "Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor = int(input(\"Specify width: \")) factor2 = int(input(\"Specify", "= ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening amount: \")) im_output =", "folder (for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor", "deepfry amount (0-100): \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def", "im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img = input(\"Insert the name", "im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) factor = float(input(\"Specify", "SHARPEN() def DEEPFRY(): img = input(\"Insert the name of an", "in the Downloads folder (for example: Image.png): \") im =", "DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or INVERT: \") if mode ==", "Downloads folder (for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img))", "Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show()", "== \"SHARPEN\": SHARPEN() def DEEPFRY(): img = input(\"Insert the name", "ImageEnhance user_account_name = \"Thomas.Li26\" def main(): mode = input(\"Specify image", "\"INVERT\": INVERT() if mode == \"BRIGHTNESS\": BRIGHTNESS() if mode ==", "factor = float(input(\"Specify brightness amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png')", "= float(input(\"Specify brightness amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show()", "the Downloads folder (for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name,", "example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im)", "= Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png')", "def BRIGHTNESS(): img = input(\"Insert the name of an image", "\") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) factor =", "img)) factor = int(input(\"Specify width: \")) factor2 = int(input(\"Specify height:", "BRIGHTNESS, SHARPEN, or INVERT: \") if mode == \"DEEPFRY\": DEEPFRY()", "from PIL import Image, ImageEnhance user_account_name = \"Thomas.Li26\" def main():", "def DEEPFRY(): img = input(\"Insert the name of an image", "\") if mode == \"DEEPFRY\": DEEPFRY() if mode == \"STRETCH\":", "folder (for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer", "im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show() def INVERT(): img = input(\"Insert", "(for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) factor =", "= enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img = input(\"Insert the", "img)) enhancer = ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness amount: \"))", "SHARPEN(): img = input(\"Insert the name of an image found", "if mode == \"DEEPFRY\": DEEPFRY() if mode == \"STRETCH\": STRETCH()", "BRIGHTNESS() if mode == \"SHARPEN\": SHARPEN() def DEEPFRY(): img =", "(for example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer =", "\"STRETCH\": STRETCH() if mode == \"INVERT\": INVERT() if mode ==", "ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening amount: \")) im_output = enhancer.enhance(factor)", "\")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() if __name__ == \"__main__\":", "DEEPFRY() if mode == \"STRETCH\": STRETCH() if mode == \"INVERT\":", "Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im) factor", "im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im) factor = float(input(\"Specify", "= int(input(\"Specify width: \")) factor2 = int(input(\"Specify height: \")) im_output", "factor = int(input(\"Specify width: \")) factor2 = int(input(\"Specify height: \"))", "\"DEEPFRY\": DEEPFRY() if mode == \"STRETCH\": STRETCH() if mode ==", "input(\"Insert the name of an image found in the Downloads", "\")) factor2 = int(input(\"Specify height: \")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png')", "float(input(\"Specify sharpening amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() if", "found in the Downloads folder (for example: Image.png): \") im", "Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im) factor = float(input(\"Specify sharpening amount:", "INVERT() if mode == \"BRIGHTNESS\": BRIGHTNESS() if mode == \"SHARPEN\":", "\") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Sharpness(im) factor =", "enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img = input(\"Insert the name", "PIL import Image, ImageEnhance user_account_name = \"Thomas.Li26\" def main(): mode", "if mode == \"INVERT\": INVERT() if mode == \"BRIGHTNESS\": BRIGHTNESS()", "amount: \")) im_output = enhancer.enhance(factor) im_output.save('more-contrast-image.png') im_output.show() def SHARPEN(): img", "user_account_name = \"Thomas.Li26\" def main(): mode = input(\"Specify image editing", "<filename>main.py from PIL import Image, ImageEnhance user_account_name = \"Thomas.Li26\" def", "im_output.show() def INVERT(): img = input(\"Insert the name of an", "factor2 = int(input(\"Specify height: \")) im_output = im.resize((factor,factor2)) im_output.save('more-contrast-image.png') im_output.show()", "Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im) factor", "mode. Type DEEPFRY, STRETCH, BRIGHTNESS, SHARPEN, or INVERT: \") if", "\"Thomas.Li26\" def main(): mode = input(\"Specify image editing mode. Type", "DEEPFRY(): img = input(\"Insert the name of an image found", "ImageEnhance.Contrast(im) im_output = enhancer.enhance(-1) im_output.save('more-contrast-image.png') im_output.show() def BRIGHTNESS(): img =", "= Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im) factor = float(input(\"Specify brightness", "INVERT: \") if mode == \"DEEPFRY\": DEEPFRY() if mode ==", "an image found in the Downloads folder (for example: Image.png):", "image found in the Downloads folder (for example: Image.png): \")", "img)) enhancer = ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry amount (0-100):", "Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Contrast(im) im_output", "example: Image.png): \") im = Image.open(r\"C:\\Users\\{}\\Downloads\\{}\".format(user_account_name, img)) enhancer = ImageEnhance.Brightness(im)", "im_output.show() def SHARPEN(): img = input(\"Insert the name of an", "enhancer = ImageEnhance.Contrast(im) factor = float(input(\"Specify deepfry amount (0-100): \"))", "= input(\"Insert the name of an image found in the", "im_output.show() def STRETCH(): img = input(\"Insert the name of an" ]
[ "Curbrock Summon 2 CURBROCK2 = 9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2", "Summon 2 CURBROCK2 = 9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 =", "2 sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\", CURBROCKS_ESCAPE_ROUTE_VER3, 0))", "ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050", "CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2 sm.spawnMob(CURBROCK2, 190, -208,", "CURBROCK2 = 9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 #", "# Curbrock Summon 2 CURBROCK2 = 9400930 # MOD ID", "= 600050050 # MAP ID 2 sm.spawnMob(CURBROCK2, 190, -208, False)", "MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2 sm.spawnMob(CURBROCK2,", "600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID", "9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID", "= 600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP", "2 CURBROCK2 = 9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040", "= 9400930 # MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP", "-208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\", CURBROCKS_ESCAPE_ROUTE_VER3, 0)) sm.waitForMobDeath(CURBROCK2) sm.warp(CURBROCKS_ESCAPE_ROUTE_VER2) sm.stopEvents()", "600050050 # MAP ID 2 sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800)", "<reponame>G00dBye/YYMS<gh_stars>10-100 # Curbrock Summon 2 CURBROCK2 = 9400930 # MOD", "ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2 sm.spawnMob(CURBROCK2, 190,", "MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 =", "# MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 # MAP ID 2", "CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3 = 600050050 #", "190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\", CURBROCKS_ESCAPE_ROUTE_VER3, 0)) sm.waitForMobDeath(CURBROCK2) sm.warp(CURBROCKS_ESCAPE_ROUTE_VER2)", "MAP ID 2 sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\",", "# MAP ID 2 sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000,", "# MOD ID CURBROCKS_ESCAPE_ROUTE_VER2 = 600050040 # MAP ID CURBROCKS_ESCAPE_ROUTE_VER3", "ID 2 sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\", CURBROCKS_ESCAPE_ROUTE_VER3,", "sm.spawnMob(CURBROCK2, 190, -208, False) sm.createClock(1800) sm.addEvent(sm.invokeAfterDelay(1800000, \"warp\", CURBROCKS_ESCAPE_ROUTE_VER3, 0)) sm.waitForMobDeath(CURBROCK2)" ]
[ "<reponame>Gerryflap/master_thesis \"\"\" Cancelling jobs on the University cluster forces programs", "As a remedy, this killswitch listener will stop the experiment", "will be stopped if a file named \"stop\" is encountered", "which sometimes crashes cluster nodes. As a remedy, this killswitch", "The existence of this file is checked after each epoch.", "import Listener class KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__() self.path =", "killswitch listener will stop the experiment in a nicer way", "prevent this from happening. The experiment will be stopped if", "KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__() self.path = os.path.join(experiment_path, \"stop\") def", "to prevent this from happening. The experiment will be stopped", "happening. The experiment will be stopped if a file named", "encountered in the results folder of the experiment. The existence", "Cancelling jobs on the University cluster forces programs to instantly", "to instantly quit, which sometimes crashes cluster nodes. As a", "the experiment. The existence of this file is checked after", "is encountered in the results folder of the experiment. The", "super().__init__() self.path = os.path.join(experiment_path, \"stop\") def initialize(self): pass def report(self,", "experiment. The existence of this file is checked after each", "this file is checked after each epoch. \"\"\" import os", "\"\"\" Cancelling jobs on the University cluster forces programs to", "crashes cluster nodes. As a remedy, this killswitch listener will", "a nicer way to prevent this from happening. The experiment", "on the University cluster forces programs to instantly quit, which", "a file named \"stop\" is encountered in the results folder", "nicer way to prevent this from happening. The experiment will", "is checked after each epoch. \"\"\" import os from trainloops.listeners.listener", "of this file is checked after each epoch. \"\"\" import", "file is checked after each epoch. \"\"\" import os from", "= os.path.join(experiment_path, \"stop\") def initialize(self): pass def report(self, state_dict): if", "os from trainloops.listeners.listener import Listener class KillSwitchListener(Listener): def __init__(self, experiment_path):", "class KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__() self.path = os.path.join(experiment_path, \"stop\")", "of the experiment. The existence of this file is checked", "programs to instantly quit, which sometimes crashes cluster nodes. As", "experiment in a nicer way to prevent this from happening.", "experiment_path): super().__init__() self.path = os.path.join(experiment_path, \"stop\") def initialize(self): pass def", "from trainloops.listeners.listener import Listener class KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__()", "results folder of the experiment. The existence of this file", "__init__(self, experiment_path): super().__init__() self.path = os.path.join(experiment_path, \"stop\") def initialize(self): pass", "the experiment in a nicer way to prevent this from", "nodes. As a remedy, this killswitch listener will stop the", "epoch. \"\"\" import os from trainloops.listeners.listener import Listener class KillSwitchListener(Listener):", "instantly quit, which sometimes crashes cluster nodes. As a remedy,", "if a file named \"stop\" is encountered in the results", "in the results folder of the experiment. The existence of", "quit, which sometimes crashes cluster nodes. As a remedy, this", "os.path.join(experiment_path, \"stop\") def initialize(self): pass def report(self, state_dict): if os.path.exists(self.path):", "a remedy, this killswitch listener will stop the experiment in", "file named \"stop\" is encountered in the results folder of", "will stop the experiment in a nicer way to prevent", "existence of this file is checked after each epoch. \"\"\"", "cluster nodes. As a remedy, this killswitch listener will stop", "after each epoch. \"\"\" import os from trainloops.listeners.listener import Listener", "def __init__(self, experiment_path): super().__init__() self.path = os.path.join(experiment_path, \"stop\") def initialize(self):", "forces programs to instantly quit, which sometimes crashes cluster nodes.", "\"stop\" is encountered in the results folder of the experiment.", "\"stop\") def initialize(self): pass def report(self, state_dict): if os.path.exists(self.path): exit()", "stop the experiment in a nicer way to prevent this", "self.path = os.path.join(experiment_path, \"stop\") def initialize(self): pass def report(self, state_dict):", "this killswitch listener will stop the experiment in a nicer", "remedy, this killswitch listener will stop the experiment in a", "listener will stop the experiment in a nicer way to", "The experiment will be stopped if a file named \"stop\"", "the results folder of the experiment. The existence of this", "jobs on the University cluster forces programs to instantly quit,", "each epoch. \"\"\" import os from trainloops.listeners.listener import Listener class", "Listener class KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__() self.path = os.path.join(experiment_path,", "stopped if a file named \"stop\" is encountered in the", "University cluster forces programs to instantly quit, which sometimes crashes", "\"\"\" import os from trainloops.listeners.listener import Listener class KillSwitchListener(Listener): def", "from happening. The experiment will be stopped if a file", "sometimes crashes cluster nodes. As a remedy, this killswitch listener", "cluster forces programs to instantly quit, which sometimes crashes cluster", "this from happening. The experiment will be stopped if a", "way to prevent this from happening. The experiment will be", "the University cluster forces programs to instantly quit, which sometimes", "trainloops.listeners.listener import Listener class KillSwitchListener(Listener): def __init__(self, experiment_path): super().__init__() self.path", "named \"stop\" is encountered in the results folder of the", "folder of the experiment. The existence of this file is", "import os from trainloops.listeners.listener import Listener class KillSwitchListener(Listener): def __init__(self,", "be stopped if a file named \"stop\" is encountered in", "experiment will be stopped if a file named \"stop\" is", "checked after each epoch. \"\"\" import os from trainloops.listeners.listener import", "in a nicer way to prevent this from happening. The" ]
[ "a user \"\"\" # decode users authentication token user_data =", "\"\"\" This class method is used to update a users", "notifications # the action below is done by use of", "notification = request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request) # append user_id", "serializers notification[\"user_id\"] = user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update", "# create a list of notifications # the action below", "the action below is done by use of list comprehension", "serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request): \"\"\" retrieve all", "list_of_notifications = [i for i in notifications] return Response({\"notifications\": list_of_notifications},", "renderer_classes = (NotificationsJSONRenderer,) def put(self, request): \"\"\" This class method", "by use of list comprehension list_of_notifications = [i for i", "from .models import Notifications from .renderers import ( NotificationsJSONRenderer )", "rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import", "notification statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self,", "\"read_status\" ) # create a list of notifications # the", "JWTAuthentication().authenticate(request) # append user_id from token to article variable for", ") from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response", "status=status.HTTP_201_CREATED) def get(self, request): \"\"\" retrieve all notifications of a", "from rest_framework import status from rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView,", "of notifications # the action below is done by use", "\"notification_body\", \"notification_owner\", \"read_status\" ) # create a list of notifications", "# append user_id from token to article variable for later", "of a user \"\"\" # decode users authentication token user_data", "from rest_framework.response import Response from rest_framework.views import APIView from ..authentication.backends", "import APIView from ..authentication.backends import JWTAuthentication from ..authentication.models import User", "request): \"\"\" This class method is used to update a", "to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request): \"\"\"", "# get user notifications details from the Notifications table in", "NotificationsJSONRenderer ) from .serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class", "import User from .models import Notifications from .renderers import (", "from .serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes", "# decode users authentication token user_data = JWTAuthentication().authenticate(request) # get", "AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView", "\"\"\" retrieve all notifications of a user \"\"\" # decode", "the Notifications table in the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\",", "serializer_class = NotificationsAPIViewSerializer notification = request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request)", "= JWTAuthentication().authenticate(request) # get user notifications details from the Notifications", "\"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" ) # create a", "class method is used to update a users article \"\"\"", "= user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the notification", "NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes =", ".renderers import ( NotificationsJSONRenderer ) from .serializers import ( NotificationsAPIViewSerializer,", "from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from", "= NotificationsAPIViewSerializer notification = request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request) #", "validations in serializers notification[\"user_id\"] = user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True)", "notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" )", "permission_classes = (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def put(self, request): \"\"\"", "put(self, request): \"\"\" This class method is used to update", "list comprehension list_of_notifications = [i for i in notifications] return", "Notifications from .renderers import ( NotificationsJSONRenderer ) from .serializers import", "IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from", "notifications of a user \"\"\" # decode users authentication token", "import status from rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView )", "import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,)", "(NotificationsJSONRenderer,) def put(self, request): \"\"\" This class method is used", "user notifications details from the Notifications table in the database", "( NotificationsJSONRenderer ) from .serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer )", "<gh_stars>1-10 from rest_framework import status from rest_framework.generics import ( RetrieveUpdateAPIView,", "comprehension list_of_notifications = [i for i in notifications] return Response({\"notifications\":", ".serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes =", "RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import AllowAny, IsAuthenticated from", "list of notifications # the action below is done by", "import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views import", "use of list comprehension list_of_notifications = [i for i in", "..authentication.models import User from .models import Notifications from .renderers import", "decode users authentication token user_data = JWTAuthentication().authenticate(request) # get user", "database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\"", "def get(self, request): \"\"\" retrieve all notifications of a user", "all notifications of a user \"\"\" # decode users authentication", "\"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" ) # create a list of", "# the action below is done by use of list", "\"\"\" # decode users authentication token user_data = JWTAuthentication().authenticate(request) #", "import Notifications from .renderers import ( NotificationsJSONRenderer ) from .serializers", "( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import AllowAny, IsAuthenticated", "from token to article variable for later validations in serializers", "import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import AllowAny,", "token user_data = JWTAuthentication().authenticate(request) # get user notifications details from", "for later validations in serializers notification[\"user_id\"] = user_data[1] serializer =", "user_id from token to article variable for later validations in", "import JWTAuthentication from ..authentication.models import User from .models import Notifications", "serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the notification statue to True serializer.update_read_status(serializer.data[\"notifications\"])", "# update the notification statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data,", "notification[\"user_id\"] = user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the", "from ..authentication.models import User from .models import Notifications from .renderers", "JWTAuthentication().authenticate(request) # get user notifications details from the Notifications table", "\"\"\" serializer_class = NotificationsAPIViewSerializer notification = request.data.get('notification', {}) user_data =", "of list comprehension list_of_notifications = [i for i in notifications]", "user_data = JWTAuthentication().authenticate(request) # get user notifications details from the", "import ( NotificationsJSONRenderer ) from .serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer", "Response from rest_framework.views import APIView from ..authentication.backends import JWTAuthentication from", "APIView from ..authentication.backends import JWTAuthentication from ..authentication.models import User from", "user_data = JWTAuthentication().authenticate(request) # append user_id from token to article", "from the Notifications table in the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values(", "NotificationsAPIViewSerializer notification = request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request) # append", "serializer.is_valid(raise_exception=True) # update the notification statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return", "user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the notification statue", "the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\",", "Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request): \"\"\" retrieve all notifications of", "status from rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from", "from ..authentication.backends import JWTAuthentication from ..authentication.models import User from .models", ") from .serializers import ( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView):", "serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the notification statue to", "= request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request) # append user_id from", "users article \"\"\" serializer_class = NotificationsAPIViewSerializer notification = request.data.get('notification', {})", ") class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def", "= Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" ) #", "rest_framework import status from rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView", ") # create a list of notifications # the action", "from rest_framework.generics import ( RetrieveUpdateAPIView, CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions", "CreateAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response", "rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views", "rest_framework.views import APIView from ..authentication.backends import JWTAuthentication from ..authentication.models import", "= (NotificationsJSONRenderer,) def put(self, request): \"\"\" This class method is", "class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def put(self,", "update a users article \"\"\" serializer_class = NotificationsAPIViewSerializer notification =", "action below is done by use of list comprehension list_of_notifications", "users authentication token user_data = JWTAuthentication().authenticate(request) # get user notifications", "\"notification_owner\", \"read_status\" ) # create a list of notifications #", "variable for later validations in serializers notification[\"user_id\"] = user_data[1] serializer", "user \"\"\" # decode users authentication token user_data = JWTAuthentication().authenticate(request)", "in serializers notification[\"user_id\"] = user_data[1] serializer = serializer_class(data=notification) serializer.is_valid(raise_exception=True) #", "to update a users article \"\"\" serializer_class = NotificationsAPIViewSerializer notification", "below is done by use of list comprehension list_of_notifications =", "(IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def put(self, request): \"\"\" This class", "to article variable for later validations in serializers notification[\"user_id\"] =", "True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request): \"\"\" retrieve", "User from .models import Notifications from .renderers import ( NotificationsJSONRenderer", "Notifications table in the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\",", "get(self, request): \"\"\" retrieve all notifications of a user \"\"\"", "token to article variable for later validations in serializers notification[\"user_id\"]", "update the notification statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED)", "return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request): \"\"\" retrieve all notifications", "( NotificationsAPIViewSerializer, GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes", "= JWTAuthentication().authenticate(request) # append user_id from token to article variable", "= (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def put(self, request): \"\"\" This", "append user_id from token to article variable for later validations", "RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import", "notifications details from the Notifications table in the database notifications", "\"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" ) # create a list", "def put(self, request): \"\"\" This class method is used to", "article \"\"\" serializer_class = NotificationsAPIViewSerializer notification = request.data.get('notification', {}) user_data", "from rest_framework.views import APIView from ..authentication.backends import JWTAuthentication from ..authentication.models", "statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request):", "= serializer_class(data=notification) serializer.is_valid(raise_exception=True) # update the notification statue to True", ".models import Notifications from .renderers import ( NotificationsJSONRenderer ) from", "rest_framework.response import Response from rest_framework.views import APIView from ..authentication.backends import", "GetNotificationsAPIViewSerializer ) class NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,)", "method is used to update a users article \"\"\" serializer_class", "later validations in serializers notification[\"user_id\"] = user_data[1] serializer = serializer_class(data=notification)", "retrieve all notifications of a user \"\"\" # decode users", "Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\", \"notification_owner\", \"read_status\" ) # create", "This class method is used to update a users article", "used to update a users article \"\"\" serializer_class = NotificationsAPIViewSerializer", "JWTAuthentication from ..authentication.models import User from .models import Notifications from", "table in the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\",", "in the database notifications = Notifications.objects.filter(notification_owner=user_data[1]).values( \"id\", \"article_id\", \"notification_title\", \"notification_body\",", "= [i for i in notifications] return Response({\"notifications\": list_of_notifications}, status=status.HTTP_200_OK)", "request): \"\"\" retrieve all notifications of a user \"\"\" #", "create a list of notifications # the action below is", "details from the Notifications table in the database notifications =", "is used to update a users article \"\"\" serializer_class =", "a users article \"\"\" serializer_class = NotificationsAPIViewSerializer notification = request.data.get('notification',", "get user notifications details from the Notifications table in the", "done by use of list comprehension list_of_notifications = [i for", "{}) user_data = JWTAuthentication().authenticate(request) # append user_id from token to", "NotificationsAPIView(RetrieveUpdateAPIView): permission_classes = (IsAuthenticated,) renderer_classes = (NotificationsJSONRenderer,) def put(self, request):", "article variable for later validations in serializers notification[\"user_id\"] = user_data[1]", "authentication token user_data = JWTAuthentication().authenticate(request) # get user notifications details", "request.data.get('notification', {}) user_data = JWTAuthentication().authenticate(request) # append user_id from token", "import Response from rest_framework.views import APIView from ..authentication.backends import JWTAuthentication", "a list of notifications # the action below is done", "..authentication.backends import JWTAuthentication from ..authentication.models import User from .models import", "from .renderers import ( NotificationsJSONRenderer ) from .serializers import (", "the notification statue to True serializer.update_read_status(serializer.data[\"notifications\"]) return Response(serializer.data, status=status.HTTP_201_CREATED) def", "is done by use of list comprehension list_of_notifications = [i" ]
[ "its behavior on all of the dictionary's subtypes before using", "the LICENSE file. \"\"\"Implements a frozen dictionary-like object\"\"\" import collections", "frozen dictionary-like object\"\"\" import collections import copy import common.memo as", "license that can be # found in the LICENSE file.", "self == other def __deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i() def", "a copy of this object with the 'kwargs' fields updated.\"\"\"", "be anything from heavyhanded to incorrect depending on the contents", "the one-size-fits-all behavior of 'deepcopy', the result can be anything", "of the dictionary. The caller should make sure they understand", "@memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns a", "be # found in the LICENSE file. \"\"\"Implements a frozen", "dictionary-like object\"\"\" import collections import copy import common.memo as memo", "not self == other def __deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i()", "len(self._data) def __getitem__(self, key): return self._data[key] @memo.memo_i() def __hash__(self): return", "self._data[key] @memo.memo_i() def __hash__(self): return hash(self.itemtuple()) def __str__(self): return str(self._data)", "mutable dictionary copy, replacing 'frozendict' with 'dict's. This function uses", "using it. Returns: (dict) A mutable clone of the dictionary", "depending on the contents of the dictionary. The caller should", "it. Returns: (dict) A mutable clone of the dictionary and", "mutable clone of the dictionary and its members. \"\"\" return", "__iter__(self): return iter(self._data) def __len__(self): return len(self._data) def __getitem__(self, key):", "'%s(%s)' % (type(self).__name__, str(self)) def __eq__(self, other): return self._data ==", "**kwargs): self._data = dict(*args, **kwargs) def __iter__(self): return iter(self._data) def", "BSD-style license that can be # found in the LICENSE", "by a BSD-style license that can be # found in", "# Use of this source code is governed by a", "is governed by a BSD-style license that can be #", "create a mutable deep copy of the dictionary. Note that", "copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns a copy of this object", "return str(self._data) def __repr__(self): return '%s(%s)' % (type(self).__name__, str(self)) def", "def mutableDict(self): \"\"\" Returns a mutable dictionary copy, replacing 'frozendict'", "should make sure they understand the operation and its behavior", "the result can be anything from heavyhanded to incorrect depending", "the dictionary. The caller should make sure they understand the", "__ne__(self, other): return not self == other def __deepcopy__(self, _memo):", "on the contents of the dictionary. The caller should make", "caller should make sure they understand the operation and its", "that can be # found in the LICENSE file. \"\"\"Implements", "operation and its behavior on all of the dictionary's subtypes", "dictionary. The caller should make sure they understand the operation", "of this source code is governed by a BSD-style license", "__str__(self): return str(self._data) def __repr__(self): return '%s(%s)' % (type(self).__name__, str(self))", "def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) def __getitem__(self,", "of the dictionary. Note that due to the one-size-fits-all behavior", "object\"\"\" import collections import copy import common.memo as memo class", "behavior of 'deepcopy', the result can be anything from heavyhanded", "The Chromium Authors. All rights reserved. # Use of this", "__deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems())) def", "This function uses the 'copy.deepcopy' method to create a mutable", "reserved. # Use of this source code is governed by", "__init__(self, *args, **kwargs): self._data = dict(*args, **kwargs) def __iter__(self): return", "import collections import copy import common.memo as memo class frozendict(collections.Mapping):", "dict(*args, **kwargs) def __iter__(self): return iter(self._data) def __len__(self): return len(self._data)", "replacing 'frozendict' with 'dict's. This function uses the 'copy.deepcopy' method", "object with the 'kwargs' fields updated.\"\"\" ndata = self.mutableDict() ndata.update(kwargs)", "understand the operation and its behavior on all of the", "key): return self._data[key] @memo.memo_i() def __hash__(self): return hash(self.itemtuple()) def __str__(self):", "__len__(self): return len(self._data) def __getitem__(self, key): return self._data[key] @memo.memo_i() def", "(type(self).__name__, str(self)) def __eq__(self, other): return self._data == other def", "this object with the 'kwargs' fields updated.\"\"\" ndata = self.mutableDict()", "Returns a mutable dictionary copy, replacing 'frozendict' with 'dict's. This", "def __len__(self): return len(self._data) def __getitem__(self, key): return self._data[key] @memo.memo_i()", "# Copyright 2014 The Chromium Authors. All rights reserved. #", "return self._data == other def __ne__(self, other): return not self", "from heavyhanded to incorrect depending on the contents of the", "return copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns a copy of this", "str(self._data) def __repr__(self): return '%s(%s)' % (type(self).__name__, str(self)) def __eq__(self,", "dictionary and its members. \"\"\" return copy.deepcopy(self) def extend(self, **kwargs):", "code is governed by a BSD-style license that can be", "__getitem__(self, key): return self._data[key] @memo.memo_i() def __hash__(self): return hash(self.itemtuple()) def", "(dict) A mutable clone of the dictionary and its members.", "a BSD-style license that can be # found in the", "to create a mutable deep copy of the dictionary. Note", "the dictionary. Note that due to the one-size-fits-all behavior of", "return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns a mutable dictionary copy,", "the contents of the dictionary. The caller should make sure", "on all of the dictionary's subtypes before using it. Returns:", "due to the one-size-fits-all behavior of 'deepcopy', the result can", "file. \"\"\"Implements a frozen dictionary-like object\"\"\" import collections import copy", "def itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns a mutable", "mutable deep copy of the dictionary. Note that due to", "Note that due to the one-size-fits-all behavior of 'deepcopy', the", "that due to the one-size-fits-all behavior of 'deepcopy', the result", "make sure they understand the operation and its behavior on", "governed by a BSD-style license that can be # found", "a frozen dictionary-like object\"\"\" import collections import copy import common.memo", "sure they understand the operation and its behavior on all", "Use of this source code is governed by a BSD-style", "'copy.deepcopy' method to create a mutable deep copy of the", "return hash(self.itemtuple()) def __str__(self): return str(self._data) def __repr__(self): return '%s(%s)'", "itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns a mutable dictionary", "dictionary copy, replacing 'frozendict' with 'dict's. This function uses the", "return not self == other def __deepcopy__(self, _memo): return copy.deepcopy(self._data)", "dictionary's subtypes before using it. Returns: (dict) A mutable clone", "def extend(self, **kwargs): \"\"\"Returns a copy of this object with", "copy of this object with the 'kwargs' fields updated.\"\"\" ndata", "'dict's. This function uses the 'copy.deepcopy' method to create a", "All rights reserved. # Use of this source code is", "# found in the LICENSE file. \"\"\"Implements a frozen dictionary-like", "frozen dictionary class\"\"\" def __init__(self, *args, **kwargs): self._data = dict(*args,", "class frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\" def __init__(self, *args, **kwargs):", "The caller should make sure they understand the operation and", "memo class frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\" def __init__(self, *args,", "self._data = dict(*args, **kwargs) def __iter__(self): return iter(self._data) def __len__(self):", "copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns", "return len(self._data) def __getitem__(self, key): return self._data[key] @memo.memo_i() def __hash__(self):", "tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\" Returns a mutable dictionary copy, replacing", "__hash__(self): return hash(self.itemtuple()) def __str__(self): return str(self._data) def __repr__(self): return", "**kwargs): \"\"\"Returns a copy of this object with the 'kwargs'", "import copy import common.memo as memo class frozendict(collections.Mapping): \"\"\"A frozen", "2014 The Chromium Authors. All rights reserved. # Use of", "result can be anything from heavyhanded to incorrect depending on", "def __str__(self): return str(self._data) def __repr__(self): return '%s(%s)' % (type(self).__name__,", "LICENSE file. \"\"\"Implements a frozen dictionary-like object\"\"\" import collections import", "def __eq__(self, other): return self._data == other def __ne__(self, other):", "\"\"\"A frozen dictionary class\"\"\" def __init__(self, *args, **kwargs): self._data =", "all of the dictionary's subtypes before using it. Returns: (dict)", "A mutable clone of the dictionary and its members. \"\"\"", "Copyright 2014 The Chromium Authors. All rights reserved. # Use", "_memo): return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self):", "== other def __deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self):", "its members. \"\"\" return copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns a", "extend(self, **kwargs): \"\"\"Returns a copy of this object with the", "return '%s(%s)' % (type(self).__name__, str(self)) def __eq__(self, other): return self._data", "heavyhanded to incorrect depending on the contents of the dictionary.", "members. \"\"\" return copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns a copy", "with 'dict's. This function uses the 'copy.deepcopy' method to create", "mutableDict(self): \"\"\" Returns a mutable dictionary copy, replacing 'frozendict' with", "incorrect depending on the contents of the dictionary. The caller", "other def __ne__(self, other): return not self == other def", "deep copy of the dictionary. Note that due to the", "subtypes before using it. Returns: (dict) A mutable clone of", "\"\"\" return copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns a copy of", "hash(self.itemtuple()) def __str__(self): return str(self._data) def __repr__(self): return '%s(%s)' %", "clone of the dictionary and its members. \"\"\" return copy.deepcopy(self)", "frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\" def __init__(self, *args, **kwargs): self._data", "== other def __ne__(self, other): return not self == other", "% (type(self).__name__, str(self)) def __eq__(self, other): return self._data == other", "def __init__(self, *args, **kwargs): self._data = dict(*args, **kwargs) def __iter__(self):", "'frozendict' with 'dict's. This function uses the 'copy.deepcopy' method to", "rights reserved. # Use of this source code is governed", "the 'kwargs' fields updated.\"\"\" ndata = self.mutableDict() ndata.update(kwargs) return type(self)(**ndata)", "def __hash__(self): return hash(self.itemtuple()) def __str__(self): return str(self._data) def __repr__(self):", "def __deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems()))", "@memo.memo_i() def __hash__(self): return hash(self.itemtuple()) def __str__(self): return str(self._data) def", "of the dictionary and its members. \"\"\" return copy.deepcopy(self) def", "class\"\"\" def __init__(self, *args, **kwargs): self._data = dict(*args, **kwargs) def", "Chromium Authors. All rights reserved. # Use of this source", "self._data == other def __ne__(self, other): return not self ==", "method to create a mutable deep copy of the dictionary.", "return iter(self._data) def __len__(self): return len(self._data) def __getitem__(self, key): return", "collections import copy import common.memo as memo class frozendict(collections.Mapping): \"\"\"A", "the operation and its behavior on all of the dictionary's", "and its behavior on all of the dictionary's subtypes before", "uses the 'copy.deepcopy' method to create a mutable deep copy", "return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return tuple(sorted(self.iteritems())) def mutableDict(self): \"\"\"", "copy import common.memo as memo class frozendict(collections.Mapping): \"\"\"A frozen dictionary", "they understand the operation and its behavior on all of", "other): return not self == other def __deepcopy__(self, _memo): return", "a mutable dictionary copy, replacing 'frozendict' with 'dict's. This function", "\"\"\"Implements a frozen dictionary-like object\"\"\" import collections import copy import", "a mutable deep copy of the dictionary. Note that due", "copy of the dictionary. Note that due to the one-size-fits-all", "behavior on all of the dictionary's subtypes before using it.", "this source code is governed by a BSD-style license that", "to the one-size-fits-all behavior of 'deepcopy', the result can be", "Returns: (dict) A mutable clone of the dictionary and its", "anything from heavyhanded to incorrect depending on the contents of", "other def __deepcopy__(self, _memo): return copy.deepcopy(self._data) @memo.memo_i() def itemtuple(self): return", "contents of the dictionary. The caller should make sure they", "to incorrect depending on the contents of the dictionary. The", "dictionary class\"\"\" def __init__(self, *args, **kwargs): self._data = dict(*args, **kwargs)", "other): return self._data == other def __ne__(self, other): return not", "def __ne__(self, other): return not self == other def __deepcopy__(self,", "the dictionary and its members. \"\"\" return copy.deepcopy(self) def extend(self,", "__eq__(self, other): return self._data == other def __ne__(self, other): return", "return self._data[key] @memo.memo_i() def __hash__(self): return hash(self.itemtuple()) def __str__(self): return", "str(self)) def __eq__(self, other): return self._data == other def __ne__(self,", "iter(self._data) def __len__(self): return len(self._data) def __getitem__(self, key): return self._data[key]", "function uses the 'copy.deepcopy' method to create a mutable deep", "found in the LICENSE file. \"\"\"Implements a frozen dictionary-like object\"\"\"", "of 'deepcopy', the result can be anything from heavyhanded to", "def __repr__(self): return '%s(%s)' % (type(self).__name__, str(self)) def __eq__(self, other):", "__repr__(self): return '%s(%s)' % (type(self).__name__, str(self)) def __eq__(self, other): return", "the dictionary's subtypes before using it. Returns: (dict) A mutable", "'deepcopy', the result can be anything from heavyhanded to incorrect", "dictionary. Note that due to the one-size-fits-all behavior of 'deepcopy',", "def __getitem__(self, key): return self._data[key] @memo.memo_i() def __hash__(self): return hash(self.itemtuple())", "**kwargs) def __iter__(self): return iter(self._data) def __len__(self): return len(self._data) def", "in the LICENSE file. \"\"\"Implements a frozen dictionary-like object\"\"\" import", "with the 'kwargs' fields updated.\"\"\" ndata = self.mutableDict() ndata.update(kwargs) return", "before using it. Returns: (dict) A mutable clone of the", "common.memo as memo class frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\" def", "source code is governed by a BSD-style license that can", "Authors. All rights reserved. # Use of this source code", "*args, **kwargs): self._data = dict(*args, **kwargs) def __iter__(self): return iter(self._data)", "\"\"\" Returns a mutable dictionary copy, replacing 'frozendict' with 'dict's.", "and its members. \"\"\" return copy.deepcopy(self) def extend(self, **kwargs): \"\"\"Returns", "the 'copy.deepcopy' method to create a mutable deep copy of", "of this object with the 'kwargs' fields updated.\"\"\" ndata =", "as memo class frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\" def __init__(self,", "= dict(*args, **kwargs) def __iter__(self): return iter(self._data) def __len__(self): return", "copy, replacing 'frozendict' with 'dict's. This function uses the 'copy.deepcopy'", "of the dictionary's subtypes before using it. Returns: (dict) A", "one-size-fits-all behavior of 'deepcopy', the result can be anything from", "\"\"\"Returns a copy of this object with the 'kwargs' fields", "can be anything from heavyhanded to incorrect depending on the", "import common.memo as memo class frozendict(collections.Mapping): \"\"\"A frozen dictionary class\"\"\"", "can be # found in the LICENSE file. \"\"\"Implements a" ]
[]
[]
[]
[ "common to CIFAR10 and CIFAR100 datasets. \"\"\" from __future__ import", "= cPickle.load(f, encoding='bytes') # decode utf8 d_decoded = {} for", "if sys.version_info < (3,): d = cPickle.load(f) else: d =", "import print_function import sys from six.moves import cPickle def load_batch(fpath,", "labels)`. \"\"\" with open(fpath, 'rb') as f: if sys.version_info <", "{} for k, v in d.items(): d_decoded[k.decode('utf8')] = v d", "from __future__ import print_function import sys from six.moves import cPickle", "= cPickle.load(f) else: d = cPickle.load(f, encoding='bytes') # decode utf8", "import cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal utility for parsing CIFAR", "labels = d[label_key] data = data.reshape(data.shape[0], 3, 32, 32) return", "-*- coding: utf-8 -*- \"\"\"Utilities common to CIFAR10 and CIFAR100", "CIFAR10 and CIFAR100 datasets. \"\"\" from __future__ import absolute_import from", "cPickle.load(f) else: d = cPickle.load(f, encoding='bytes') # decode utf8 d_decoded", "__future__ import division from __future__ import print_function import sys from", "for parsing CIFAR data. # Arguments fpath: path the file", "path the file to parse. label_key: key for label data", "cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal utility for parsing CIFAR data.", "= v d = d_decoded data = d['data'] labels =", "else: d = cPickle.load(f, encoding='bytes') # decode utf8 d_decoded =", "sys.version_info < (3,): d = cPickle.load(f) else: d = cPickle.load(f,", "data. # Arguments fpath: path the file to parse. label_key:", "-*- \"\"\"Utilities common to CIFAR10 and CIFAR100 datasets. \"\"\" from", "# Arguments fpath: path the file to parse. label_key: key", "utf-8 -*- \"\"\"Utilities common to CIFAR10 and CIFAR100 datasets. \"\"\"", "key for label data in the retrieve dictionary. # Returns", "CIFAR100 datasets. \"\"\" from __future__ import absolute_import from __future__ import", "open(fpath, 'rb') as f: if sys.version_info < (3,): d =", "fpath: path the file to parse. label_key: key for label", "decode utf8 d_decoded = {} for k, v in d.items():", "sys from six.moves import cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal utility", "for label data in the retrieve dictionary. # Returns A", "utility for parsing CIFAR data. # Arguments fpath: path the", "\"\"\"Utilities common to CIFAR10 and CIFAR100 datasets. \"\"\" from __future__", "d = d_decoded data = d['data'] labels = d[label_key] data", "d = cPickle.load(f) else: d = cPickle.load(f, encoding='bytes') # decode", "the retrieve dictionary. # Returns A tuple `(data, labels)`. \"\"\"", "parsing CIFAR data. # Arguments fpath: path the file to", "utf8 d_decoded = {} for k, v in d.items(): d_decoded[k.decode('utf8')]", "label data in the retrieve dictionary. # Returns A tuple", "CIFAR data. # Arguments fpath: path the file to parse.", "tuple `(data, labels)`. \"\"\" with open(fpath, 'rb') as f: if", "dictionary. # Returns A tuple `(data, labels)`. \"\"\" with open(fpath,", "< (3,): d = cPickle.load(f) else: d = cPickle.load(f, encoding='bytes')", "`(data, labels)`. \"\"\" with open(fpath, 'rb') as f: if sys.version_info", "in the retrieve dictionary. # Returns A tuple `(data, labels)`.", "v d = d_decoded data = d['data'] labels = d[label_key]", "to parse. label_key: key for label data in the retrieve", "to CIFAR10 and CIFAR100 datasets. \"\"\" from __future__ import absolute_import", "Returns A tuple `(data, labels)`. \"\"\" with open(fpath, 'rb') as", "import sys from six.moves import cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal", "from __future__ import absolute_import from __future__ import division from __future__", "A tuple `(data, labels)`. \"\"\" with open(fpath, 'rb') as f:", "\"\"\" with open(fpath, 'rb') as f: if sys.version_info < (3,):", "label_key: key for label data in the retrieve dictionary. #", "retrieve dictionary. # Returns A tuple `(data, labels)`. \"\"\" with", "'rb') as f: if sys.version_info < (3,): d = cPickle.load(f)", "__future__ import print_function import sys from six.moves import cPickle def", "Arguments fpath: path the file to parse. label_key: key for", "= d[label_key] data = data.reshape(data.shape[0], 3, 32, 32) return data,", "for k, v in d.items(): d_decoded[k.decode('utf8')] = v d =", "def load_batch(fpath, label_key='labels'): \"\"\"Internal utility for parsing CIFAR data. #", "d = cPickle.load(f, encoding='bytes') # decode utf8 d_decoded = {}", "label_key='labels'): \"\"\"Internal utility for parsing CIFAR data. # Arguments fpath:", "k, v in d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded", "\"\"\" from __future__ import absolute_import from __future__ import division from", "coding: utf-8 -*- \"\"\"Utilities common to CIFAR10 and CIFAR100 datasets.", "absolute_import from __future__ import division from __future__ import print_function import", "d_decoded[k.decode('utf8')] = v d = d_decoded data = d['data'] labels", "f: if sys.version_info < (3,): d = cPickle.load(f) else: d", "# -*- coding: utf-8 -*- \"\"\"Utilities common to CIFAR10 and", "__future__ import absolute_import from __future__ import division from __future__ import", "from __future__ import division from __future__ import print_function import sys", "load_batch(fpath, label_key='labels'): \"\"\"Internal utility for parsing CIFAR data. # Arguments", "v in d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded data", "\"\"\"Internal utility for parsing CIFAR data. # Arguments fpath: path", "data in the retrieve dictionary. # Returns A tuple `(data,", "data = d['data'] labels = d[label_key] data = data.reshape(data.shape[0], 3,", "datasets. \"\"\" from __future__ import absolute_import from __future__ import division", "the file to parse. label_key: key for label data in", "from six.moves import cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal utility for", "file to parse. label_key: key for label data in the", "(3,): d = cPickle.load(f) else: d = cPickle.load(f, encoding='bytes') #", "import division from __future__ import print_function import sys from six.moves", "d_decoded data = d['data'] labels = d[label_key] data = data.reshape(data.shape[0],", "= {} for k, v in d.items(): d_decoded[k.decode('utf8')] = v", "# decode utf8 d_decoded = {} for k, v in", "d['data'] labels = d[label_key] data = data.reshape(data.shape[0], 3, 32, 32)", "= d['data'] labels = d[label_key] data = data.reshape(data.shape[0], 3, 32,", "d[label_key] data = data.reshape(data.shape[0], 3, 32, 32) return data, labels", "division from __future__ import print_function import sys from six.moves import", "six.moves import cPickle def load_batch(fpath, label_key='labels'): \"\"\"Internal utility for parsing", "and CIFAR100 datasets. \"\"\" from __future__ import absolute_import from __future__", "encoding='bytes') # decode utf8 d_decoded = {} for k, v", "d_decoded = {} for k, v in d.items(): d_decoded[k.decode('utf8')] =", "in d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded data =", "d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded data = d['data']", "parse. label_key: key for label data in the retrieve dictionary.", "with open(fpath, 'rb') as f: if sys.version_info < (3,): d", "as f: if sys.version_info < (3,): d = cPickle.load(f) else:", "import absolute_import from __future__ import division from __future__ import print_function", "= d_decoded data = d['data'] labels = d[label_key] data =", "print_function import sys from six.moves import cPickle def load_batch(fpath, label_key='labels'):", "# Returns A tuple `(data, labels)`. \"\"\" with open(fpath, 'rb')", "cPickle.load(f, encoding='bytes') # decode utf8 d_decoded = {} for k," ]
[ "').splitlines()]) for key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in", "bag', '').replace('.', '').replace(' no other', '0 ').splitlines()]) for key in", "no other', '0 ').splitlines()]) for key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip()))", "int(d[:2].strip())) for d in rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1 cause", "rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1 cause shiny bag not included", "f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace(' no other', '0 ').splitlines()])", "open('day7/input.txt') as f: rules=dict([l.split(' contain') for l in f.read().replace(' bags',", "for key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in rules[key].split(',", "return numBags with open('day7/input.txt') as f: rules=dict([l.split(' contain') for l", "bags', '').replace(' bag', '').replace('.', '').replace(' no other', '0 ').splitlines()]) for", "getNumBags(color): if color=='': return 0 numBags=1 for bag in rules[color]:", "d in rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1 cause shiny bag", "if color=='': return 0 numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0])", "<gh_stars>1-10 def getNumBags(color): if color=='': return 0 numBags=1 for bag", "0 numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with", "return 0 numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags", "other', '0 ').splitlines()]) for key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for", "rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1", "for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as", "contain') for l in f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace('", "rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as f: rules=dict([l.split(' contain')", "color=='': return 0 numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return", "in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in rules[key].split(', ')] print(getNumBags('shiny", "in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as f: rules=dict([l.split('", "with open('day7/input.txt') as f: rules=dict([l.split(' contain') for l in f.read().replace('", "def getNumBags(color): if color=='': return 0 numBags=1 for bag in", "'').replace(' bag', '').replace('.', '').replace(' no other', '0 ').splitlines()]) for key", "rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in rules[key].split(', ')] print(getNumBags('shiny gold')-1)", "for d in rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1 cause shiny", "numBags=1 for bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt')", "in f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace(' no other', '0", "'').replace(' no other', '0 ').splitlines()]) for key in rules: rules[key]=[(d[2:].strip(),", "f: rules=dict([l.split(' contain') for l in f.read().replace(' bags', '').replace(' bag',", "'0 ').splitlines()]) for key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d", "'').replace('.', '').replace(' no other', '0 ').splitlines()]) for key in rules:", "in rules[key].split(', ')] print(getNumBags('shiny gold')-1) #-1 cause shiny bag not", "numBags with open('day7/input.txt') as f: rules=dict([l.split(' contain') for l in", "l in f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace(' no other',", "numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as f: rules=dict([l.split(' contain') for", "for l in f.read().replace(' bags', '').replace(' bag', '').replace('.', '').replace(' no", "rules=dict([l.split(' contain') for l in f.read().replace(' bags', '').replace(' bag', '').replace('.',", "key in rules: rules[key]=[(d[2:].strip(), int(d[:2].strip())) for d in rules[key].split(', ')]", "bag in rules[color]: numBags+=bag[1]*getNumBags(bag[0]) return numBags with open('day7/input.txt') as f:", "as f: rules=dict([l.split(' contain') for l in f.read().replace(' bags', '').replace('" ]
[ "core.advbase import * from slot.d import * def module(): return", "Leviathan() conf['acl'] = \"\"\" `dragon `s1 `s2, seq=5 and cancel", "import * def module(): return Luther class Luther(Adv): a1 =", "fsc `fs, seq=5 \"\"\" coab = ['Blade', 'Xander', 'Tiki'] if", "or fsc `fs, seq=5 \"\"\" coab = ['Blade', 'Xander', 'Tiki']", "['slots.d'] = Leviathan() conf['acl'] = \"\"\" `dragon `s1 `s2, seq=5", "module(): return Luther class Luther(Adv): a1 = ('cc',0.10,'hit15') conf =", "from core.advbase import * from slot.d import * def module():", "`s2, seq=5 and cancel `s3, seq=5 and cancel or fsc", "import * from slot.d import * def module(): return Luther", "\"\"\" coab = ['Blade', 'Xander', 'Tiki'] if __name__ == '__main__':", "def module(): return Luther class Luther(Adv): a1 = ('cc',0.10,'hit15') conf", "`s1 `s2, seq=5 and cancel `s3, seq=5 and cancel or", "`s3, seq=5 and cancel or fsc `fs, seq=5 \"\"\" coab", "and cancel or fsc `fs, seq=5 \"\"\" coab = ['Blade',", "cancel or fsc `fs, seq=5 \"\"\" coab = ['Blade', 'Xander',", "conf['acl'] = \"\"\" `dragon `s1 `s2, seq=5 and cancel `s3,", "return Luther class Luther(Adv): a1 = ('cc',0.10,'hit15') conf = {}", "and cancel `s3, seq=5 and cancel or fsc `fs, seq=5", "coab = ['Blade', 'Xander', 'Tiki'] if __name__ == '__main__': from", "Luther(Adv): a1 = ('cc',0.10,'hit15') conf = {} conf ['slots.d'] =", "conf ['slots.d'] = Leviathan() conf['acl'] = \"\"\" `dragon `s1 `s2,", "seq=5 and cancel or fsc `fs, seq=5 \"\"\" coab =", "`fs, seq=5 \"\"\" coab = ['Blade', 'Xander', 'Tiki'] if __name__", "slot.d import * def module(): return Luther class Luther(Adv): a1", "a1 = ('cc',0.10,'hit15') conf = {} conf ['slots.d'] = Leviathan()", "conf = {} conf ['slots.d'] = Leviathan() conf['acl'] = \"\"\"", "= {} conf ['slots.d'] = Leviathan() conf['acl'] = \"\"\" `dragon", "{} conf ['slots.d'] = Leviathan() conf['acl'] = \"\"\" `dragon `s1", "seq=5 \"\"\" coab = ['Blade', 'Xander', 'Tiki'] if __name__ ==", "from slot.d import * def module(): return Luther class Luther(Adv):", "Luther class Luther(Adv): a1 = ('cc',0.10,'hit15') conf = {} conf", "\"\"\" `dragon `s1 `s2, seq=5 and cancel `s3, seq=5 and", "('cc',0.10,'hit15') conf = {} conf ['slots.d'] = Leviathan() conf['acl'] =", "`dragon `s1 `s2, seq=5 and cancel `s3, seq=5 and cancel", "class Luther(Adv): a1 = ('cc',0.10,'hit15') conf = {} conf ['slots.d']", "['Blade', 'Xander', 'Tiki'] if __name__ == '__main__': from core.simulate import", "* def module(): return Luther class Luther(Adv): a1 = ('cc',0.10,'hit15')", "cancel `s3, seq=5 and cancel or fsc `fs, seq=5 \"\"\"", "= Leviathan() conf['acl'] = \"\"\" `dragon `s1 `s2, seq=5 and", "if __name__ == '__main__': from core.simulate import test_with_argv test_with_argv(None, *sys.argv)", "'Tiki'] if __name__ == '__main__': from core.simulate import test_with_argv test_with_argv(None,", "= \"\"\" `dragon `s1 `s2, seq=5 and cancel `s3, seq=5", "= ['Blade', 'Xander', 'Tiki'] if __name__ == '__main__': from core.simulate", "* from slot.d import * def module(): return Luther class", "'Xander', 'Tiki'] if __name__ == '__main__': from core.simulate import test_with_argv", "seq=5 and cancel `s3, seq=5 and cancel or fsc `fs,", "= ('cc',0.10,'hit15') conf = {} conf ['slots.d'] = Leviathan() conf['acl']" ]
[ "limit MAX_DIMENSION = 65500 _log_type = \"image-file\" format: Optional[str] _grouping:", "mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples})", "for (k, mask) in self._masks.items() } return json_dict def guess_mode(self,", "= np.min(data) if dmin < 0: data = (data -", "\"viewed in the UI. Please upgrade your wandb server\", repeat=False,", "self._boxes is not None ) and self._classes is None: raise", "class_id + \"_cls\",) classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"] = {", "some images have range -1...1 or 0-1 dmin = np.min(data)", "array filenames. In some cases, this can prevent images from", "# assert issubclass(data.dtype.type, np.integer), 'Illegal image format.' return data.clip(0, 255).astype(np.uint8)", "### Create a wandb.Image from a PILImage <!--yeadoc-test:log-image-pil-> ```python import", "key, step) if all_boxes: meta[\"all_boxes\"] = all_boxes return meta @classmethod", "= image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups", "type of image the np.array is representing \"\"\" # TODO:", "Classes( [ {\"id\": key, \"name\": total_classes[key]} for key in total_classes.keys()", "just the image-related data. # self._boxes = wbimage._boxes # self._masks", "data.shape[-1] == 4: return \"RGBA\" else: raise ValueError( \"Un-supported shape", "width, height = seq[0].image.size # type: ignore format = jsons[0][\"format\"]", "= all(size_equals_image(img) for img in seq) if not sizes_match: logging.warning(", "all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and not all(x is None", "\"_type\": \"images/separated\", \"width\": width, \"height\": height, \"format\": format, \"count\": num_images_to_log,", "boxes when adding to artifacts\" ) if self._classes is not", "masks: mask_item = masks[key] if isinstance(mask_item, ImageMask): masks_final[key] = mask_item", "it. self._grouping = None self._caption = None self._width = None", "vs the data type, since many # image libraries will", "is not None: for i, k in enumerate(self._masks): id_ =", "boxes: if not isinstance(boxes, dict): raise ValueError('Images \"boxes\" argument must", "-> None: super(Image, self).__init__() # TODO: We should remove grouping,", "'Illegal image format.' return data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json( cls:", "import Run as LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\",", "the PIL package. To get it, run \"pip install pillow\".',", "images: Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self,", "if np.max(data) <= 1.0: data = (data * 255).astype(np.int32) #", "meta dictionary object describing the child images. \"\"\" if TYPE_CHECKING:", "mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks) def _set_initialization_meta( self, grouping:", "in enumerate(self._boxes): id_ = \"{}{}\".format(id_, i) if id_ is not", "ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] = {", "\"L\" elif data.shape[-1] == 3: return \"RGB\" elif data.shape[-1] ==", "mode for an image. Most common are \"L\", \"RGB\", \"RGBA\".", "import Image as PILImage import wandb wandb.init() examples = []", "from .base_types.media import BatchableMedia, Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D from", "self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] = self.format if self._width is", "import Artifact as PublicArtifact from ..wandb_artifacts import Artifact as LocalArtifact", "uses it. self._grouping = None self._caption = None self._width =", "# but older versions would have issues with this. max_cli_version", "for i in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100,", ") if hasattr(data, \"requires_grad\") and data.requires_grad: data = data.detach() data", "common are \"L\", \"RGB\", \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption:", "if self._grouping: json_dict[\"grouping\"] = self._grouping if self._caption: json_dict[\"caption\"] = self._caption", "def __eq__(self, other: object) -> bool: if not isinstance(other, Image):", "examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS = 108 # PIL", "not None else None self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err", "object) -> bool: return not self.__eq__(other) def __eq__(self, other: object)", "a wandb.Image from a numpy array <!--yeadoc-test:log-image-numpy-> ```python import numpy", "ignore import numpy as np # type: ignore import PIL", "wbimage: \"Image\") -> None: self._grouping = wbimage._grouping self._caption = wbimage._caption", "image(self) -> Optional[\"PIL.Image\"]: if self._image is None: if self._path is", "issubclass(data.dtype.type, np.integer), 'Illegal image format.' return data.clip(0, 255).astype(np.uint8) @classmethod def", "cls.captions(images) def __ne__(self, other: object) -> bool: return not self.__eq__(other)", "self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension self._sha256 = wbimage._sha256 self._size", "= 65500 _log_type = \"image-file\" format: Optional[str] _grouping: Optional[int] _caption:", "self._set_file(tmp_path, is_tmp=True) @classmethod def from_json( cls: Type[\"Image\"], json_obj: dict, source_artifact:", "self._path is not None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs", "the range [0,255] to uint8, clipping if necessary. \"\"\" np", "# only overriding additional metdata passed in. If this pattern", "__eq__(self, other: object) -> bool: if not isinstance(other, Image): return", "else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks) def _set_initialization_meta(", "if not supplying PIL Images: pip install numpy\", ) #", "elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\", \"torchvision is required to", "Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] = None,", "val[\"name\"] for val in classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"] for", "in classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"] for val in classes})", "-> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = [] for image in", "cls: Type[\"Image\"], images: Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images)", "= None, grouping: Optional[int] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] =", "package. To get it, run \"pip install pillow\".', ) self._image", "PublicArtifact from ..wandb_artifacts import Artifact as LocalArtifact from ..wandb_run import", "isinstance(data, pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module(", "other._classes ) def to_data_array(self) -> List[Any]: res = [] if", "Optional[str] = None, caption: Optional[str] = None, grouping: Optional[int] =", "numpy\", ) # I think it's better to check the", "data: \"ImageDataType\", mode: str = None,) -> None: pil_image =", "Type, TYPE_CHECKING, Union from pkg_resources import parse_version import wandb from", "ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes = json_obj.get(\"boxes\") _boxes:", "or masks, just the image-related data. # self._boxes = wbimage._boxes", "key in masks: mask_item = masks[key] if isinstance(mask_item, ImageMask): masks_final[key]", "= BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image", "None: raise ValueError( \"classes must be passed to wandb.Image which", "] ) self._width, self._height = self.image.size # type: ignore self._free_ram()", ") # I think it's better to check the image", "def _initialize_from_wbimage(self, wbimage: \"Image\") -> None: self._grouping = wbimage._grouping self._caption", "Optional[int] _caption: Optional[str] _width: Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"] _classes:", "conversion %s\" % list(data.shape) ) @classmethod def to_uint8(cls, data: \"np.ndarray\")", "if not isinstance(other, Image): return False else: self_image = self.image", "-> dict: json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"]", ") self._set_file(path, is_tmp=False) self._image = pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:]", "classes if user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels)", "cover import matplotlib # type: ignore import numpy as np", "def bind_to_run( self, run: \"LocalRun\", key: Union[int, str], step: Union[int,", "a numpy array <!--yeadoc-test:log-image-numpy-> ```python import numpy as np import", "self._classes = wbimage._classes self._path = wbimage._path self._is_tmp = wbimage._is_tmp self._extension", "self._width is not None: json_dict[\"width\"] = self._width if self._height is", "= util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise ValueError( \"Files in an", "think anyone uses it. self._grouping = None self._caption = None", "Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None, ) -> None: if", "= image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups", "json_dict[\"grouping\"] = self._grouping if self._caption: json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact,", "step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is not None: for i,", "Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping,", "versions would have issues with this. max_cli_version = util._get_max_cli_version() if", "== other._classes ) def to_data_array(self) -> List[Any]: res = []", "Label for display of image. Examples: ### Create a wandb.Image", "can prevent images from being\" \"viewed in the UI. Please", "boxes_final[key] = box_item elif isinstance(box_item, dict): # TODO: Consider injecting", "this. max_cli_version = util._get_max_cli_version() if max_cli_version is None: return False", "255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal image format.' return data.clip(0,", "# type: ignore return img_width == width and img_height ==", "from wandb.apis.public import Artifact as PublicArtifact from ..wandb_artifacts import Artifact", "wbimage._height self._image = wbimage._image self._classes = wbimage._classes self._path = wbimage._path", "in all_box_groups): return all_box_groups else: return False @classmethod def all_captions(", "Run as LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\"", "we want to support dimensions being at the beginning of", "None self._masks = None # Allows the user to pass", "in range(self.image.height): res.append(data[i * self.image.width : (i + 1) *", "numpy as np import wandb wandb.init() examples = [] for", "Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str, step: Union[int, str],", "older versions would have issues with this. max_cli_version = util._get_max_cli_version()", "to be display incorrectly in the UI.\" ) meta =", "self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) +", "# type: ignore import numpy as np # type: ignore", ") @classmethod def to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts", "ImageMask if TYPE_CHECKING: # pragma: no cover import matplotlib #", "range [0,1] and integer images on the range [0,255] to", "object) -> bool: if not isinstance(other, Image): return False else:", "k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() } return json_dict", "from ..wandb_artifacts import Artifact as LocalArtifact from ..wandb_run import Run", "Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None, ) -> None: super(Image,", "str: return os.path.join(\"media\", \"images\") def bind_to_run( self, run: \"LocalRun\", key:", "Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] =", "None self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) if self._masks", "### Create a wandb.Image from a numpy array <!--yeadoc-test:log-image-numpy-> ```python", "\"pip install pillow\".', ) self._set_file(path, is_tmp=False) self._image = pil_image.open(path) self._image.load()", "sizes_match = all(size_equals_image(img) for img in seq) if not sizes_match:", "in masks: mask_item = masks[key] if isinstance(mask_item, ImageMask): masks_final[key] =", "= pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else: if hasattr(data,", "import wandb from wandb import util from ._private import MEDIA_TMP", "not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\") if", "Images: pip install numpy\", ) # I think it's better", "for k in image._boxes: box = image._boxes[k] box_group[k] = box.to_json(run)", "None: if grouping is not None: self._grouping = grouping if", "height = seq[0].image.size # type: ignore format = jsons[0][\"format\"] def", "return False else: self_image = self.image other_image = other.image if", "self.image is not None: data = list(self.image.getdata()) for i in", "wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if ( self._masks is not None", "is None: return False return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia):", "have masks or bounding boxes when adding to artifacts\" )", "if isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for val in classes._class_set}", "the array? if data.ndim == 2: return \"L\" elif data.shape[-1]", "(i + 1) * self.image.width]) self._free_ram() return res def _free_ram(self)", "i, k in enumerate(self._masks): id_ = \"{}{}\".format(id_, i) if id_", "Consider injecting top-level classes if user-provided is empty boxes_final[key] =", "(data - np.min(data)) / np.ptp(data) if np.max(data) <= 1.0: data", "additional metdata passed in. If this pattern is compelling, we", "key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, )", "\"width\": width, \"height\": height, \"format\": format, \"count\": num_images_to_log, } if", "None, ignore_copy_err: Optional[bool] = None, ) -> None: super().bind_to_run(run, key,", "None self._image = None self._classes = None self._boxes = None", "ValueError('Images \"boxes\" argument must be a dictionary') boxes_final: Dict[str, BoundingBoxes2D]", "= Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType = Union[str,", "shape for image conversion %s\" % list(data.shape) ) @classmethod def", "\"boxes\" argument must be a dictionary') boxes_final: Dict[str, BoundingBoxes2D] =", "key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is not None: for", "as LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ]", "self._height = self.image.size # type: ignore self._free_ram() def _initialize_from_wbimage(self, wbimage:", "data.detach() data = vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1,", "think it's better to check the image range vs the", ") def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict =", "= key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks,", "in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) image", "# TODO: Consider injecting top-level classes if user-provided is empty", "img_width == width and img_height == height # type: ignore", "if id_ is not None else None self._boxes[k].bind_to_run( run, key,", "= [obj[\"path\"] for obj in jsons] else: wandb.termwarn( \"Unable to", "return data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"],", "if self._path is not None: self._image = None @property def", "Allows the user to pass an Image object as the", "self._masks is not None: for i, k in enumerate(self._masks): id_", "want to implicitly copy boxes or masks, just the image-related", "hasattr(data, \"requires_grad\") and data.requires_grad: data = data.detach() data = vis_util.make_grid(data,", "= self._width if self._height is not None: json_dict[\"height\"] = self._height", "if self._caption: json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact =", "pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util", "= util.get_module( \"torchvision.utils\", \"torchvision is required to render images\" )", "== 3: return \"RGB\" elif data.shape[-1] == 4: return \"RGBA\"", "if not isinstance(boxes, dict): raise ValueError('Images \"boxes\" argument must be", "[] for i in range(3): pixels = np.random.randint(low=0, high=256, size=(100,", "mask = image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if", "mode=mode or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\")", "self._image = wbimage._image self._classes = wbimage._classes self._path = wbimage._path self._is_tmp", "{} for key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key", "\"RGB\" elif data.shape[-1] == 4: return \"RGBA\" else: raise ValueError(", "= [obj.to_json(run) for obj in seq] media_dir = cls.get_media_subdir() for", "= wbimage._path self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension self._sha256 =", "res.append(data[i * self.image.width : (i + 1) * self.image.width]) self._free_ram()", "= cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run) for obj in seq]", "``` ### Create a wandb.Image from a PILImage <!--yeadoc-test:log-image-pil-> ```python", "num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for obj in", "arrays # but older versions would have issues with this.", "masks[key] if isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif isinstance(mask_item, dict):", "self._height is not None: json_dict[\"height\"] = self._height if self._grouping: json_dict[\"grouping\"]", "TYPE_CHECKING, Union from pkg_resources import parse_version import wandb from wandb", "other_image = list(other_image.getdata()) return ( self._grouping == other._grouping and self._caption", "self._set_initialization_meta(grouping, caption, classes, boxes, masks) def _set_initialization_meta( self, grouping: Optional[int]", "= { \"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest, } elif", "def _initialize_from_path(self, path: str) -> None: pil_image = util.get_module( \"PIL.Image\",", "MAX_ITEMS = 108 # PIL limit MAX_DIMENSION = 65500 _log_type", "= { k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() }", "self._classes = None self._boxes = None self._masks = None #", "the first parameter and have a perfect copy, # only", "to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts floating point image", "self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks) def _set_initialization_meta( self,", "util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise ValueError( \"Files in an array", "the UI. Please upgrade your wandb server\", repeat=False, ) captions", "caption: (string) Label for display of image. Examples: ### Create", "an image. Most common are \"L\", \"RGB\", \"RGBA\". Full explanation", "height # type: ignore sizes_match = all(size_equals_image(img) for img in", "if masks: _masks = {} for key in masks: _masks[key]", "parse_version import wandb from wandb import util from ._private import", "json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if", "image. Examples: ### Create a wandb.Image from a numpy array", "Converts floating point image on the range [0,1] and integer", "_boxes: Optional[Dict[str, BoundingBoxes2D]] = None if boxes: _boxes = {}", "required='wandb.Image needs the PIL package. To get it, run \"pip", ") -> \"Image\": classes = None if json_obj.get(\"classes\") is not", "util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data,", "generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else:", "range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pil_image", "list(other_image.getdata()) return ( self._grouping == other._grouping and self._caption == other._caption", "buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image):", "which have masks or bounding boxes when adding to artifacts\"", "prevent images from being\" \"viewed in the UI. Please upgrade", "a terrible name and I don't # think anyone uses", "width and img_height == height # type: ignore sizes_match =", "assert issubclass(data.dtype.type, np.integer), 'Illegal image format.' return data.clip(0, 255).astype(np.uint8) @classmethod", "and not all(x is None for x in all_box_groups): return", "2, 0).cpu().numpy() ) else: if hasattr(data, \"numpy\"): # TF data", "some cases, this can prevent images from being\" \"viewed in", "= wbimage._image self._classes = wbimage._classes self._path = wbimage._path self._is_tmp =", "and converts it. mode: (string) The PIL mode for an", "infer the data format and converts it. mode: (string) The", "not isinstance(masks, dict): raise ValueError('Images \"masks\" argument must be a", "empty masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks", "for val in classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"] for val", "Optional[int] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str,", "as the first parameter and have a perfect copy, #", "image._masks: mask = image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None)", "not isinstance(other, Image): return False else: self_image = self.image other_image", "of image the np.array is representing \"\"\" # TODO: do", "self.image other_image = other.image if self_image is not None: self_image", "all_box_groups.append(None) if all_box_groups and not all(x is None for x", "key in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key =", "[] for image in images: if image._boxes: box_group = {}", "dict: \"\"\" Combines a list of images into a meta", "image._boxes: box = image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None)", "or 0-1 dmin = np.min(data) if dmin < 0: data", "captions = Image.all_captions(seq) if captions: meta[\"captions\"] = captions all_masks =", "key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key", "def _free_ram(self) -> None: if self._path is not None: self._image", "self._grouping = wbimage._grouping self._caption = wbimage._caption self._width = wbimage._width self._height", "if all_mask_groups and not all(x is None for x in", "grouping, it's a terrible name and I don't # think", "large image filenames arrays # but older versions would have", "Image.all_boxes(seq, run, key, step) if all_boxes: meta[\"all_boxes\"] = all_boxes return", "Optional[str] _width: Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes:", "max_cli_version is None: return False return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class", "= wbimage._height self._image = wbimage._image self._classes = wbimage._classes self._path =", "json_dict[\"width\"] = self._width if self._height is not None: json_dict[\"height\"] =", "\"torchvision.utils\", \"torchvision is required to render images\" ) if hasattr(data,", "PIL mode for an image. Most common are \"L\", \"RGB\",", "255).byte().permute(1, 2, 0).cpu().numpy() ) else: if hasattr(data, \"numpy\"): # TF", "required to render images\" ) if hasattr(data, \"requires_grad\") and data.requires_grad:", "return \"L\" elif data.shape[-1] == 3: return \"RGB\" elif data.shape[-1]", "False else: self_image = self.image other_image = other.image if self_image", "to implicitly copy boxes or masks, just the image-related data.", "mode: str = None,) -> None: pil_image = util.get_module( \"PIL.Image\",", "Image): return False else: self_image = self.image other_image = other.image", "step) if all_boxes: meta[\"all_boxes\"] = all_boxes return meta @classmethod def", "= [] for i in range(3): pixels = np.random.randint(low=0, high=256,", "all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]: return", "from ._private import MEDIA_TMP from .base_types.media import BatchableMedia, Media from", "\"{}{}\".format(id_, i) if id_ is not None else None self._boxes[k].bind_to_run(", "to uint8, clipping if necessary. \"\"\" np = util.get_module( \"numpy\",", "field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` ### Create a wandb.Image", "Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = []", "{ \"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest, } elif not", "array of Image's must be in the {} directory, not", ") ) num_images_to_log = len(seq) width, height = seq[0].image.size #", ") -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self, other: object)", "your wandb server\", repeat=False, ) captions = Image.all_captions(seq) if captions:", "= \"{}{}\".format(id_, i) if id_ is not None else None", "= Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() -> bool: # Newer versions", "don't # think anyone uses it. self._grouping = None self._caption", "= boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item,", "self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks) def", "isinstance(masks, dict): raise ValueError('Images \"masks\" argument must be a dictionary')", "not self.__eq__(other) def __eq__(self, other: object) -> bool: if not", "object describing the child images. \"\"\" if TYPE_CHECKING: seq =", "= Image._log_type json_dict[\"format\"] = self.format if self._width is not None:", "hashlib from io import BytesIO import logging import os from", "if user-provided is empty masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key],", "== other._height and self_image == other_image and self._classes == other._classes", "None: json_dict[\"height\"] = self._height if self._grouping: json_dict[\"grouping\"] = self._grouping if", "To get it, run \"pip install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)):", "\"Images sizes do not match. This will causes images to", "img_height = image.image.size # type: ignore return img_width == width", "into a meta dictionary object describing the child images. \"\"\"", "img_width, img_height = image.image.size # type: ignore return img_width ==", "being\" \"viewed in the UI. Please upgrade your wandb server\",", "[0,1] and integer images on the range [0,255] to uint8,", ") meta = { \"_type\": \"images/separated\", \"width\": width, \"height\": height,", "get it, run \"pip install pillow\".', ) self._set_file(path, is_tmp=False) self._image", "and I don't # think anyone uses it. self._grouping =", "None for x in all_mask_groups): return all_mask_groups else: return False", "= wbimage._caption self._width = wbimage._width self._height = wbimage._height self._image =", "= (data - np.min(data)) / np.ptp(data) if np.max(data) <= 1.0:", "masks = json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] = None if masks:", "not None: for i, k in enumerate(self._boxes): id_ = \"{}{}\".format(id_,", "images for logging to W&B. Arguments: data_or_path: (numpy array, string,", "0 and 255 # some images have range -1...1 or", "data = data.squeeze() # get rid of trivial dimensions as", "key boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None if", "is_tmp=True) @classmethod def from_json( cls: Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\"", "if self_image is not None: self_image = list(self_image.getdata()) if other_image", "key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if classes", "self._masks = wbimage._masks def _initialize_from_path(self, path: str) -> None: pil_image", "= wbimage._masks def _initialize_from_path(self, path: str) -> None: pil_image =", "examples = [] for i in range(3): pixels = np.random.randint(low=0,", "self._caption == other._caption and self._width == other._width and self._height ==", "data = data.detach() data = vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray(", "do not want to implicitly copy boxes or masks, just", "other_image = other.image if self_image is not None: self_image =", "Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for display of", "not None: self._grouping = grouping if caption is not None:", "= wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` ###", "If this pattern is compelling, we can generalize. if isinstance(data_or_path,", "only overriding additional metdata passed in. If this pattern is", "None: other_image = list(other_image.getdata()) return ( self._grouping == other._grouping and", "wandb.Image which have masks or bounding boxes when adding to", "is not None else None self._masks[k].bind_to_run( run, key, step, id_,", "if not obj[\"path\"].startswith(expected): raise ValueError( \"Files in an array of", "_server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for obj in jsons] else: wandb.termwarn(", "self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if ( self._masks", "display of image. Examples: ### Create a wandb.Image from a", "copy boxes or masks, just the image-related data. # self._boxes", "class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\", \"classes\", class_id", "image.image.size # type: ignore return img_width == width and img_height", "to check the image range vs the data type, since", "```python import numpy as np from PIL import Image as", "_initialize_from_path(self, path: str) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image", "json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items()", "self._image = pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:] self.format = ext", "display incorrectly in the UI.\" ) meta = { \"_type\":", "import Artifact as LocalArtifact from ..wandb_run import Run as LocalRun", "raise ValueError('Images \"masks\" argument must be a dictionary') masks_final: Dict[str,", "if self._height is not None: json_dict[\"height\"] = self._height if self._grouping:", "for key in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key", "all_mask_groups else: return False @classmethod def all_boxes( cls: Type[\"Image\"], images:", "bool: img_width, img_height = image.image.size # type: ignore return img_width", "to render images\" ) if hasattr(data, \"requires_grad\") and data.requires_grad: data", "data = data.numpy() if data.ndim > 2: data = data.squeeze()", "cls: Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\" ) -> \"Image\": classes", "ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if", "Optional[str] = None, grouping: Optional[int] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]]", "} if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for obj in jsons]", "bool]: all_mask_groups: List[Optional[dict]] = [] for image in images: if", "\"pip install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf)", "is not None: self._image = None @property def image(self) ->", "util from ._private import MEDIA_TMP from .base_types.media import BatchableMedia, Media", "\"np.ndarray\") -> str: \"\"\" Guess what type of image the", "def seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str,", "65500 _log_type = \"image-file\" format: Optional[str] _grouping: Optional[int] _caption: Optional[str]", "<!--yeadoc-test:log-image-numpy-> ```python import numpy as np import wandb wandb.init() examples", "= {} for key in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact)", "None if boxes: _boxes = {} for key in boxes:", "from wandb import util from ._private import MEDIA_TMP from .base_types.media", "# type: ignore import PIL # type: ignore import torch", "None self._classes = None self._boxes = None self._masks = None", "TYPE_CHECKING: # pragma: no cover import matplotlib # type: ignore", "wandb accept large image filenames arrays # but older versions", "= {} for key in boxes: box_item = boxes[key] if", "i in range(self.image.height): res.append(data[i * self.image.width : (i + 1)", "other._grouping and self._caption == other._caption and self._width == other._width and", "bool: if not isinstance(other, Image): return False else: self_image =", "= wbimage._is_tmp self._extension = wbimage._extension self._sha256 = wbimage._sha256 self._size =", "an Image object as the first parameter and have a", "boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item, dict):", "ignore_copy_err=ignore_copy_err ) if self._masks is not None: for i, k", "meta = { \"_type\": \"images/separated\", \"width\": width, \"height\": height, \"format\":", "._private import MEDIA_TMP from .base_types.media import BatchableMedia, Media from .helper_types.bounding_boxes_2d", "\"ImageMask\"], Dict[str, dict]]] = None, ) -> None: super(Image, self).__init__()", "self_image = list(self_image.getdata()) if other_image is not None: other_image =", "data.ndim > 2: data = data.squeeze() # get rid of", "self._width, self._height = self.image.size # type: ignore self._free_ram() def _initialize_from_wbimage(self,", "-1...1 or 0-1 dmin = np.min(data) if dmin < 0:", "a list of images into a meta dictionary object describing", "Accepts numpy array of image data, or a PIL image.", "wandb.Image from a PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy as np", "transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def from_json( cls: Type[\"Image\"], json_obj: dict,", "Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str,", "\"RGBA\" else: raise ValueError( \"Un-supported shape for image conversion %s\"", "image filenames arrays # but older versions would have issues", "\"masks\" argument must be a dictionary') masks_final: Dict[str, ImageMask] =", "return meta @classmethod def all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"], run:", "= None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None, )", "from a PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy as np from", "key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks: if not isinstance(masks,", "= util.get_module( \"numpy\", required=\"wandb.Image requires numpy if not supplying PIL", "numpy as np # type: ignore import PIL # type:", "is not None: json_dict[\"width\"] = self._width if self._height is not", "images on the range [0,255] to uint8, clipping if necessary.", "other.image if self_image is not None: self_image = list(self_image.getdata()) if", "= None, ) -> None: super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err)", "if all_boxes: meta[\"all_boxes\"] = all_boxes return meta @classmethod def all_masks(", "self._classes is None: raise ValueError( \"classes must be passed to", "PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy as np from PIL import", "def all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]:", "_masks: Optional[Dict[str, ImageMask]] = None if masks: _masks = {}", "if isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif isinstance(mask_item, dict): #", "obj in seq] media_dir = cls.get_media_subdir() for obj in jsons:", "step, id_, ignore_copy_err=ignore_copy_err ) if self._masks is not None: for", "{} for key in masks: mask_item = masks[key] if isinstance(mask_item,", "array, string, io) Accepts numpy array of image data, or", "array? if data.ndim == 2: return \"L\" elif data.shape[-1] ==", "-> bool: # Newer versions of wandb accept large image", "is empty masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"])", "name and I don't # think anyone uses it. self._grouping", "MEDIA_TMP from .base_types.media import BatchableMedia, Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D", "empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if", "= Image.all_boxes(seq, run, key, step) if all_boxes: meta[\"all_boxes\"] = all_boxes", "import Any, cast, Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Union", "all_box_groups and not all(x is None for x in all_box_groups):", "id_, ignore_copy_err=ignore_copy_err ) if self._masks is not None: for i,", "We do not want to implicitly copy boxes or masks,", "\"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run):", "rid of trivial dimensions as a convenience self._image = pil_image.fromarray(", "pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id())", "self_image is not None: self_image = list(self_image.getdata()) if other_image is", "wbimage._caption self._width = wbimage._width self._height = wbimage._height self._image = wbimage._image", "seq) if not sizes_match: logging.warning( \"Images sizes do not match.", "= None,) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs", "to support dimensions being at the beginning of the array?", "= list(self_image.getdata()) if other_image is not None: other_image = list(other_image.getdata())", "wandb wandb.init() examples = [] for i in range(3): pixels", "mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() } return json_dict def", "1) * self.image.width]) self._free_ram() return res def _free_ram(self) -> None:", "import BatchableMedia, Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes import", "# image libraries will return floats between 0 and 255", "+ \"_cls\",) classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"] = { \"type\":", "other._height and self_image == other_image and self._classes == other._classes )", "self._boxes.items() } if self._masks: json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact) for", "boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return cls(", "Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes import Classes from", "self._artifact_target = wbimage._artifact_target # We do not want to implicitly", "_masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]]", "= data.squeeze() # get rid of trivial dimensions as a", "i in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3))", "format and converts it. mode: (string) The PIL mode for", "Dict[str, dict]]] = None, ) -> None: super(Image, self).__init__() #", "Optional[int] = None, caption: Optional[str] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]]", "_log_type = \"image-file\" format: Optional[str] _grouping: Optional[int] _caption: Optional[str] _width:", "cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str, step: Union[int,", "-> bool: img_width, img_height = image.image.size # type: ignore return", "trivial dimensions as a convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode", "key, \"name\": total_classes[key]} for key in total_classes.keys() ] ) self._width,", "\"ImageMask\"], Dict[str, dict]]] = None, ) -> None: if grouping", "} return json_dict def guess_mode(self, data: \"np.ndarray\") -> str: \"\"\"", "if captions: meta[\"captions\"] = captions all_masks = Image.all_masks(seq, run, key,", "None, ) -> None: if grouping is not None: self._grouping", "if TYPE_CHECKING: # pragma: no cover import matplotlib # type:", "needs the PIL package. To get it, run \"pip install", "captions all_masks = Image.all_masks(seq, run, key, step) if all_masks: meta[\"all_masks\"]", "field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS = 108", "for key in boxes: box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D):", "len(total_classes.keys()) > 0: self._classes = Classes( [ {\"id\": key, \"name\":", "self._size = wbimage._size self.format = wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target", "run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups:", "if boxes: _boxes = {} for key in boxes: _boxes[key]", "= pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)):", "else: if hasattr(data, \"numpy\"): # TF data eager tensors data", "= Image.all_masks(seq, run, key, step) if all_masks: meta[\"all_masks\"] = all_masks", "= {} for k in image._masks: mask = image._masks[k] mask_group[k]", "np.min(data)) / np.ptp(data) if np.max(data) <= 1.0: data = (data", "wbimage._image self._classes = wbimage._classes self._path = wbimage._path self._is_tmp = wbimage._is_tmp", ") -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = [] for image", "return ( self._grouping == other._grouping and self._caption == other._caption and", "size_equals_image(image: \"Image\") -> bool: img_width, img_height = image.image.size # type:", "\"image-file\" format: Optional[str] _grouping: Optional[int] _caption: Optional[str] _width: Optional[int] _height:", "{val[\"id\"]: val[\"name\"] for val in classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"]", "res = [] if self.image is not None: data =", "for x in all_mask_groups): return all_mask_groups else: return False @classmethod", "caption is not None: self._caption = caption total_classes = {}", "LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType", "being at the beginning of the array? if data.ndim ==", "ValueError( \"Un-supported shape for image conversion %s\" % list(data.shape) )", "dict]]] = None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None,", "if boxes: if not isinstance(boxes, dict): raise ValueError('Images \"boxes\" argument", "run_or_artifact if ( self._masks is not None or self._boxes is", "and self._height == other._height and self_image == other_image and self._classes", "Consider injecting top-level classes if user-provided is empty masks_final[key] =", "Create a wandb.Image from a PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy", "all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step:", "pragma: no cover import matplotlib # type: ignore import numpy", "at the beginning of the array? if data.ndim == 2:", "This will causes images to be display incorrectly in the", "sizes do not match. This will causes images to be", "directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log = len(seq)", "(string) Label for display of image. Examples: ### Create a", "to infer the data format and converts it. mode: (string)", "self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def from_json( cls: Type[\"Image\"], json_obj:", "To get it, run \"pip install pillow\".', ) self._set_file(path, is_tmp=False)", "caption total_classes = {} if boxes: if not isinstance(boxes, dict):", "if self._boxes is not None: for i, k in enumerate(self._boxes):", "wandb from wandb import util from ._private import MEDIA_TMP from", "None # Allows the user to pass an Image object", "pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:] self.format = ext def _initialize_from_data(self,", "```python import numpy as np import wandb wandb.init() examples =", "filenames arrays # but older versions would have issues with", "= wbimage._grouping self._caption = wbimage._caption self._width = wbimage._width self._height =", "import util from ._private import MEDIA_TMP from .base_types.media import BatchableMedia,", "id_, ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict:", "box.to_json(run_or_artifact) for (k, box) in self._boxes.items() } if self._masks: json_dict[\"masks\"]", ") else: total_classes.update({val[\"id\"]: val[\"name\"] for val in classes}) if len(total_classes.keys())", "and self._classes == other._classes ) def to_data_array(self) -> List[Any]: res", "data.numpy() if data.ndim > 2: data = data.squeeze() # get", "= ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes = json_obj.get(\"boxes\")", "-> List[Any]: res = [] if self.image is not None:", "a perfect copy, # only overriding additional metdata passed in.", "log image array filenames. In some cases, this can prevent", "Type[\"Image\"]) -> str: return os.path.join(\"media\", \"images\") def bind_to_run( self, run:", "isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif isinstance(mask_item, dict): # TODO:", "pattern is compelling, we can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path)", "list(self_image.getdata()) if other_image is not None: other_image = list(other_image.getdata()) return", "dict): # TODO: Consider injecting top-level classes if user-provided is", "isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for val in classes._class_set} )", "= [] for image in images: if image._masks: mask_group =", "and self._width == other._width and self._height == other._height and self_image", "obj in jsons: expected = util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise", "def to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts floating point", "<= 1.0: data = (data * 255).astype(np.int32) # assert issubclass(data.dtype.type,", "of Image's must be in the {} directory, not {}\".format(", "be in the {} directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"] )", "self._width if self._height is not None: json_dict[\"height\"] = self._height if", "as np from PIL import Image as PILImage import wandb", "util.get_module( \"numpy\", required=\"wandb.Image requires numpy if not supplying PIL Images:", "BoundingBoxes2D from .helper_types.classes import Classes from .helper_types.image_mask import ImageMask if", "k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items() } if self._masks:", "json_obj.get(\"classes\") is not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\")", "the data format and converts it. mode: (string) The PIL", "def all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str,", "= image.image.size # type: ignore return img_width == width and", "None self._height = None self._image = None self._classes = None", "None,) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the", "self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str] = None, caption: Optional[str] =", "if classes is not None: if isinstance(classes, Classes): total_classes.update( {val[\"id\"]:", "not None: json_dict[\"height\"] = self._height if self._grouping: json_dict[\"grouping\"] = self._grouping", "self._masks = masks_final if classes is not None: if isinstance(classes,", "108 # PIL limit MAX_DIMENSION = 65500 _log_type = \"image-file\"", "jsons[0][\"format\"] def size_equals_image(image: \"Image\") -> bool: img_width, img_height = image.image.size", "Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self, other:", "if self._width is not None: json_dict[\"width\"] = self._width if self._height", "hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\", \"classes\", class_id + \"_cls\",)", "data_or_path: \"ImageDataOrPathType\", mode: Optional[str] = None, caption: Optional[str] = None,", "if data.ndim > 2: data = data.squeeze() # get rid", "None: self._grouping = grouping if caption is not None: self._caption", "= captions all_masks = Image.all_masks(seq, run, key, step) if all_masks:", "examples}) ``` ### Create a wandb.Image from a PILImage <!--yeadoc-test:log-image-pil->", "masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes", "# TODO: We should remove grouping, it's a terrible name", "\"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType = Union[str, \"Image\", ImageDataType]", "None: self_image = list(self_image.getdata()) if other_image is not None: other_image", "\"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType = Union[str, \"Image\", ImageDataType] TorchTensorType", "as PublicArtifact from ..wandb_artifacts import Artifact as LocalArtifact from ..wandb_run", "get_media_subdir(cls: Type[\"Image\"]) -> str: return os.path.join(\"media\", \"images\") def bind_to_run( self,", "uint8, clipping if necessary. \"\"\" np = util.get_module( \"numpy\", required=\"wandb.Image", "BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"),", "dict): raise ValueError('Images \"masks\" argument must be a dictionary') masks_final:", "ValueError( \"Files in an array of Image's must be in", "grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, ) @classmethod def get_media_subdir(cls: Type[\"Image\"]) ->", "user-provided is empty masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"):", "ignore format = jsons[0][\"format\"] def size_equals_image(image: \"Image\") -> bool: img_width,", "vis_util = util.get_module( \"torchvision.utils\", \"torchvision is required to render images\"", "0: data = (data - np.min(data)) / np.ptp(data) if np.max(data)", "isinstance(other, Image): return False else: self_image = self.image other_image =", ") -> None: if grouping is not None: self._grouping =", "= len(seq) width, height = seq[0].image.size # type: ignore format", "# pragma: no cover import matplotlib # type: ignore import", "def guess_mode(self, data: \"np.ndarray\") -> str: \"\"\" Guess what type", "= wbimage._boxes # self._masks = wbimage._masks def _initialize_from_path(self, path: str)", "== other_image and self._classes == other._classes ) def to_data_array(self) ->", "masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None, ) -> None:", "Union[int, str], id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] =", "TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() -> bool: # Newer", "\"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if classes is not None:", "os.path.splitext(path)[1][1:] self.format = ext def _initialize_from_data(self, data: \"ImageDataType\", mode: str", "\"path\": classes_entry.path, \"digest\": classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise", "key: Union[int, str], step: Union[int, str], id_: Optional[Union[int, str]] =", "3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random", "= mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and not all(x", "\"_cls\",) classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"] = { \"type\": \"classes-file\",", "@property def image(self) -> Optional[\"PIL.Image\"]: if self._image is None: if", "\"\"\" if TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run)", "all_masks = Image.all_masks(seq, run, key, step) if all_masks: meta[\"all_masks\"] =", "pillow\".', ) self._set_file(path, is_tmp=False) self._image = pil_image.open(path) self._image.load() ext =", "else: all_box_groups.append(None) if all_box_groups and not all(x is None for", "from pkg_resources import parse_version import wandb from wandb import util", "is None for x in all_box_groups): return all_box_groups else: return", "= data.detach() data = vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0,", "in image._boxes: box = image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else:", "Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = [] for image in images:", "required=\"wandb.Image requires numpy if not supplying PIL Images: pip install", "= seq[0].image.size # type: ignore format = jsons[0][\"format\"] def size_equals_image(image:", "Guess what type of image the np.array is representing \"\"\"", "must be in the {} directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"]", "and img_height == height # type: ignore sizes_match = all(size_equals_image(img)", "None: if isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for val in", "len(seq) width, height = seq[0].image.size # type: ignore format =", "json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] = self.format", "type: ignore from wandb.apis.public import Artifact as PublicArtifact from ..wandb_artifacts", "else None self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) def", "Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = []", "mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and not all(x is", "data.requires_grad: data = data.detach() data = vis_util.make_grid(data, normalize=True) self._image =", "@classmethod def get_media_subdir(cls: Type[\"Image\"]) -> str: return os.path.join(\"media\", \"images\") def", "None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str,", "implicitly copy boxes or masks, just the image-related data. #", "dict]]] = None, ) -> None: if grouping is not", "{} for key in boxes: box_item = boxes[key] if isinstance(box_item,", "None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]]", "pip install numpy\", ) # I think it's better to", "import BoundingBoxes2D from .helper_types.classes import Classes from .helper_types.image_mask import ImageMask", "ImageMask): masks_final[key] = mask_item elif isinstance(mask_item, dict): # TODO: Consider", "self._caption: json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact", "We should remove grouping, it's a terrible name and I", "= {} if boxes: if not isinstance(boxes, dict): raise ValueError('Images", "data: \"np.ndarray\") -> str: \"\"\" Guess what type of image", "enumerate(self._masks): id_ = \"{}{}\".format(id_, i) if id_ is not None", "== 2: return \"L\" elif data.shape[-1] == 3: return \"RGB\"", "= super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] = self.format if", "type: ignore sizes_match = all(size_equals_image(img) for img in seq) if", "issues with this. max_cli_version = util._get_max_cli_version() if max_cli_version is None:", "= wbimage._extension self._sha256 = wbimage._sha256 self._size = wbimage._size self.format =", "Newer versions of wandb accept large image filenames arrays #", "{} for k in image._boxes: box = image._boxes[k] box_group[k] =", "logging to W&B. Arguments: data_or_path: (numpy array, string, io) Accepts", ") -> dict: \"\"\" Combines a list of images into", "_masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes =", "parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images for logging to W&B. Arguments:", "data. # self._boxes = wbimage._boxes # self._masks = wbimage._masks def", "\"ImageMask\"]] def __init__( self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str] = None,", "in classes}) if len(total_classes.keys()) > 0: self._classes = Classes( [", "img in seq) if not sizes_match: logging.warning( \"Images sizes do", "import Classes from .helper_types.image_mask import ImageMask if TYPE_CHECKING: # pragma:", "meta[\"captions\"] = captions all_masks = Image.all_masks(seq, run, key, step) if", "in jsons] else: wandb.termwarn( \"Unable to log image array filenames.", "..wandb_artifacts import Artifact as LocalArtifact from ..wandb_run import Run as", "is_tmp=False) self._image = pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:] self.format =", "\"pip install pillow\".', ) self._image = pil_image.open(self._path) self._image.load() return self._image", "data = (data * 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal", "dict: json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] =", "if data.ndim == 2: return \"L\" elif data.shape[-1] == 3:", "\"LocalArtifact\"]) -> dict: json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type", "box) in self._boxes.items() } if self._masks: json_dict[\"masks\"] = { k:", "None @property def image(self) -> Optional[\"PIL.Image\"]: if self._image is None:", "pkg_resources import parse_version import wandb from wandb import util from", "# type: ignore import torch # type: ignore from wandb.apis.public", "in an array of Image's must be in the {}", "= None if masks: _masks = {} for key in", "UI. Please upgrade your wandb server\", repeat=False, ) captions =", "height, \"format\": format, \"count\": num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"] =", "what type of image the np.array is representing \"\"\" #", "\"ImageDataOrPathType\", mode: Optional[str] = None, caption: Optional[str] = None, grouping:", "not None: if isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for val", "in total_classes.keys() ] ) self._width, self._height = self.image.size # type:", "cases, this can prevent images from being\" \"viewed in the", "_height: Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks:", "= caption total_classes = {} if boxes: if not isinstance(boxes,", "it's better to check the image range vs the data", "isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item, dict): # TODO:", "PIL Images: pip install numpy\", ) # I think it's", "self._image = None @property def image(self) -> Optional[\"PIL.Image\"]: if self._image", "artifact = run_or_artifact if ( self._masks is not None or", "width, \"height\": height, \"format\": format, \"count\": num_images_to_log, } if _server_accepts_image_filenames():", ".helper_types.image_mask import ImageMask if TYPE_CHECKING: # pragma: no cover import", "run \"pip install pillow\".', ) self._set_file(path, is_tmp=False) self._image = pil_image.open(path)", "data = vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2,", ") and self._classes is None: raise ValueError( \"classes must be", "all_boxes return meta @classmethod def all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"],", "injecting top-level classes if user-provided is empty masks_final[key] = ImageMask(mask_item,", "on the range [0,255] to uint8, clipping if necessary. \"\"\"", "boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks:", "Please upgrade your wandb server\", repeat=False, ) captions = Image.all_captions(seq)", "W&B. Arguments: data_or_path: (numpy array, string, io) Accepts numpy array", "num_images_to_log = len(seq) width, height = seq[0].image.size # type: ignore", "> 0: self._classes = Classes( [ {\"id\": key, \"name\": total_classes[key]}", "in all_mask_groups): return all_mask_groups else: return False @classmethod def all_boxes(", "if self._classes is not None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest()", "= None # Allows the user to pass an Image", "elif isinstance(data, pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util =", "else None self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) if", "dictionary object describing the child images. \"\"\" if TYPE_CHECKING: seq", "if not sizes_match: logging.warning( \"Images sizes do not match. This", "= None if boxes: _boxes = {} for key in", "= None self._classes = None self._boxes = None self._masks =", "not match. This will causes images to be display incorrectly", "= masks_final if classes is not None: if isinstance(classes, Classes):", "not None: self._image = None @property def image(self) -> Optional[\"PIL.Image\"]:", ") @classmethod def get_media_subdir(cls: Type[\"Image\"]) -> str: return os.path.join(\"media\", \"images\")", "tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format = \"png\" self._image.save(tmp_path,", "for obj in seq] media_dir = cls.get_media_subdir() for obj in", "[obj[\"path\"] for obj in jsons] else: wandb.termwarn( \"Unable to log", "wandb_run.Run or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact)", "caption, classes, boxes, masks) def _set_initialization_meta( self, grouping: Optional[int] =", "class_name = os.path.join(\"media\", \"classes\", class_id + \"_cls\",) classes_entry = artifact.add(self._classes,", "must be a dictionary') masks_final: Dict[str, ImageMask] = {} for", "format: Optional[str] _grouping: Optional[int] _caption: Optional[str] _width: Optional[int] _height: Optional[int]", "tensors data = data.numpy() if data.ndim > 2: data =", "all_masks: meta[\"all_masks\"] = all_masks all_boxes = Image.all_boxes(seq, run, key, step)", "return not self.__eq__(other) def __eq__(self, other: object) -> bool: if", "images: if image._masks: mask_group = {} for k in image._masks:", "else: all_mask_groups.append(None) if all_mask_groups and not all(x is None for", "BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item, dict): # TODO: Consider", "Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self, other: object) -> bool: return", "bounding boxes when adding to artifacts\" ) if self._classes is", "compelling, we can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path,", "\"torch.Variable\"] def _server_accepts_image_filenames() -> bool: # Newer versions of wandb", "= box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and not all(x", "# type: ignore self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\") -> None:", "(string) The PIL mode for an image. Most common are", "PIL import Image as PILImage import wandb wandb.init() examples =", "json_dict[\"format\"] = self.format if self._width is not None: json_dict[\"width\"] =", "Optional, Sequence, Type, TYPE_CHECKING, Union from pkg_resources import parse_version import", "wandb.log({\"examples\": examples}) ``` ### Create a wandb.Image from a PILImage", "json_dict def guess_mode(self, data: \"np.ndarray\") -> str: \"\"\" Guess what", "seq) jsons = [obj.to_json(run) for obj in seq] media_dir =", "= data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\", \"torchvision is", "total_classes.update({val[\"id\"]: val[\"name\"] for val in classes}) if len(total_classes.keys()) > 0:", "as np import wandb wandb.init() examples = [] for i", "top-level classes if user-provided is empty masks_final[key] = ImageMask(mask_item, key)", "not isinstance(boxes, dict): raise ValueError('Images \"boxes\" argument must be a", "str]] = None, ignore_copy_err: Optional[bool] = None, ) -> None:", "( self._masks is not None or self._boxes is not None", "seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str, step: Union[int, str], )", "is representing \"\"\" # TODO: do we want to support", "util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL package. To get it,", "it, run \"pip install pillow\".', ) self._set_file(path, is_tmp=False) self._image =", "argument must be a dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {}", "a meta dictionary object describing the child images. \"\"\" if", "meta[\"filenames\"] = [obj[\"path\"] for obj in jsons] else: wandb.termwarn( \"Unable", "_initialize_from_data(self, data: \"ImageDataType\", mode: str = None,) -> None: pil_image", "cast, Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Union from pkg_resources", "wbimage._masks def _initialize_from_path(self, path: str) -> None: pil_image = util.get_module(", "data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else: if hasattr(data, \"numpy\"): #", "step) if all_masks: meta[\"all_masks\"] = all_masks all_boxes = Image.all_boxes(seq, run,", "from io import BytesIO import logging import os from typing", "io import BytesIO import logging import os from typing import", "BoundingBoxes2D] = {} for key in boxes: box_item = boxes[key]", "json_dict[\"classes\"] = { \"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest, }", "child images. \"\"\" if TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq) jsons", "in the {} directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"] ) )", "box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and not all(x is", "other: object) -> bool: return not self.__eq__(other) def __eq__(self, other:", "convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path", "= \"image-file\" format: Optional[str] _grouping: Optional[int] _caption: Optional[str] _width: Optional[int]", "= (data * 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal image", "wandb server\", repeat=False, ) captions = Image.all_captions(seq) if captions: meta[\"captions\"]", "a wandb.Image from a PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy as", "return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, ) @classmethod", "cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log = len(seq) width, height =", "np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\")", "List, Optional, Sequence, Type, TYPE_CHECKING, Union from pkg_resources import parse_version", "Image object as the first parameter and have a perfect", "_grouping: Optional[int] _caption: Optional[str] _width: Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"]", "enumerate(self._boxes): id_ = \"{}{}\".format(id_, i) if id_ is not None", "== height # type: ignore sizes_match = all(size_equals_image(img) for img", "size=(100, 100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image =", "self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption,", "class_name) json_dict[\"classes\"] = { \"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest,", "= wbimage._artifact_target # We do not want to implicitly copy", "\"ImageDataType\", mode: str = None,) -> None: pil_image = util.get_module(", "wbimage._sha256 self._size = wbimage._size self.format = wbimage.format self._artifact_source = wbimage._artifact_source", "\"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for display", "BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image =", "val in classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"] for val in", "as LocalArtifact from ..wandb_run import Run as LocalRun ImageDataType =", "if self._image is None: if self._path is not None: pil_image", "\"Image\") -> bool: img_width, img_height = image.image.size # type: ignore", "key: str, step: Union[int, str], ) -> dict: \"\"\" Combines", "else: return False @classmethod def all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"]", "caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, ) @classmethod def get_media_subdir(cls: Type[\"Image\"])", "or self._boxes is not None ) and self._classes is None:", "ext = os.path.splitext(path)[1][1:] self.format = ext def _initialize_from_data(self, data: \"ImageDataType\",", "TODO: Consider injecting top-level classes if user-provided is empty masks_final[key]", "elif isinstance(box_item, dict): # TODO: Consider injecting top-level classes if", "None: data = list(self.image.getdata()) for i in range(self.image.height): res.append(data[i *", ") else: if hasattr(data, \"numpy\"): # TF data eager tensors", "Artifact as LocalArtifact from ..wandb_run import Run as LocalRun ImageDataType", "self.image.width]) self._free_ram() return res def _free_ram(self) -> None: if self._path", "= { \"_type\": \"images/separated\", \"width\": width, \"height\": height, \"format\": format,", "upgrade your wandb server\", repeat=False, ) captions = Image.all_captions(seq) if", "image range vs the data type, since many # image", "and self._classes is None: raise ValueError( \"classes must be passed", "None: self._image = None @property def image(self) -> Optional[\"PIL.Image\"]: if", "[obj.to_json(run) for obj in seq] media_dir = cls.get_media_subdir() for obj", "wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We do not want to", "range vs the data type, since many # image libraries", "and self._caption == other._caption and self._width == other._width and self._height", "first parameter and have a perfect copy, # only overriding", "= pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:] self.format = ext def", "self._path = wbimage._path self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension self._sha256", "data_or_path: (numpy array, string, io) Accepts numpy array of image", "image the np.array is representing \"\"\" # TODO: do we", "parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images for logging to", "for i, k in enumerate(self._boxes): id_ = \"{}{}\".format(id_, i) if", "key in boxes: box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key]", "To get it, run \"pip install pillow\".', ) self._image =", "util._get_max_cli_version() if max_cli_version is None: return False return parse_version(\"0.12.10\") <=", "is not None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name =", "None if masks: _masks = {} for key in masks:", "@classmethod def to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts floating", "None or self._boxes is not None ) and self._classes is", "{\"id\": key, \"name\": total_classes[key]} for key in total_classes.keys() ] )", "str], ) -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = [] for", "for image in images: if image._boxes: box_group = {} for", "self._set_file(path, is_tmp=False) self._image = pil_image.open(path) self._image.load() ext = os.path.splitext(path)[1][1:] self.format", "isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes,", "# Newer versions of wandb accept large image filenames arrays", "self._image = None self._classes = None self._boxes = None self._masks", "= None self._width = None self._height = None self._image =", "not None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL", "-> None: super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is", "passed to wandb.Image which have masks or bounding boxes when", "= None, ) -> None: if grouping is not None:", "get rid of trivial dimensions as a convenience self._image =", "passed in. If this pattern is compelling, we can generalize.", "TODO: We should remove grouping, it's a terrible name and", "ignore import torch # type: ignore from wandb.apis.public import Artifact", "None for x in all_box_groups): return all_box_groups else: return False", "{ k: mask.to_json(run_or_artifact) for (k, mask) in self._masks.items() } return", "self._classes = Classes( [ {\"id\": key, \"name\": total_classes[key]} for key", "wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS = 108 # PIL limit", "def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict = super(Image,", "data format and converts it. mode: (string) The PIL mode", "is compelling, we can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif", "seq = cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run) for obj in", "integer images on the range [0,255] to uint8, clipping if", "Optional[bool] = None, ) -> None: super().bind_to_run(run, key, step, id_,", "not obj[\"path\"].startswith(expected): raise ValueError( \"Files in an array of Image's", "self._boxes = boxes_final if masks: if not isinstance(masks, dict): raise", "3)) image = wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples})", "_width: Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str,", "# TODO: do we want to support dimensions being at", "-> bool: return not self.__eq__(other) def __eq__(self, other: object) ->", "obj[\"path\"] ) ) num_images_to_log = len(seq) width, height = seq[0].image.size", "at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for display of image. Examples:", "import torch # type: ignore from wandb.apis.public import Artifact as", "images. \"\"\" if TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq) jsons =", "incorrectly in the UI.\" ) meta = { \"_type\": \"images/separated\",", "grouping if caption is not None: self._caption = caption total_classes", "BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks: if not", "@classmethod def seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key:", "self).__init__() # TODO: We should remove grouping, it's a terrible", "classes=classes, boxes=_boxes, masks=_masks, ) @classmethod def get_media_subdir(cls: Type[\"Image\"]) -> str:", "Image(BatchableMedia): \"\"\"Format images for logging to W&B. Arguments: data_or_path: (numpy", "is not None: for i, k in enumerate(self._boxes): id_ =", "would have issues with this. max_cli_version = util._get_max_cli_version() if max_cli_version", "json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] = self.format if self._width is not", "have issues with this. max_cli_version = util._get_max_cli_version() if max_cli_version is", "ignore self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\") -> None: self._grouping =", "= jsons[0][\"format\"] def size_equals_image(image: \"Image\") -> bool: img_width, img_height =", "str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]]", "= PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image)", "the {} directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log", "image._boxes: box_group = {} for k in image._boxes: box =", "get it, run \"pip install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf", "if self._masks is not None: for i, k in enumerate(self._masks):", "data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run:", "user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes =", "self._masks.items() } return json_dict def guess_mode(self, data: \"np.ndarray\") -> str:", "{ k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items() } if", "k in image._masks: mask = image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group)", "np.ptp(data) if np.max(data) <= 1.0: data = (data * 255).astype(np.int32)", "source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str,", "Artifact as PublicArtifact from ..wandb_artifacts import Artifact as LocalArtifact from", "box = image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if", "4: return \"RGBA\" else: raise ValueError( \"Un-supported shape for image", "if all_box_groups and not all(x is None for x in", "_masks: Optional[Dict[str, \"ImageMask\"]] def __init__( self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str]", "box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif", "dimensions being at the beginning of the array? if data.ndim", "of wandb accept large image filenames arrays # but older", "anyone uses it. self._grouping = None self._caption = None self._width", "import MEDIA_TMP from .base_types.media import BatchableMedia, Media from .helper_types.bounding_boxes_2d import", "want to support dimensions being at the beginning of the", "List[Any]: res = [] if self.image is not None: data", "Image._log_type json_dict[\"format\"] = self.format if self._width is not None: json_dict[\"width\"]", "array of image data, or a PIL image. The class", "self.image.width : (i + 1) * self.image.width]) self._free_ram() return res", "in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8)", "def get_media_subdir(cls: Type[\"Image\"]) -> str: return os.path.join(\"media\", \"images\") def bind_to_run(", "mode: Optional[str] = None, caption: Optional[str] = None, grouping: Optional[int]", "data = list(self.image.getdata()) for i in range(self.image.height): res.append(data[i * self.image.width", "run, key, step, id_, ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact: Union[\"LocalRun\",", "i in range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3),", "os.path.join(\"media\", \"images\") def bind_to_run( self, run: \"LocalRun\", key: Union[int, str],", "None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL package.", "if masks: if not isinstance(masks, dict): raise ValueError('Images \"masks\" argument", "= None self._height = None self._image = None self._classes =", "for i, k in enumerate(self._masks): id_ = \"{}{}\".format(id_, i) if", "logging import os from typing import Any, cast, Dict, List,", "self._width == other._width and self._height == other._height and self_image ==", "as PILImage import wandb wandb.init() examples = [] for i", "artifacts\" ) if self._classes is not None: class_id = hashlib.md5(", "= \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def from_json( cls:", "format.' return data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json( cls: Type[\"Image\"], seq:", "_classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def __init__(", "self._width = wbimage._width self._height = wbimage._height self._image = wbimage._image self._classes", "np.random.randint(low=0, high=256, size=(100, 100, 3)) image = wandb.Image(pixels, caption=f\"random field", "def __init__( self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str] = None, caption:", "boxes_final if masks: if not isinstance(masks, dict): raise ValueError('Images \"masks\"", "\"LocalRun\", run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]:", "Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\" ) -> \"Image\": classes =", "def __ne__(self, other: object) -> bool: return not self.__eq__(other) def", "boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None if boxes:", "else: raise ValueError( \"Un-supported shape for image conversion %s\" %", "the UI.\" ) meta = { \"_type\": \"images/separated\", \"width\": width,", "] ImageDataOrPathType = Union[str, \"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"]", "all_boxes: meta[\"all_boxes\"] = all_boxes return meta @classmethod def all_masks( cls:", "= {} for k in image._boxes: box = image._boxes[k] box_group[k]", "box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and not", "box_item elif isinstance(box_item, dict): # TODO: Consider injecting top-level classes", "ext def _initialize_from_data(self, data: \"ImageDataType\", mode: str = None,) ->", "support dimensions being at the beginning of the array? if", "np.max(data) <= 1.0: data = (data * 255).astype(np.int32) # assert", "metdata passed in. If this pattern is compelling, we can", "grouping: Optional[int] = None, caption: Optional[str] = None, classes: Optional[Union[\"Classes\",", "if max_cli_version is None: return False return parse_version(\"0.12.10\") <= parse_version(max_cli_version)", "mask) in self._masks.items() } return json_dict def guess_mode(self, data: \"np.ndarray\")", "== 4: return \"RGBA\" else: raise ValueError( \"Un-supported shape for", "return all_mask_groups else: return False @classmethod def all_boxes( cls: Type[\"Image\"],", "pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else: if hasattr(data, \"numpy\"):", "{i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS = 108 #", "0: self._classes = Classes( [ {\"id\": key, \"name\": total_classes[key]} for", "None: if self._path is not None: self._image = None @property", "mask_group = {} for k in image._masks: mask = image._masks[k]", "return \"RGBA\" else: raise ValueError( \"Un-supported shape for image conversion", "_image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]]", "on the range [0,1] and integer images on the range", "source_artifact: \"PublicArtifact\" ) -> \"Image\": classes = None if json_obj.get(\"classes\")", "if len(total_classes.keys()) > 0: self._classes = Classes( [ {\"id\": key,", "key, step) if all_masks: meta[\"all_masks\"] = all_masks all_boxes = Image.all_boxes(seq,", "total_classes[key]} for key in total_classes.keys() ] ) self._width, self._height =", "k in enumerate(self._masks): id_ = \"{}{}\".format(id_, i) if id_ is", "key, step, id_, ignore_copy_err=ignore_copy_err ) if self._masks is not None:", "img_height == height # type: ignore sizes_match = all(size_equals_image(img) for", "str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\", \"classes\", class_id + \"_cls\",) classes_entry", "data, or a PIL image. The class attempts to infer", "meta[\"all_masks\"] = all_masks all_boxes = Image.all_boxes(seq, run, key, step) if", "for i in range(self.image.height): res.append(data[i * self.image.width : (i +", "total_classes.update( {val[\"id\"]: val[\"name\"] for val in classes._class_set} ) else: total_classes.update({val[\"id\"]:", "check the image range vs the data type, since many", "beginning of the array? if data.ndim == 2: return \"L\"", "self_image == other_image and self._classes == other._classes ) def to_data_array(self)", "meta[\"all_boxes\"] = all_boxes return meta @classmethod def all_masks( cls: Type[\"Image\"],", "data.shape[-1] == 3: return \"RGB\" elif data.shape[-1] == 4: return", "masks: _masks = {} for key in masks: _masks[key] =", "= os.path.join(\"media\", \"classes\", class_id + \"_cls\",) classes_entry = artifact.add(self._classes, class_name)", "= { k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items() }", "str], step: Union[int, str], id_: Optional[Union[int, str]] = None, ignore_copy_err:", "type: ignore return img_width == width and img_height == height", "Optional[\"PIL.Image\"]: if self._image is None: if self._path is not None:", "= 108 # PIL limit MAX_DIMENSION = 65500 _log_type =", "Optional[str] _grouping: Optional[int] _caption: Optional[str] _width: Optional[int] _height: Optional[int] _image:", "str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]]", "jsons = [obj.to_json(run) for obj in seq] media_dir = cls.get_media_subdir()", "{} for key in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact)", "classes is not None: if isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"]", "\"Unable to log image array filenames. In some cases, this", "isinstance(mask_item, dict): # TODO: Consider injecting top-level classes if user-provided", "self.format = wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target #", "\"LocalRun\", key: Union[int, str], step: Union[int, str], id_: Optional[Union[int, str]]", "is not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks:", "and self_image == other_image and self._classes == other._classes ) def", "Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str,", "= None @property def image(self) -> Optional[\"PIL.Image\"]: if self._image is", "as np # type: ignore import PIL # type: ignore", "\"images\") def bind_to_run( self, run: \"LocalRun\", key: Union[int, str], step:", "other._width and self._height == other._height and self_image == other_image and", "is None: if self._path is not None: pil_image = util.get_module(", "import parse_version import wandb from wandb import util from ._private", "examples.append(image) wandb.log({\"examples\": examples}) ``` ### Create a wandb.Image from a", "pass an Image object as the first parameter and have", "PIL image. The class attempts to infer the data format", "100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image,", "explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for display of image.", "torch # type: ignore from wandb.apis.public import Artifact as PublicArtifact", "from a numpy array <!--yeadoc-test:log-image-numpy-> ```python import numpy as np", "not None else None self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err", "image libraries will return floats between 0 and 255 #", "self._caption = wbimage._caption self._width = wbimage._width self._height = wbimage._height self._image", "vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() )", "grouping is not None: self._grouping = grouping if caption is", "type: ignore self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\") -> None: self._grouping", "list(self.image.getdata()) for i in range(self.image.height): res.append(data[i * self.image.width : (i", "class Image(BatchableMedia): \"\"\"Format images for logging to W&B. Arguments: data_or_path:", "the data type, since many # image libraries will return", "hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if classes is not", "many # image libraries will return floats between 0 and", "all_box_groups: List[Optional[dict]] = [] for image in images: if image._boxes:", "dimensions as a convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or", "elif isinstance(mask_item, dict): # TODO: Consider injecting top-level classes if", "os from typing import Any, cast, Dict, List, Optional, Sequence,", "= None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] = None, masks:", "PIL # type: ignore import torch # type: ignore from", "\"Image\": classes = None if json_obj.get(\"classes\") is not None: classes", "Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Union from pkg_resources import", "The class attempts to infer the data format and converts", "key, step, id_, ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"])", "other: object) -> bool: if not isinstance(other, Image): return False", "_boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return cls( source_artifact.get_path(json_obj[\"path\"]).download(),", "libraries will return floats between 0 and 255 # some", "no cover import matplotlib # type: ignore import numpy as", "_free_ram(self) -> None: if self._path is not None: self._image =", "a convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) )", "image format.' return data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json( cls: Type[\"Image\"],", "os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format = \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path,", "https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for display of image. Examples: ###", "(k, mask) in self._masks.items() } return json_dict def guess_mode(self, data:", "import ImageMask if TYPE_CHECKING: # pragma: no cover import matplotlib", "from .helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes import Classes from .helper_types.image_mask", "data: \"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts floating point image on", "%s\" % list(data.shape) ) @classmethod def to_uint8(cls, data: \"np.ndarray\") ->", "self._caption = caption total_classes = {} if boxes: if not", "# Allows the user to pass an Image object as", "in image._masks: mask = image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else:", "should remove grouping, it's a terrible name and I don't", "all(x is None for x in all_mask_groups): return all_mask_groups else:", "pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random field {i}\")", "bool: return not self.__eq__(other) def __eq__(self, other: object) -> bool:", "image = wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ```", "return img_width == width and img_height == height # type:", "mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and not", "Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step: Union[int, str],", "other._caption and self._width == other._width and self._height == other._height and", "all_mask_groups: List[Optional[dict]] = [] for image in images: if image._masks:", "if id_ is not None else None self._masks[k].bind_to_run( run, key,", "Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() -> bool: # Newer versions of", "-> None: if self._path is not None: self._image = None", "the image-related data. # self._boxes = wbimage._boxes # self._masks =", "in seq) if not sizes_match: logging.warning( \"Images sizes do not", "= wbimage._width self._height = wbimage._height self._image = wbimage._image self._classes =", "key in total_classes.keys() ] ) self._width, self._height = self.image.size #", "raise ValueError( \"classes must be passed to wandb.Image which have", "attempts to infer the data format and converts it. mode:", "self.format = ext def _initialize_from_data(self, data: \"ImageDataType\", mode: str =", "install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image", "-> str: \"\"\" Guess what type of image the np.array", "image in images: if image._boxes: box_group = {} for k", "i, k in enumerate(self._boxes): id_ = \"{}{}\".format(id_, i) if id_", "MAX_DIMENSION = 65500 _log_type = \"image-file\" format: Optional[str] _grouping: Optional[int]", "ignore return img_width == width and img_height == height #", "# think anyone uses it. self._grouping = None self._caption =", "wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We do", "supplying PIL Images: pip install numpy\", ) # I think", "bool: # Newer versions of wandb accept large image filenames", "self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format =", "self._masks: json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact) for (k, mask) in", ") -> None: super(Image, self).__init__() # TODO: We should remove", "if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if classes is", "{} directory, not {}\".format( cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log =", ") if self._masks is not None: for i, k in", "= hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\", \"classes\", class_id +", "between 0 and 255 # some images have range -1...1", "other_image and self._classes == other._classes ) def to_data_array(self) -> List[Any]:", "% list(data.shape) ) @classmethod def to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\":", "self._masks is not None or self._boxes is not None )", "format = jsons[0][\"format\"] def size_equals_image(image: \"Image\") -> bool: img_width, img_height", "None if json_obj.get(\"classes\") is not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks", "to log image array filenames. In some cases, this can", "Sequence, Type, TYPE_CHECKING, Union from pkg_resources import parse_version import wandb", "= other.image if self_image is not None: self_image = list(self_image.getdata())", "elif data.shape[-1] == 3: return \"RGB\" elif data.shape[-1] == 4:", "we can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str):", "= list(other_image.getdata()) return ( self._grouping == other._grouping and self._caption ==", "\"\"\" Combines a list of images into a meta dictionary", "Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for val in classes._class_set} ) else:", "type: ignore format = jsons[0][\"format\"] def size_equals_image(image: \"Image\") -> bool:", "i) if id_ is not None else None self._boxes[k].bind_to_run( run,", "filenames. In some cases, this can prevent images from being\"", "self, run: \"LocalRun\", key: Union[int, str], step: Union[int, str], id_:", "all_mask_groups and not all(x is None for x in all_mask_groups):", "None, caption: Optional[str] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None,", "are \"L\", \"RGB\", \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string)", "step, id_, ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) ->", "100, 3)) image = wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\":", "it's a terrible name and I don't # think anyone", "util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image = data", "for img in seq) if not sizes_match: logging.warning( \"Images sizes", "in. If this pattern is compelling, we can generalize. if", "wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` ### Create", "import BytesIO import logging import os from typing import Any,", "data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\", \"torchvision is required", "isinstance(boxes, dict): raise ValueError('Images \"boxes\" argument must be a dictionary')", "+ 1) * self.image.width]) self._free_ram() return res def _free_ram(self) ->", "= {} for key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact)", "data type, since many # image libraries will return floats", "masks_final if classes is not None: if isinstance(classes, Classes): total_classes.update(", "None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str,", "terrible name and I don't # think anyone uses it.", "source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, ) @classmethod def get_media_subdir(cls:", "do we want to support dimensions being at the beginning", "\"numpy\"): # TF data eager tensors data = data.numpy() if", "not all(x is None for x in all_box_groups): return all_box_groups", "for key in masks: mask_item = masks[key] if isinstance(mask_item, ImageMask):", "None else None self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err )", "= wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We", "be a dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {} for key", "k in enumerate(self._boxes): id_ = \"{}{}\".format(id_, i) if id_ is", "\"\"\" MAX_ITEMS = 108 # PIL limit MAX_DIMENSION = 65500", "None: if self._path is not None: pil_image = util.get_module( \"PIL.Image\",", "json_obj: dict, source_artifact: \"PublicArtifact\" ) -> \"Image\": classes = None", "super(Image, self).__init__() # TODO: We should remove grouping, it's a", "it. mode: (string) The PIL mode for an image. Most", "Dict[str, BoundingBoxes2D] = {} for key in boxes: box_item =", "ImageMask]] = None if masks: _masks = {} for key", "pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image =", "= run_or_artifact if ( self._masks is not None or self._boxes", "accept large image filenames arrays # but older versions would", "image._masks: mask_group = {} for k in image._masks: mask =", "= self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if (", "= BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks: if", "= None, caption: Optional[str] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] =", "Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] =", "Optional[Dict[str, BoundingBoxes2D]] = None if boxes: _boxes = {} for", "\".png\") self.format = \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def", "an array of Image's must be in the {} directory,", "in seq] media_dir = cls.get_media_subdir() for obj in jsons: expected", "injecting top-level classes if user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item,", "in images: if image._masks: mask_group = {} for k in", "self._grouping = grouping if caption is not None: self._caption =", "self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\", \"torchvision", "logging.warning( \"Images sizes do not match. This will causes images", "LocalArtifact from ..wandb_run import Run as LocalRun ImageDataType = Union[", "remove grouping, it's a terrible name and I don't #", "for key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key =", "None, grouping: Optional[int] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None,", "isinstance(box_item, dict): # TODO: Consider injecting top-level classes if user-provided", "-> None: self._grouping = wbimage._grouping self._caption = wbimage._caption self._width =", "elif data.shape[-1] == 4: return \"RGBA\" else: raise ValueError( \"Un-supported", "for val in classes}) if len(total_classes.keys()) > 0: self._classes =", "2: return \"L\" elif data.shape[-1] == 3: return \"RGB\" elif", "= wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\"", "if hasattr(data, \"numpy\"): # TF data eager tensors data =", "Classes from .helper_types.image_mask import ImageMask if TYPE_CHECKING: # pragma: no", "image._masks[k] mask_group[k] = mask.to_json(run) all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and", "None self._width = None self._height = None self._image = None", "id_ = \"{}{}\".format(id_, i) if id_ is not None else", "str) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the", "def _set_initialization_meta( self, grouping: Optional[int] = None, caption: Optional[str] =", "get it, run \"pip install pillow\".', ) self._image = pil_image.open(self._path)", "val in classes}) if len(total_classes.keys()) > 0: self._classes = Classes(", "will causes images to be display incorrectly in the UI.\"", "raise ValueError( \"Un-supported shape for image conversion %s\" % list(data.shape)", "- np.min(data)) / np.ptp(data) if np.max(data) <= 1.0: data =", "= json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None if boxes: _boxes", "None: super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is not", "boxes or masks, just the image-related data. # self._boxes =", "seq] media_dir = cls.get_media_subdir() for obj in jsons: expected =", "of images into a meta dictionary object describing the child", "run: \"LocalRun\", run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]],", "the user to pass an Image object as the first", "self._extension = wbimage._extension self._sha256 = wbimage._sha256 self._size = wbimage._size self.format", "None self._boxes = None self._masks = None # Allows the", "not None or self._boxes is not None ) and self._classes", "False return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images for", "_boxes[key]._key = key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes,", "range [0,255] to uint8, clipping if necessary. \"\"\" np =", "ImageDataOrPathType = Union[str, \"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def", "* self.image.width : (i + 1) * self.image.width]) self._free_ram() return", "PIL package. To get it, run \"pip install pillow\".', )", "return json_dict def guess_mode(self, data: \"np.ndarray\") -> str: \"\"\" Guess", "json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] = None if masks: _masks =", "return all_box_groups else: return False @classmethod def all_captions( cls: Type[\"Image\"],", "False @classmethod def all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\",", "classes_entry.path, \"digest\": classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json", "when adding to artifacts\" ) if self._classes is not None:", "# type: ignore format = jsons[0][\"format\"] def size_equals_image(image: \"Image\") ->", "\"torchvision is required to render images\" ) if hasattr(data, \"requires_grad\")", ".helper_types.classes import Classes from .helper_types.image_mask import ImageMask if TYPE_CHECKING: #", "match. This will causes images to be display incorrectly in", "-> bool: if not isinstance(other, Image): return False else: self_image", "with this. max_cli_version = util._get_max_cli_version() if max_cli_version is None: return", "Dict[str, dict]]] = None, ) -> None: if grouping is", "_caption: Optional[str] _width: Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"]", "str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] = [] for", "all_box_groups else: return False @classmethod def all_captions( cls: Type[\"Image\"], images:", "elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes,", "if all_masks: meta[\"all_masks\"] = all_masks all_boxes = Image.all_boxes(seq, run, key,", "obj in jsons] else: wandb.termwarn( \"Unable to log image array", "for image in images: if image._masks: mask_group = {} for", "self._classes == other._classes ) def to_data_array(self) -> List[Any]: res =", "PILImage import wandb wandb.init() examples = [] for i in", "_masks = {} for key in masks: _masks[key] = ImageMask.from_json(masks[key],", "box_group = {} for k in image._boxes: box = image._boxes[k]", "* self.image.width]) self._free_ram() return res def _free_ram(self) -> None: if", "high=256, size=(100, 100, 3)) image = wandb.Image(pixels, caption=f\"random field {i}\")", "wandb.Image from a numpy array <!--yeadoc-test:log-image-numpy-> ```python import numpy as", "Most common are \"L\", \"RGB\", \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes.", "images: if image._boxes: box_group = {} for k in image._boxes:", "= Image.all_captions(seq) if captions: meta[\"captions\"] = captions all_masks = Image.all_masks(seq,", "= np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels,", "raise ValueError( \"Files in an array of Image's must be", "Image as PILImage import wandb wandb.init() examples = [] for", "# type: ignore from wandb.apis.public import Artifact as PublicArtifact from", "package. To get it, run \"pip install pillow\".', ) self._set_file(path,", "image = wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ```", "_server_accepts_image_filenames() -> bool: # Newer versions of wandb accept large", "os.path.join(\"media\", \"classes\", class_id + \"_cls\",) classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"]", "= masks[key] if isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif isinstance(mask_item,", "__ne__(self, other: object) -> bool: return not self.__eq__(other) def __eq__(self,", "of image data, or a PIL image. The class attempts", "data.squeeze() # get rid of trivial dimensions as a convenience", "class attempts to infer the data format and converts it.", "numpy if not supplying PIL Images: pip install numpy\", )", "bool]: all_box_groups: List[Optional[dict]] = [] for image in images: if", "if self.image is not None: data = list(self.image.getdata()) for i", "boxes=_boxes, masks=_masks, ) @classmethod def get_media_subdir(cls: Type[\"Image\"]) -> str: return", "self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We do not", "is not None: self._caption = caption total_classes = {} if", "since many # image libraries will return floats between 0", "caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS =", "all_masks all_boxes = Image.all_boxes(seq, run, key, step) if all_boxes: meta[\"all_boxes\"]", "isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode)", "BytesIO import logging import os from typing import Any, cast,", "numpy array <!--yeadoc-test:log-image-numpy-> ```python import numpy as np import wandb", ") tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format = \"png\"", "if ( self._masks is not None or self._boxes is not", "not want to implicitly copy boxes or masks, just the", "of image. Examples: ### Create a wandb.Image from a numpy", "\"name\": total_classes[key]} for key in total_classes.keys() ] ) self._width, self._height", "\"\"\"Format images for logging to W&B. Arguments: data_or_path: (numpy array,", "-> \"np.ndarray\": \"\"\" Converts floating point image on the range", "None self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) def to_json(self,", "adding to artifacts\" ) if self._classes is not None: class_id", "None: json_dict[\"width\"] = self._width if self._height is not None: json_dict[\"height\"]", "from typing import Any, cast, Dict, List, Optional, Sequence, Type,", "-> Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self, other: object) ->", "(k, box) in self._boxes.items() } if self._masks: json_dict[\"masks\"] = {", "Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] = None, ) ->", "} elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run or", "= ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final", "Union[int, str], step: Union[int, str], id_: Optional[Union[int, str]] = None,", "str: \"\"\" Guess what type of image the np.array is", "{}\".format( cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log = len(seq) width, height", "np # type: ignore import PIL # type: ignore import", "not None: data = list(self.image.getdata()) for i in range(self.image.height): res.append(data[i", "run \"pip install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO()", "= ext def _initialize_from_data(self, data: \"ImageDataType\", mode: str = None,)", "str, step: Union[int, str], ) -> dict: \"\"\" Combines a", "\"count\": num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for obj", "self._grouping if self._caption: json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact", "the np.array is representing \"\"\" # TODO: do we want", "self.__eq__(other) def __eq__(self, other: object) -> bool: if not isinstance(other,", "clipping if necessary. \"\"\" np = util.get_module( \"numpy\", required=\"wandb.Image requires", "Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step: Union[int, str], ) ->", "Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def __init__( self,", ") def to_data_array(self) -> List[Any]: res = [] if self.image", "mode: (string) The PIL mode for an image. Most common", "util.get_module( \"torchvision.utils\", \"torchvision is required to render images\" ) if", "PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\":", "self._sha256 = wbimage._sha256 self._size = wbimage._size self.format = wbimage.format self._artifact_source", "if self._path is not None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image", "step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] =", "classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run", "not None: self_image = list(self_image.getdata()) if other_image is not None:", "pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL package. To", "None else None self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err )", "in boxes: box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] =", "classes._class_set} ) else: total_classes.update({val[\"id\"]: val[\"name\"] for val in classes}) if", "= BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"),", "total_classes = {} if boxes: if not isinstance(boxes, dict): raise", "return \"RGB\" elif data.shape[-1] == 4: return \"RGBA\" else: raise", "in masks: _masks[key] = ImageMask.from_json(masks[key], source_artifact) _masks[key]._set_artifact_source(source_artifact) _masks[key]._key = key", "not None ) and self._classes is None: raise ValueError( \"classes", "+ \".png\") self.format = \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod", "type: ignore import PIL # type: ignore import torch #", "Any, cast, Dict, List, Optional, Sequence, Type, TYPE_CHECKING, Union from", "to W&B. Arguments: data_or_path: (numpy array, string, io) Accepts numpy", "(data * 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal image format.'", "images into a meta dictionary object describing the child images.", "( self._grouping == other._grouping and self._caption == other._caption and self._width", "in self._boxes.items() } if self._masks: json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact)", "= cls.get_media_subdir() for obj in jsons: expected = util.to_forward_slash_path(media_dir) if", "ignore sizes_match = all(size_equals_image(img) for img in seq) if not", "boxes: box_item = boxes[key] if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item", "None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\", \"classes\",", "masks: if not isinstance(masks, dict): raise ValueError('Images \"masks\" argument must", "\"LocalRun\", key: str, step: Union[int, str], ) -> dict: \"\"\"", "np.array is representing \"\"\" # TODO: do we want to", "x in all_box_groups): return all_box_groups else: return False @classmethod def", ") if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf)", "image. Most common are \"L\", \"RGB\", \"RGBA\". Full explanation at", "floating point image on the range [0,1] and integer images", "return floats between 0 and 255 # some images have", "matplotlib # type: ignore import numpy as np # type:", "[] for image in images: if image._masks: mask_group = {}", "all(x is None for x in all_box_groups): return all_box_groups else:", "wandb.termwarn( \"Unable to log image array filenames. In some cases,", "or a PIL image. The class attempts to infer the", "grouping: Optional[int] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes:", "describing the child images. \"\"\" if TYPE_CHECKING: seq = cast(Sequence[\"Image\"],", "id_, ignore_copy_err=ignore_copy_err) if self._boxes is not None: for i, k", "255).astype(np.uint8) @classmethod def seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\",", "TODO: Consider injecting top-level classes if user-provided is empty boxes_final[key]", "range(3): pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) image =", "Union from pkg_resources import parse_version import wandb from wandb import", "in the UI.\" ) meta = { \"_type\": \"images/separated\", \"width\":", "Combines a list of images into a meta dictionary object", "dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {} for key in boxes:", "pixels = np.random.randint(low=0, high=256, size=(100, 100, 3)) image = wandb.Image(pixels,", "\"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def from_json( cls: Type[\"Image\"],", "return res def _free_ram(self) -> None: if self._path is not", "Image.all_masks(seq, run, key, step) if all_masks: meta[\"all_masks\"] = all_masks all_boxes", "Optional[str] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str,", "None: for i, k in enumerate(self._masks): id_ = \"{}{}\".format(id_, i)", "def to_data_array(self) -> List[Any]: res = [] if self.image is", "None: self._caption = caption total_classes = {} if boxes: if", "255 # some images have range -1...1 or 0-1 dmin", "import numpy as np import wandb wandb.init() examples = []", "for logging to W&B. Arguments: data_or_path: (numpy array, string, io)", "self._boxes[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) if self._masks is", "repeat=False, ) captions = Image.all_captions(seq) if captions: meta[\"captions\"] = captions", "for obj in jsons] else: wandb.termwarn( \"Unable to log image", "= grouping if caption is not None: self._caption = caption", "self._path is not None: self._image = None @property def image(self)", "it, run \"pip install pillow\".', ) self._image = pil_image.open(self._path) self._image.load()", "images\" ) if hasattr(data, \"requires_grad\") and data.requires_grad: data = data.detach()", "range -1...1 or 0-1 dmin = np.min(data) if dmin <", "{} for k in image._masks: mask = image._masks[k] mask_group[k] =", "\"RGB\", \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label for", "this pattern is compelling, we can generalize. if isinstance(data_or_path, Image):", "self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path =", "Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType = Union[str, \"Image\",", "necessary. \"\"\" np = util.get_module( \"numpy\", required=\"wandb.Image requires numpy if", "-> None: if grouping is not None: self._grouping = grouping", "accepts wandb_run.Run or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] = { k:", "classes if user-provided is empty masks_final[key] = ImageMask(mask_item, key) if", "= wbimage._size self.format = wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target =", "\"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def __init__( self, data_or_path: \"ImageDataOrPathType\", mode:", "image array filenames. In some cases, this can prevent images", "\"Image\") -> None: self._grouping = wbimage._grouping self._caption = wbimage._caption self._width", "\"Un-supported shape for image conversion %s\" % list(data.shape) ) @classmethod", "io) Accepts numpy array of image data, or a PIL", "= wbimage._classes self._path = wbimage._path self._is_tmp = wbimage._is_tmp self._extension =", "= artifact.add(self._classes, class_name) json_dict[\"classes\"] = { \"type\": \"classes-file\", \"path\": classes_entry.path,", "``` \"\"\" MAX_ITEMS = 108 # PIL limit MAX_DIMENSION =", "and not all(x is None for x in all_mask_groups): return", "Union[str, \"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() ->", "\"classes must be passed to wandb.Image which have masks or", "if TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run) for", "\"BoundingBoxes2D\"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]]", "have a perfect copy, # only overriding additional metdata passed", "to wandb.Image which have masks or bounding boxes when adding", "= {} for key in masks: mask_item = masks[key] if", "of the array? if data.ndim == 2: return \"L\" elif", "dmin < 0: data = (data - np.min(data)) / np.ptp(data)", "\"\"\" # TODO: do we want to support dimensions being", "bind_to_run( self, run: \"LocalRun\", key: Union[int, str], step: Union[int, str],", "_boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def __init__( self, data_or_path:", "= all_boxes return meta @classmethod def all_masks( cls: Type[\"Image\"], images:", "self._width = None self._height = None self._image = None self._classes", "source_artifact) _boxes[key]._key = key return cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes,", "is not None else None self._boxes[k].bind_to_run( run, key, step, id_,", "the range [0,1] and integer images on the range [0,255]", "numpy array of image data, or a PIL image. The", "Type[\"Image\"], images: Sequence[\"Media\"] ) -> Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def", "\"PublicArtifact\" ) -> \"Image\": classes = None if json_obj.get(\"classes\") is", "= Union[str, \"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames()", "wbimage._grouping self._caption = wbimage._caption self._width = wbimage._width self._height = wbimage._height", "= None, ) -> None: super(Image, self).__init__() # TODO: We", "of trivial dimensions as a convenience self._image = pil_image.fromarray( self.to_uint8(data),", "a PILImage <!--yeadoc-test:log-image-pil-> ```python import numpy as np from PIL", "not None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name = os.path.join(\"media\",", "images to be display incorrectly in the UI.\" ) meta", "# self._boxes = wbimage._boxes # self._masks = wbimage._masks def _initialize_from_path(self,", "\"requires_grad\") and data.requires_grad: data = data.detach() data = vis_util.make_grid(data, normalize=True)", "step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_mask_groups: List[Optional[dict]] =", "if other_image is not None: other_image = list(other_image.getdata()) return (", "other_image is not None: other_image = list(other_image.getdata()) return ( self._grouping", "np import wandb wandb.init() examples = [] for i in", "= None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"],", "cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step: Union[int,", "2: data = data.squeeze() # get rid of trivial dimensions", "self._boxes is not None: for i, k in enumerate(self._boxes): id_", "I think it's better to check the image range vs", "id_ is not None else None self._boxes[k].bind_to_run( run, key, step,", "for display of image. Examples: ### Create a wandb.Image from", "def from_json( cls: Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\" ) ->", "render images\" ) if hasattr(data, \"requires_grad\") and data.requires_grad: data =", "object as the first parameter and have a perfect copy,", "import hashlib from io import BytesIO import logging import os", "None ) and self._classes is None: raise ValueError( \"classes must", "wandb.Image(pil_image, caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` \"\"\" MAX_ITEMS", "super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes is not None:", "= None self._boxes = None self._masks = None # Allows", "normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else:", "examples}) ``` \"\"\" MAX_ITEMS = 108 # PIL limit MAX_DIMENSION", "masks_final: Dict[str, ImageMask] = {} for key in masks: mask_item", "[] if self.image is not None: data = list(self.image.getdata()) for", "if image._boxes: box_group = {} for k in image._boxes: box", "run: \"LocalRun\", key: Union[int, str], step: Union[int, str], id_: Optional[Union[int,", "str(util.generate_id()) + \".png\") self.format = \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True)", "high=256, size=(100, 100, 3), dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image", "PIL limit MAX_DIMENSION = 65500 _log_type = \"image-file\" format: Optional[str]", "floats between 0 and 255 # some images have range", "is not None: if isinstance(classes, Classes): total_classes.update( {val[\"id\"]: val[\"name\"] for", "media_dir = cls.get_media_subdir() for obj in jsons: expected = util.to_forward_slash_path(media_dir)", "if util.is_matplotlib_typename(util.get_full_typename(data)): buf = BytesIO() util.ensure_matplotlib_figure(data).savefig(buf) self._image = pil_image.open(buf) elif", "= util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL package. To get", "install pillow\".', ) self._set_file(path, is_tmp=False) self._image = pil_image.open(path) self._image.load() ext", "is required to render images\" ) if hasattr(data, \"requires_grad\") and", "ignore from wandb.apis.public import Artifact as PublicArtifact from ..wandb_artifacts import", ") num_images_to_log = len(seq) width, height = seq[0].image.size # type:", "caption: Optional[str] = None, classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes:", "\"np.ndarray\") -> \"np.ndarray\": \"\"\" Converts floating point image on the", "format, \"count\": num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for", "if dmin < 0: data = (data - np.min(data)) /", "UI.\" ) meta = { \"_type\": \"images/separated\", \"width\": width, \"height\":", "from .helper_types.classes import Classes from .helper_types.image_mask import ImageMask if TYPE_CHECKING:", "self._grouping == other._grouping and self._caption == other._caption and self._width ==", "from .helper_types.image_mask import ImageMask if TYPE_CHECKING: # pragma: no cover", "Union[bool, Sequence[Optional[str]]]: return cls.captions(images) def __ne__(self, other: object) -> bool:", "res def _free_ram(self) -> None: if self._path is not None:", "= [] for image in images: if image._boxes: box_group =", "pil_image.Image): self._image = data elif util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\",", "list of images into a meta dictionary object describing the", "np.min(data) if dmin < 0: data = (data - np.min(data))", "= None if json_obj.get(\"classes\") is not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"])", "_boxes = {} for key in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key],", "# get rid of trivial dimensions as a convenience self._image", "be display incorrectly in the UI.\" ) meta = {", "@classmethod def all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key:", "x in all_mask_groups): return all_mask_groups else: return False @classmethod def", "False @classmethod def all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"] ) ->", "self._height if self._grouping: json_dict[\"grouping\"] = self._grouping if self._caption: json_dict[\"caption\"] =", "-> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = [] for image in", "== width and img_height == height # type: ignore sizes_match", "# TF data eager tensors data = data.numpy() if data.ndim", "wandb.apis.public import Artifact as PublicArtifact from ..wandb_artifacts import Artifact as", "jsons: expected = util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise ValueError( \"Files", "not supplying PIL Images: pip install numpy\", ) # I", "Image.all_captions(seq) if captions: meta[\"captions\"] = captions all_masks = Image.all_masks(seq, run,", "\"L\", \"RGB\", \"RGBA\". Full explanation at https://pillow.readthedocs.io/en/4.2.x/handbook/concepts.html#concept-modes. caption: (string) Label", "to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict = super(Image, self).to_json(run_or_artifact)", "Optional[int] _height: Optional[int] _image: Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]]", "wbimage._artifact_target # We do not want to implicitly copy boxes", "type: ignore import numpy as np # type: ignore import", "sizes_match: logging.warning( \"Images sizes do not match. This will causes", "all_box_groups): return all_box_groups else: return False @classmethod def all_captions( cls:", "if necessary. \"\"\" np = util.get_module( \"numpy\", required=\"wandb.Image requires numpy", "for key in total_classes.keys() ] ) self._width, self._height = self.image.size", "be passed to wandb.Image which have masks or bounding boxes", "run, key, step, id_, ignore_copy_err=ignore_copy_err ) if self._masks is not", "cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run) for obj in seq] media_dir", "dtype=np.uint8) pil_image = PILImage.fromarray(pixels, mode=\"RGB\") image = wandb.Image(pil_image, caption=f\"random field", "Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def __init__( self, data_or_path: \"ImageDataOrPathType\",", "not all(x is None for x in all_mask_groups): return all_mask_groups", "= mask_item elif isinstance(mask_item, dict): # TODO: Consider injecting top-level", "= None, caption: Optional[str] = None, grouping: Optional[int] = None,", "= box_item elif isinstance(box_item, dict): # TODO: Consider injecting top-level", "max_cli_version = util._get_max_cli_version() if max_cli_version is None: return False return", "representing \"\"\" # TODO: do we want to support dimensions", "will return floats between 0 and 255 # some images", "None: self._grouping = wbimage._grouping self._caption = wbimage._caption self._width = wbimage._width", "all_boxes = Image.all_boxes(seq, run, key, step) if all_boxes: meta[\"all_boxes\"] =", "\"\"\" Converts floating point image on the range [0,1] and", "data.ndim == 2: return \"L\" elif data.shape[-1] == 3: return", "0).cpu().numpy() ) else: if hasattr(data, \"numpy\"): # TF data eager", "# type: ignore sizes_match = all(size_equals_image(img) for img in seq)", "boxes: _boxes = {} for key in boxes: _boxes[key] =", "self._caption = None self._width = None self._height = None self._image", "mask_item = masks[key] if isinstance(mask_item, ImageMask): masks_final[key] = mask_item elif", "(numpy array, string, io) Accepts numpy array of image data,", "and have a perfect copy, # only overriding additional metdata", "elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\")", "TODO: do we want to support dimensions being at the", "import logging import os from typing import Any, cast, Dict,", "run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict = super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"]", "converts it. mode: (string) The PIL mode for an image.", "array <!--yeadoc-test:log-image-numpy-> ```python import numpy as np import wandb wandb.init()", "in the UI. Please upgrade your wandb server\", repeat=False, )", "images from being\" \"viewed in the UI. Please upgrade your", "self._masks[k].bind_to_run( run, key, step, id_, ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact:", "guess_mode(self, data: \"np.ndarray\") -> str: \"\"\" Guess what type of", "-> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the PIL", "or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact) for", "Image's must be in the {} directory, not {}\".format( cls.get_media_subdir(),", "image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group) else: all_box_groups.append(None) if all_box_groups and", "self._height = None self._image = None self._classes = None self._boxes", "else: wandb.termwarn( \"Unable to log image array filenames. In some", "super(Image, self).to_json(run_or_artifact) json_dict[\"_type\"] = Image._log_type json_dict[\"format\"] = self.format if self._width", "image on the range [0,1] and integer images on the", "TF data eager tensors data = data.numpy() if data.ndim >", "if caption is not None: self._caption = caption total_classes =", "import os from typing import Any, cast, Dict, List, Optional,", "id_ is not None else None self._masks[k].bind_to_run( run, key, step,", "ValueError( \"classes must be passed to wandb.Image which have masks", "= wbimage._artifact_source self._artifact_target = wbimage._artifact_target # We do not want", "else: return False @classmethod def all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"],", "for (k, box) in self._boxes.items() } if self._masks: json_dict[\"masks\"] =", "wbimage._extension self._sha256 = wbimage._sha256 self._size = wbimage._size self.format = wbimage.format", "util.is_pytorch_tensor_typename(util.get_full_typename(data)): vis_util = util.get_module( \"torchvision.utils\", \"torchvision is required to render", "a PIL image. The class attempts to infer the data", "ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() -> bool: #", "\"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\", \"torch.Variable\"] def _server_accepts_image_filenames() -> bool:", "pixels = np.random.randint(low=0, high=256, size=(100, 100, 3), dtype=np.uint8) pil_image =", "wbimage._size self.format = wbimage.format self._artifact_source = wbimage._artifact_source self._artifact_target = wbimage._artifact_target", "/ np.ptp(data) if np.max(data) <= 1.0: data = (data *", "is None for x in all_mask_groups): return all_mask_groups else: return", "# We do not want to implicitly copy boxes or", "json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None if boxes: _boxes =", "wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"]", "import numpy as np # type: ignore import PIL #", "# some images have range -1...1 or 0-1 dmin =", "json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact) for (k, box) in self._boxes.items()", "= self._height if self._grouping: json_dict[\"grouping\"] = self._grouping if self._caption: json_dict[\"caption\"]", "0-1 dmin = np.min(data) if dmin < 0: data =", "boxes_final: Dict[str, BoundingBoxes2D] = {} for key in boxes: box_item", "json_dict[\"height\"] = self._height if self._grouping: json_dict[\"grouping\"] = self._grouping if self._caption:", "wbimage._classes self._path = wbimage._path self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension", "self, grouping: Optional[int] = None, caption: Optional[str] = None, classes:", "jsons] else: wandb.termwarn( \"Unable to log image array filenames. In", "Create a wandb.Image from a numpy array <!--yeadoc-test:log-image-numpy-> ```python import", "== other._caption and self._width == other._width and self._height == other._height", "masks, just the image-related data. # self._boxes = wbimage._boxes #", "and data.requires_grad: data = data.detach() data = vis_util.make_grid(data, normalize=True) self._image", "image in images: if image._masks: mask_group = {} for k", "= pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name,", "* 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer), 'Illegal image format.' return", "to_data_array(self) -> List[Any]: res = [] if self.image is not", "import wandb wandb.init() examples = [] for i in range(3):", "dict): raise ValueError('Images \"boxes\" argument must be a dictionary') boxes_final:", "masks_final[key] = ImageMask(mask_item, key) if hasattr(masks_final[key], \"_val\"): total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks =", "wbimage._path self._is_tmp = wbimage._is_tmp self._extension = wbimage._extension self._sha256 = wbimage._sha256", "= [] if self.image is not None: data = list(self.image.getdata())", "import PIL # type: ignore import torch # type: ignore", "= key boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] = None", "self._boxes: json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact) for (k, box) in", "def all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str,", "boxes, masks) def _set_initialization_meta( self, grouping: Optional[int] = None, caption:", "in images: if image._boxes: box_group = {} for k in", "= source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] = None", "return False return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images", "wbimage._boxes # self._masks = wbimage._masks def _initialize_from_path(self, path: str) ->", "self._image.load() ext = os.path.splitext(path)[1][1:] self.format = ext def _initialize_from_data(self, data:", "return cls.captions(images) def __ne__(self, other: object) -> bool: return not", "dictionary') masks_final: Dict[str, ImageMask] = {} for key in masks:", "\"np.ndarray\": \"\"\" Converts floating point image on the range [0,1]", "self._free_ram() return res def _free_ram(self) -> None: if self._path is", "list(data.shape) ) @classmethod def to_uint8(cls, data: \"np.ndarray\") -> \"np.ndarray\": \"\"\"", "classes, boxes, masks) def _set_initialization_meta( self, grouping: Optional[int] = None,", "for image conversion %s\" % list(data.shape) ) @classmethod def to_uint8(cls,", "Arguments: data_or_path: (numpy array, string, io) Accepts numpy array of", "= np.random.randint(low=0, high=256, size=(100, 100, 3)) image = wandb.Image(pixels, caption=f\"random", "if not isinstance(masks, dict): raise ValueError('Images \"masks\" argument must be", "install numpy\", ) # I think it's better to check", "in enumerate(self._masks): id_ = \"{}{}\".format(id_, i) if id_ is not", "or bounding boxes when adding to artifacts\" ) if self._classes", "\"format\": format, \"count\": num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"]", "dmin = np.min(data) if dmin < 0: data = (data", "data = (data - np.min(data)) / np.ptp(data) if np.max(data) <=", "in self._masks.items() } return json_dict def guess_mode(self, data: \"np.ndarray\") ->", "\"PIL.Image\", required='wandb.Image needs the PIL package. To get it, run", "a dictionary') masks_final: Dict[str, ImageMask] = {} for key in", "is None: raise ValueError( \"classes must be passed to wandb.Image", "ignore_copy_err=ignore_copy_err ) def to_json(self, run_or_artifact: Union[\"LocalRun\", \"LocalArtifact\"]) -> dict: json_dict", "wandb import util from ._private import MEDIA_TMP from .base_types.media import", "ignore import PIL # type: ignore import torch # type:", "caption: Optional[str] = None, grouping: Optional[int] = None, classes: Optional[Union[\"Classes\",", "for an image. Most common are \"L\", \"RGB\", \"RGBA\". Full", "the child images. \"\"\" if TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq)", "return False @classmethod def all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"] )", "eager tensors data = data.numpy() if data.ndim > 2: data", "typing import Any, cast, Dict, List, Optional, Sequence, Type, TYPE_CHECKING,", "not {}\".format( cls.get_media_subdir(), obj[\"path\"] ) ) num_images_to_log = len(seq) width,", "requires numpy if not supplying PIL Images: pip install numpy\",", "is not None: other_image = list(other_image.getdata()) return ( self._grouping ==", "return False @classmethod def all_boxes( cls: Type[\"Image\"], images: Sequence[\"Image\"], run:", "List[Optional[dict]] = [] for image in images: if image._boxes: box_group", "<= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images for logging to W&B.", ") if self._classes is not None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\")", "{ \"_type\": \"images/separated\", \"width\": width, \"height\": height, \"format\": format, \"count\":", "Examples: ### Create a wandb.Image from a numpy array <!--yeadoc-test:log-image-numpy->", "self._grouping = None self._caption = None self._width = None self._height", "hasattr(data, \"numpy\"): # TF data eager tensors data = data.numpy()", "masks=_masks, ) @classmethod def get_media_subdir(cls: Type[\"Image\"]) -> str: return os.path.join(\"media\",", "Optional[Dict[str, \"ImageMask\"]] def __init__( self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str] =", ").hexdigest() class_name = os.path.join(\"media\", \"classes\", class_id + \"_cls\",) classes_entry =", "= self._grouping if self._caption: json_dict[\"caption\"] = self._caption if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact):", ") -> None: super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if self._boxes", "is not None: self._grouping = grouping if caption is not", "_initialize_from_wbimage(self, wbimage: \"Image\") -> None: self._grouping = wbimage._grouping self._caption =", "\"images/separated\", \"width\": width, \"height\": height, \"format\": format, \"count\": num_images_to_log, }", "image. The class attempts to infer the data format and", "not None: json_dict[\"width\"] = self._width if self._height is not None:", "= json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] = None if masks: _masks", "Optional[\"PIL.Image\"] _classes: Optional[\"Classes\"] _boxes: Optional[Dict[str, \"BoundingBoxes2D\"]] _masks: Optional[Dict[str, \"ImageMask\"]] def", "meta @classmethod def all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\",", "..wandb_run import Run as LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\",", "dict]]] = None, ) -> None: super(Image, self).__init__() # TODO:", "from ..wandb_run import Run as LocalRun ImageDataType = Union[ \"matplotlib.artist.Artist\",", "is not None or self._boxes is not None ) and", "is not None ) and self._classes is None: raise ValueError(", "None, caption: Optional[str] = None, grouping: Optional[int] = None, classes:", "must be a dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {} for", "wandb.init() examples = [] for i in range(3): pixels =", "if grouping is not None: self._grouping = grouping if caption", "be a dictionary') masks_final: Dict[str, ImageMask] = {} for key", "def _server_accepts_image_filenames() -> bool: # Newer versions of wandb accept", "\"Files in an array of Image's must be in the", "None, ) -> None: super(Image, self).__init__() # TODO: We should", "classes = None if json_obj.get(\"classes\") is not None: classes =", "[ {\"id\": key, \"name\": total_classes[key]} for key in total_classes.keys() ]", "\"\"\" Guess what type of image the np.array is representing", "numpy as np from PIL import Image as PILImage import", "if self._masks: json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact) for (k, mask)", "# PIL limit MAX_DIMENSION = 65500 _log_type = \"image-file\" format:", "ignore_copy_err: Optional[bool] = None, ) -> None: super().bind_to_run(run, key, step,", "\"height\": height, \"format\": format, \"count\": num_images_to_log, } if _server_accepts_image_filenames(): meta[\"filenames\"]", "step: Union[int, str], ) -> dict: \"\"\" Combines a list", "parameter and have a perfect copy, # only overriding additional", "def image(self) -> Optional[\"PIL.Image\"]: if self._image is None: if self._path", "\"{}{}\".format(id_, i) if id_ is not None else None self._masks[k].bind_to_run(", "argument must be a dictionary') masks_final: Dict[str, ImageMask] = {}", "np = util.get_module( \"numpy\", required=\"wandb.Image requires numpy if not supplying", "= list(self.image.getdata()) for i in range(self.image.height): res.append(data[i * self.image.width :", "__init__( self, data_or_path: \"ImageDataOrPathType\", mode: Optional[str] = None, caption: Optional[str]", "self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\") -> None: self._grouping = wbimage._grouping", "is not None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs the", "self.format = \"png\" self._image.save(tmp_path, transparency=None) self._set_file(tmp_path, is_tmp=True) @classmethod def from_json(", "str], ) -> dict: \"\"\" Combines a list of images", "Union[int, str], ) -> dict: \"\"\" Combines a list of", "np.integer), 'Illegal image format.' return data.clip(0, 255).astype(np.uint8) @classmethod def seq_to_json(", "run, key, step) if all_masks: meta[\"all_masks\"] = all_masks all_boxes =", "if isinstance(box_item, BoundingBoxes2D): boxes_final[key] = box_item elif isinstance(box_item, dict): #", "-> Optional[\"PIL.Image\"]: if self._image is None: if self._path is not", "total_classes.update(masks_final[key]._val[\"class_labels\"]) self._masks = masks_final if classes is not None: if", "to artifacts\" ) if self._classes is not None: class_id =", "\"\"\" np = util.get_module( \"numpy\", required=\"wandb.Image requires numpy if not", "not sizes_match: logging.warning( \"Images sizes do not match. This will", "perfect copy, # only overriding additional metdata passed in. If", "for k in image._masks: mask = image._masks[k] mask_group[k] = mask.to_json(run)", "masks) def _set_initialization_meta( self, grouping: Optional[int] = None, caption: Optional[str]", "return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format images for logging", "path: str) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image needs", "[0,255] to uint8, clipping if necessary. \"\"\" np = util.get_module(", "not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks: Optional[Dict[str,", "else: self_image = self.image other_image = other.image if self_image is", "@classmethod def all_captions( cls: Type[\"Image\"], images: Sequence[\"Media\"] ) -> Union[bool,", "Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str, step: Union[int, str], ) ->", "import matplotlib # type: ignore import numpy as np #", "from_json( cls: Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\" ) -> \"Image\":", "seq_to_json( cls: Type[\"Image\"], seq: Sequence[\"BatchableMedia\"], run: \"LocalRun\", key: str, step:", "import numpy as np from PIL import Image as PILImage", "all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step:", ".helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes import Classes from .helper_types.image_mask import", "run: \"LocalRun\", key: str, step: Union[int, str], ) -> dict:", "have range -1...1 or 0-1 dmin = np.min(data) if dmin", "None: return False return parse_version(\"0.12.10\") <= parse_version(max_cli_version) class Image(BatchableMedia): \"\"\"Format", ") -> Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = [] for image", "classes: Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]]", ".base_types.media import BatchableMedia, Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes", "captions: meta[\"captions\"] = captions all_masks = Image.all_masks(seq, run, key, step)", "1.0: data = (data * 255).astype(np.int32) # assert issubclass(data.dtype.type, np.integer),", "self._masks = None # Allows the user to pass an", "def size_equals_image(image: \"Image\") -> bool: img_width, img_height = image.image.size #", "in jsons: expected = util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise ValueError(", "the image range vs the data type, since many #", "= wbimage._sha256 self._size = wbimage._size self.format = wbimage.format self._artifact_source =", "cls.get_media_subdir() for obj in jsons: expected = util.to_forward_slash_path(media_dir) if not", "None, ) -> None: super().bind_to_run(run, key, step, id_, ignore_copy_err=ignore_copy_err) if", "can generalize. if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path)", "= boxes_final if masks: if not isinstance(masks, dict): raise ValueError('Images", "{} if boxes: if not isinstance(boxes, dict): raise ValueError('Images \"boxes\"", "if json_obj.get(\"classes\") is not None: classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks =", "dict, source_artifact: \"PublicArtifact\" ) -> \"Image\": classes = None if", "ValueError('Images \"masks\" argument must be a dictionary') masks_final: Dict[str, ImageMask]", "point image on the range [0,1] and integer images on", "\"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\": classes_entry.digest, } elif not isinstance(run_or_artifact,", "package. To get it, run \"pip install pillow\".', ) if", "= None self._caption = None self._width = None self._height =", "isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if ( self._masks is not", "classes}) if len(total_classes.keys()) > 0: self._classes = Classes( [ {\"id\":", "\"digest\": classes_entry.digest, } elif not isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts", "expected = util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected): raise ValueError( \"Files in", ") captions = Image.all_captions(seq) if captions: meta[\"captions\"] = captions all_masks", "is empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final", "total_classes.update(boxes_final[key]._class_labels) self._boxes = boxes_final if masks: if not isinstance(masks, dict):", "string, io) Accepts numpy array of image data, or a", "self._classes is not None: class_id = hashlib.md5( str(self._classes._class_set).encode(\"utf-8\") ).hexdigest() class_name", "classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"] = { \"type\": \"classes-file\", \"path\":", "# I think it's better to check the image range", "BoundingBoxes2D]] = None if boxes: _boxes = {} for key", "= all_masks all_boxes = Image.all_boxes(seq, run, key, step) if all_boxes:", "raise ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] =", "if hasattr(data, \"requires_grad\") and data.requires_grad: data = data.detach() data =", "from being\" \"viewed in the UI. Please upgrade your wandb", "In some cases, this can prevent images from being\" \"viewed", "return os.path.join(\"media\", \"images\") def bind_to_run( self, run: \"LocalRun\", key: Union[int,", "image conversion %s\" % list(data.shape) ) @classmethod def to_uint8(cls, data:", "the beginning of the array? if data.ndim == 2: return", "None: super(Image, self).__init__() # TODO: We should remove grouping, it's", "== other._width and self._height == other._height and self_image == other_image", "-> str: return os.path.join(\"media\", \"images\") def bind_to_run( self, run: \"LocalRun\",", "overriding additional metdata passed in. If this pattern is compelling,", "I don't # think anyone uses it. self._grouping = None", "caption=f\"random field {i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` ### Create a", "ImageMask] = {} for key in masks: mask_item = masks[key]", "k in image._boxes: box = image._boxes[k] box_group[k] = box.to_json(run) all_box_groups.append(box_group)", "self.format if self._width is not None: json_dict[\"width\"] = self._width if", "List[Optional[dict]] = [] for image in images: if image._masks: mask_group", "type, since many # image libraries will return floats between", "do not match. This will causes images to be display", "self._boxes = wbimage._boxes # self._masks = wbimage._masks def _initialize_from_path(self, path:", "size=(100, 100, 3)) image = wandb.Image(pixels, caption=f\"random field {i}\") examples.append(image)", "else: total_classes.update({val[\"id\"]: val[\"name\"] for val in classes}) if len(total_classes.keys()) >", "_masks[key]._key = key boxes = json_obj.get(\"boxes\") _boxes: Optional[Dict[str, BoundingBoxes2D]] =", "self.image.size # type: ignore self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\") ->", "str], id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] = None,", "= vis_util.make_grid(data, normalize=True) self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()", "= None self._image = None self._classes = None self._boxes =", "image data, or a PIL image. The class attempts to", "Union[List[Optional[dict]], bool]: all_box_groups: List[Optional[dict]] = [] for image in images:", "\"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType = Union[str, \"Image\", ImageDataType] TorchTensorType =", "<!--yeadoc-test:log-image-pil-> ```python import numpy as np from PIL import Image", "The PIL mode for an image. Most common are \"L\",", "self._grouping: json_dict[\"grouping\"] = self._grouping if self._caption: json_dict[\"caption\"] = self._caption if", "-> dict: \"\"\" Combines a list of images into a", "type: ignore import torch # type: ignore from wandb.apis.public import", "-> \"Image\": classes = None if json_obj.get(\"classes\") is not None:", "\"np.ndarray\" ] ImageDataOrPathType = Union[str, \"Image\", ImageDataType] TorchTensorType = Union[\"torch.Tensor\",", "causes images to be display incorrectly in the UI.\" )", "all_mask_groups.append(None) if all_mask_groups and not all(x is None for x", "@classmethod def all_masks( cls: Type[\"Image\"], images: Sequence[\"Image\"], run: \"LocalRun\", run_key:", "images have range -1...1 or 0-1 dmin = np.min(data) if", "this can prevent images from being\" \"viewed in the UI.", "a dictionary') boxes_final: Dict[str, BoundingBoxes2D] = {} for key in", "to pass an Image object as the first parameter and", "all(size_equals_image(img) for img in seq) if not sizes_match: logging.warning( \"Images", "is not None: self_image = list(self_image.getdata()) if other_image is not", "if image._masks: mask_group = {} for k in image._masks: mask", "= os.path.splitext(path)[1][1:] self.format = ext def _initialize_from_data(self, data: \"ImageDataType\", mode:", "# self._masks = wbimage._masks def _initialize_from_path(self, path: str) -> None:", "{i}\") examples.append(image) wandb.log({\"examples\": examples}) ``` ### Create a wandb.Image from", "server\", repeat=False, ) captions = Image.all_captions(seq) if captions: meta[\"captions\"] =", "total_classes.keys() ] ) self._width, self._height = self.image.size # type: ignore", "self._image = pil_image.fromarray( data.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy() ) else: if", "self._height == other._height and self_image == other_image and self._classes ==", "val[\"name\"] for val in classes}) if len(total_classes.keys()) > 0: self._classes", "range(self.image.height): res.append(data[i * self.image.width : (i + 1) * self.image.width])", "as a convenience self._image = pil_image.fromarray( self.to_uint8(data), mode=mode or self.guess_mode(data)", "def _initialize_from_data(self, data: \"ImageDataType\", mode: str = None,) -> None:", "if isinstance(data_or_path, Image): self._initialize_from_wbimage(data_or_path) elif isinstance(data_or_path, str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path,", "seq[0].image.size # type: ignore format = jsons[0][\"format\"] def size_equals_image(image: \"Image\")", "_set_initialization_meta( self, grouping: Optional[int] = None, caption: Optional[str] = None,", "\"classes\", class_id + \"_cls\",) classes_entry = artifact.add(self._classes, class_name) json_dict[\"classes\"] =", "all_mask_groups): return all_mask_groups else: return False @classmethod def all_boxes( cls:", "None, masks: Optional[Union[Dict[str, \"ImageMask\"], Dict[str, dict]]] = None, ) ->", "is not None: data = list(self.image.getdata()) for i in range(self.image.height):", "id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool] = None, )", "BatchableMedia, Media from .helper_types.bounding_boxes_2d import BoundingBoxes2D from .helper_types.classes import Classes", "self._boxes = None self._masks = None # Allows the user", "np from PIL import Image as PILImage import wandb wandb.init()", "wbimage._is_tmp self._extension = wbimage._extension self._sha256 = wbimage._sha256 self._size = wbimage._size", "= Classes( [ {\"id\": key, \"name\": total_classes[key]} for key in", "boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] = None, masks: Optional[Union[Dict[str, \"ImageMask\"],", "run \"pip install pillow\".', ) self._image = pil_image.open(self._path) self._image.load() return", "cls( source_artifact.get_path(json_obj[\"path\"]).download(), caption=json_obj.get(\"caption\"), grouping=json_obj.get(\"grouping\"), classes=classes, boxes=_boxes, masks=_masks, ) @classmethod def", "== other._grouping and self._caption == other._caption and self._width == other._width", "not None: self._caption = caption total_classes = {} if boxes:", "step: Union[int, str], id_: Optional[Union[int, str]] = None, ignore_copy_err: Optional[bool]", "raise ValueError('Images \"boxes\" argument must be a dictionary') boxes_final: Dict[str,", "image-related data. # self._boxes = wbimage._boxes # self._masks = wbimage._masks", "= util._get_max_cli_version() if max_cli_version is None: return False return parse_version(\"0.12.10\")", "3: return \"RGB\" elif data.shape[-1] == 4: return \"RGBA\" else:", "< 0: data = (data - np.min(data)) / np.ptp(data) if", "but older versions would have issues with this. max_cli_version =", "self._height = wbimage._height self._image = wbimage._image self._classes = wbimage._classes self._path", ": (i + 1) * self.image.width]) self._free_ram() return res def", "better to check the image range vs the data type,", ") self._width, self._height = self.image.size # type: ignore self._free_ram() def", "Optional[Union[\"Classes\", Sequence[dict]]] = None, boxes: Optional[Union[Dict[str, \"BoundingBoxes2D\"], Dict[str, dict]]] =", "run_key: str, step: Union[int, str], ) -> Union[List[Optional[dict]], bool]: all_box_groups:", "if user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item, key) total_classes.update(boxes_final[key]._class_labels) self._boxes", "i) if id_ is not None else None self._masks[k].bind_to_run( run,", "user to pass an Image object as the first parameter", "None self._caption = None self._width = None self._height = None", "classes = source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] =", "masks_final[key] = mask_item elif isinstance(mask_item, dict): # TODO: Consider injecting", "not None: other_image = list(other_image.getdata()) return ( self._grouping == other._grouping", "masks or bounding boxes when adding to artifacts\" ) if", "versions of wandb accept large image filenames arrays # but", "self._image is None: if self._path is not None: pil_image =", "str = None,) -> None: pil_image = util.get_module( \"PIL.Image\", required='wandb.Image", "= data.numpy() if data.ndim > 2: data = data.squeeze() #", "if _server_accepts_image_filenames(): meta[\"filenames\"] = [obj[\"path\"] for obj in jsons] else:", "= self.format if self._width is not None: json_dict[\"width\"] = self._width", "run, key, step) if all_boxes: meta[\"all_boxes\"] = all_boxes return meta", "is not None: json_dict[\"height\"] = self._height if self._grouping: json_dict[\"grouping\"] =", "= self.image other_image = other.image if self_image is not None:", "not None: for i, k in enumerate(self._masks): id_ = \"{}{}\".format(id_,", "mask_item elif isinstance(mask_item, dict): # TODO: Consider injecting top-level classes", "or self.guess_mode(data) ) tmp_path = os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format", "= None, ignore_copy_err: Optional[bool] = None, ) -> None: super().bind_to_run(run,", "ignore_copy_err=ignore_copy_err) if self._boxes is not None: for i, k in", "@classmethod def from_json( cls: Type[\"Image\"], json_obj: dict, source_artifact: \"PublicArtifact\" )", "in boxes: _boxes[key] = BoundingBoxes2D.from_json(boxes[key], source_artifact) _boxes[key]._key = key return", "isinstance(run_or_artifact, wandb.wandb_sdk.wandb_run.Run): raise ValueError(\"to_json accepts wandb_run.Run or wandb_artifact.Artifact\") if self._boxes:", "images: Sequence[\"Image\"], run: \"LocalRun\", run_key: str, step: Union[int, str], )", "None: for i, k in enumerate(self._boxes): id_ = \"{}{}\".format(id_, i)", "source_artifact.get(json_obj[\"classes\"][\"path\"]) masks = json_obj.get(\"masks\") _masks: Optional[Dict[str, ImageMask]] = None if", "copy, # only overriding additional metdata passed in. If this", "all_mask_groups.append(mask_group) else: all_mask_groups.append(None) if all_mask_groups and not all(x is None", "self._image = pil_image.open(buf) elif isinstance(data, pil_image.Image): self._image = data elif", "for x in all_box_groups): return all_box_groups else: return False @classmethod", "obj[\"path\"].startswith(expected): raise ValueError( \"Files in an array of Image's must", "= os.path.join(MEDIA_TMP.name, str(util.generate_id()) + \".png\") self.format = \"png\" self._image.save(tmp_path, transparency=None)", "self_image = self.image other_image = other.image if self_image is not", "and integer images on the range [0,255] to uint8, clipping", "= self.image.size # type: ignore self._free_ram() def _initialize_from_wbimage(self, wbimage: \"Image\")", "from PIL import Image as PILImage import wandb wandb.init() examples", "\"numpy\", required=\"wandb.Image requires numpy if not supplying PIL Images: pip", "for obj in jsons: expected = util.to_forward_slash_path(media_dir) if not obj[\"path\"].startswith(expected):", "TYPE_CHECKING: seq = cast(Sequence[\"Image\"], seq) jsons = [obj.to_json(run) for obj", "wbimage._width self._height = wbimage._height self._image = wbimage._image self._classes = wbimage._classes", "data eager tensors data = data.numpy() if data.ndim > 2:", "if self._boxes: json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact) for (k, box)", "} if self._masks: json_dict[\"masks\"] = { k: mask.to_json(run_or_artifact) for (k,", "Optional[Dict[str, ImageMask]] = None if masks: _masks = {} for", "Dict[str, ImageMask] = {} for key in masks: mask_item =", "it, run \"pip install pillow\".', ) if util.is_matplotlib_typename(util.get_full_typename(data)): buf =", "wandb_artifact.Artifact\") if self._boxes: json_dict[\"boxes\"] = { k: box.to_json(run_or_artifact) for (k,", "and 255 # some images have range -1...1 or 0-1", "= None self._masks = None # Allows the user to", "ImageDataType = Union[ \"matplotlib.artist.Artist\", \"PIL.Image\", \"TorchTensorType\", \"np.ndarray\" ] ImageDataOrPathType =", "artifact.add(self._classes, class_name) json_dict[\"classes\"] = { \"type\": \"classes-file\", \"path\": classes_entry.path, \"digest\":", "str): self._initialize_from_path(data_or_path) else: self._initialize_from_data(data_or_path, mode) self._set_initialization_meta(grouping, caption, classes, boxes, masks)", "if isinstance(run_or_artifact, wandb.wandb_sdk.wandb_artifacts.Artifact): artifact = run_or_artifact if ( self._masks is", "must be passed to wandb.Image which have masks or bounding", "> 2: data = data.squeeze() # get rid of trivial", "top-level classes if user-provided is empty boxes_final[key] = BoundingBoxes2D(box_item, key)" ]
[ "return '%02d:%02d:%02d.%03d' % (hours, minutes, seconds, milliseconds) # Returns a", "minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours == 0: if minutes", "return '%d.%03d' % (seconds, milliseconds) return '%02d:%02d.%03d' % (minutes, seconds,", "hours == 0: if minutes == 0: return '%d.%03d' %", "Returns string formatted as HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending on", "0: return '%d.%03d' % (seconds, milliseconds) return '%02d:%02d.%03d' % (minutes,", "milli % 1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if", "time. def get_time_from_milliseconds(milli): milliseconds = milli % 1000 seconds= (milli//1000)%60", "HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending on the time. def get_time_from_milliseconds(milli):", "# Returns a string formatted as YYYY-MM-DD def get_date_today(): return", "milliseconds) return '%02d:%02d.%03d' % (minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d' %", "% (minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d' % (hours, minutes, seconds,", "Returns a string formatted as YYYY-MM-DD def get_date_today(): return datetime.date.today().strftime(\"%Y-%m-%d\")", "datetime # Gets time from milliseconds # Returns string formatted", "== 0: if minutes == 0: return '%d.%03d' % (seconds,", "minutes, seconds, milliseconds) # Returns a string formatted as YYYY-MM-DD", "milliseconds) return '%02d:%02d:%02d.%03d' % (hours, minutes, seconds, milliseconds) # Returns", "from milliseconds # Returns string formatted as HH:MM:SS:mmm, MM:SS:mmm or", "or S:mmm, depending on the time. def get_time_from_milliseconds(milli): milliseconds =", "% 1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours", "if hours == 0: if minutes == 0: return '%d.%03d'", "'%d.%03d' % (seconds, milliseconds) return '%02d:%02d.%03d' % (minutes, seconds, milliseconds)", "(seconds, milliseconds) return '%02d:%02d.%03d' % (minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d'", "MM:SS:mmm or S:mmm, depending on the time. def get_time_from_milliseconds(milli): milliseconds", "milliseconds) # Returns a string formatted as YYYY-MM-DD def get_date_today():", "get_time_from_milliseconds(milli): milliseconds = milli % 1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60", "Gets time from milliseconds # Returns string formatted as HH:MM:SS:mmm,", "seconds, milliseconds) # Returns a string formatted as YYYY-MM-DD def", "<reponame>skostic14/isda-racing-backend import datetime # Gets time from milliseconds # Returns", "def get_time_from_milliseconds(milli): milliseconds = milli % 1000 seconds= (milli//1000)%60 minutes=", "'%02d:%02d:%02d.%03d' % (hours, minutes, seconds, milliseconds) # Returns a string", "hours= (milli//(1000*60*60))%24 if hours == 0: if minutes == 0:", "% (seconds, milliseconds) return '%02d:%02d.%03d' % (minutes, seconds, milliseconds) return", "formatted as HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending on the time.", "import datetime # Gets time from milliseconds # Returns string", "(milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours == 0: if", "1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours ==", "(milli//(1000*60*60))%24 if hours == 0: if minutes == 0: return", "return '%02d:%02d.%03d' % (minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d' % (hours,", "if minutes == 0: return '%d.%03d' % (seconds, milliseconds) return", "as HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending on the time. def", "milliseconds # Returns string formatted as HH:MM:SS:mmm, MM:SS:mmm or S:mmm,", "milliseconds = milli % 1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours=", "string formatted as HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending on the", "# Gets time from milliseconds # Returns string formatted as", "minutes == 0: return '%d.%03d' % (seconds, milliseconds) return '%02d:%02d.%03d'", "= milli % 1000 seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24", "on the time. def get_time_from_milliseconds(milli): milliseconds = milli % 1000", "0: if minutes == 0: return '%d.%03d' % (seconds, milliseconds)", "== 0: return '%d.%03d' % (seconds, milliseconds) return '%02d:%02d.%03d' %", "'%02d:%02d.%03d' % (minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d' % (hours, minutes,", "% (hours, minutes, seconds, milliseconds) # Returns a string formatted", "S:mmm, depending on the time. def get_time_from_milliseconds(milli): milliseconds = milli", "time from milliseconds # Returns string formatted as HH:MM:SS:mmm, MM:SS:mmm", "# Returns string formatted as HH:MM:SS:mmm, MM:SS:mmm or S:mmm, depending", "(milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours == 0: if minutes ==", "depending on the time. def get_time_from_milliseconds(milli): milliseconds = milli %", "seconds, milliseconds) return '%02d:%02d:%02d.%03d' % (hours, minutes, seconds, milliseconds) #", "(hours, minutes, seconds, milliseconds) # Returns a string formatted as", "(minutes, seconds, milliseconds) return '%02d:%02d:%02d.%03d' % (hours, minutes, seconds, milliseconds)", "the time. def get_time_from_milliseconds(milli): milliseconds = milli % 1000 seconds=", "seconds= (milli//1000)%60 minutes= (milli//(1000*60))%60 hours= (milli//(1000*60*60))%24 if hours == 0:" ]
[ "step2_time)) def interactive(): \"\"\"Simple function to interact with user\"\"\" print(\"Compute", "for i in range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(\":\", (linecount", "0: print printed += colwidth*columns rem = (len(digits) - skip)", "0: skip = 0 else: skip = len(intpart) print(\"Step 1", "+ 1)*colwidth],) print(\":\", (linecount + 1)*perline) if (linecount + 1)", "in range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(\":\", (linecount + 1)*perline)", "== 0: skip = 0 else: skip = len(intpart) print(\"Step", "example Example shows arbitrary precision using mpmath with the computation", "1)*perline] for i in range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(\":\",", "%f seconds (%f calc, %f convert)\" % \\ ((step1_time +", "base, digits, tofile) def main(): \"\"\"A non-interactive runner\"\"\" base =", "intpart = libmp.numeral(3, base) if intpart == 0: skip =", "= int(n*math.log(base, 2)) + 10 t = clock() a =", "10 t = clock() a = func(prec) step1_time = clock()", "n, tofile): \"\"\"Writes first n base-digits of a mpmath function", "step1_time = clock() - t print(\"Step 2 of 2: converting", "def calculateit(func, base, n, tofile): \"\"\"Writes first n base-digits of", "buf = digits[-rem:] s = \"\" for i in range(columns):", "mpmath import libmp, pi from mpmath import functions as mpf_funs", "= (len(digits) - skip) % (colwidth * columns) if rem:", "range((len(digits) - skip) // (colwidth * columns)): line = digits[skip", "press enter\\nto print directly to the screen) \\n> \") if", "\"\" for i in range(columns): s += buf[:colwidth].ljust(colwidth + 1,", "0 for linecount in range((len(digits) - skip) // (colwidth *", "\") buf = buf[colwidth:] print(s + \":\", printed + colwidth*columns)", "2: calculating binary value...\") prec = int(n*math.log(base, 2)) + 10", "- t print(\"Step 2 of 2: converting to specified base...\")", "d = libmp.bin_to_radix(a.man, -a.exp, base, n) d = libmp.numeral(d, base,", "for first n digits of a fraction\"\"\" perline = colwidth", "open(tofile, \"w\") calculateit(pi, base, digits, tofile) def main(): \"\"\"A non-interactive", "libmp, pi from mpmath import functions as mpf_funs import math", "calculateit(func, base, n, tofile): \"\"\"Writes first n base-digits of a", "int(n*math.log(base, 2)) + 10 t = clock() a = func(prec)", "n) step2_time = clock() - t print(\"\\nWriting output...\\n\") if tofile:", "decimal) \\n> \") digits = input(\"How many digits? (enter a", "= None calculateit(pi, base, digits, tofile) if __name__ == \"__main__\":", "import sys def display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty printer for", "2 of 2: converting to specified base...\") t = clock()", "columns printed = 0 for linecount in range((len(digits) - skip)", "base-%i digits of pi:\\n\" % (n, base)) print(intpart, \".\\n\") display_fraction(d,", "(enter a filename, or just press enter\\nto print directly to", "10000)\\n> \") tofile = raw_input(\"Output to file? (enter a filename,", "\") if tofile: tofile = open(tofile, \"w\") calculateit(pi, base, digits,", "if intpart == 0: skip = 0 else: skip =", "if tofile: tofile = open(tofile, \"w\") calculateit(pi, base, digits, tofile)", "tofile: out_ = sys.stdout sys.stdout = tofile print(\"%i base-%i digits", "clock() - t print(\"Step 2 of 2: converting to specified", "mpmath function to file\"\"\" prec = 100 intpart = libmp.numeral(3,", "sys.stdout = out_ print(\"\\nFinished in %f seconds (%f calc, %f", "colwidth=10, columns=5) if tofile: sys.stdout = out_ print(\"\\nFinished in %f", "first n digits of a fraction\"\"\" perline = colwidth *", "clock() d = libmp.bin_to_radix(a.man, -a.exp, base, n) d = libmp.numeral(d,", "+ linecount*perline:skip + (linecount + 1)*perline] for i in range(columns):", "non-interactive runner\"\"\" base = 16 digits = 500 tofile =", "file\"\"\" prec = 100 intpart = libmp.numeral(3, base) if intpart", "print(\"Step 2 of 2: converting to specified base...\") t =", "= tofile print(\"%i base-%i digits of pi:\\n\" % (n, base))", "t = clock() d = libmp.bin_to_radix(a.man, -a.exp, base, n) d", "sys.stdout sys.stdout = tofile print(\"%i base-%i digits of pi:\\n\" %", "sys.stdout = tofile print(\"%i base-%i digits of pi:\\n\" % (n,", "base = input(\"Which base? (2-36, 10 for decimal) \\n> \")", "100 intpart = libmp.numeral(3, base) if intpart == 0: skip", "out_ = sys.stdout sys.stdout = tofile print(\"%i base-%i digits of", "= 16 digits = 500 tofile = None calculateit(pi, base,", "% (colwidth * columns) if rem: buf = digits[-rem:] s", "SymPy\\n\") base = input(\"Which base? (2-36, 10 for decimal) \\n>", "to the screen) \\n> \") if tofile: tofile = open(tofile,", "(%f calc, %f convert)\" % \\ ((step1_time + step2_time), step1_time,", "(linecount + 1) % 10 == 0: print printed +=", "user\"\"\" print(\"Compute digits of pi with SymPy\\n\") base = input(\"Which", "\"\"\" from mpmath import libmp, pi from mpmath import functions", "= clock() a = func(prec) step1_time = clock() - t", "base, n, tofile): \"\"\"Writes first n base-digits of a mpmath", "\".\\n\") display_fraction(d, skip, colwidth=10, columns=5) if tofile: sys.stdout = out_", "d = libmp.numeral(d, base, n) step2_time = clock() - t", "print(\"\\nFinished in %f seconds (%f calc, %f convert)\" % \\", "s += buf[:colwidth].ljust(colwidth + 1, \" \") buf = buf[colwidth:]", "a fraction\"\"\" perline = colwidth * columns printed = 0", "calc, %f convert)\" % \\ ((step1_time + step2_time), step1_time, step2_time))", "= 0 else: skip = len(intpart) print(\"Step 1 of 2:", "func(prec) step1_time = clock() - t print(\"Step 2 of 2:", "intpart == 0: skip = 0 else: skip = len(intpart)", "buf[colwidth:] print(s + \":\", printed + colwidth*columns) def calculateit(func, base,", "import math from time import clock import sys def display_fraction(digits,", "perline = colwidth * columns printed = 0 for linecount", "((step1_time + step2_time), step1_time, step2_time)) def interactive(): \"\"\"Simple function to", "+ step2_time), step1_time, step2_time)) def interactive(): \"\"\"Simple function to interact", "10 for decimal) \\n> \") digits = input(\"How many digits?", "enter\\nto print directly to the screen) \\n> \") if tofile:", "= digits[skip + linecount*perline:skip + (linecount + 1)*perline] for i", "of 2: converting to specified base...\") t = clock() d", "= clock() d = libmp.bin_to_radix(a.man, -a.exp, base, n) d =", "= 500 tofile = None calculateit(pi, base, digits, tofile) if", "+ (linecount + 1)*perline] for i in range(columns): print(line[i*colwidth: (i", "skip = 0 else: skip = len(intpart) print(\"Step 1 of", "out_ print(\"\\nFinished in %f seconds (%f calc, %f convert)\" %", "tofile: sys.stdout = out_ print(\"\\nFinished in %f seconds (%f calc,", "of pi:\\n\" % (n, base)) print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10,", "say, 10000)\\n> \") tofile = raw_input(\"Output to file? (enter a", "from mpmath import libmp, pi from mpmath import functions as", "computation of the digits of pi. \"\"\" from mpmath import", "= \"\" for i in range(columns): s += buf[:colwidth].ljust(colwidth +", "1)*colwidth],) print(\":\", (linecount + 1)*perline) if (linecount + 1) %", "digits[skip + linecount*perline:skip + (linecount + 1)*perline] for i in", "buf = buf[colwidth:] print(s + \":\", printed + colwidth*columns) def", "0 else: skip = len(intpart) print(\"Step 1 of 2: calculating", "convert)\" % \\ ((step1_time + step2_time), step1_time, step2_time)) def interactive():", "columns=5): \"\"\"Pretty printer for first n digits of a fraction\"\"\"", "base = 16 digits = 500 tofile = None calculateit(pi,", "base)) print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10, columns=5) if tofile: sys.stdout", "arbitrary precision using mpmath with the computation of the digits", "clock import sys def display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty printer", "(colwidth * columns) if rem: buf = digits[-rem:] s =", "500 tofile = None calculateit(pi, base, digits, tofile) if __name__", "linecount*perline:skip + (linecount + 1)*perline] for i in range(columns): print(line[i*colwidth:", "skip) // (colwidth * columns)): line = digits[skip + linecount*perline:skip", "colwidth*columns) def calculateit(func, base, n, tofile): \"\"\"Writes first n base-digits", "\") digits = input(\"How many digits? (enter a big number,", "digits = 500 tofile = None calculateit(pi, base, digits, tofile)", "printer for first n digits of a fraction\"\"\" perline =", "== 0: print printed += colwidth*columns rem = (len(digits) -", "skip = len(intpart) print(\"Step 1 of 2: calculating binary value...\")", "for linecount in range((len(digits) - skip) // (colwidth * columns)):", "python \"\"\"Pi digits example Example shows arbitrary precision using mpmath", "of pi. \"\"\" from mpmath import libmp, pi from mpmath", "directly to the screen) \\n> \") if tofile: tofile =", "10 == 0: print printed += colwidth*columns rem = (len(digits)", "interactive(): \"\"\"Simple function to interact with user\"\"\" print(\"Compute digits of", "* columns) if rem: buf = digits[-rem:] s = \"\"", "functions as mpf_funs import math from time import clock import", "print(\"%i base-%i digits of pi:\\n\" % (n, base)) print(intpart, \".\\n\")", "skip, colwidth=10, columns=5) if tofile: sys.stdout = out_ print(\"\\nFinished in", "of pi with SymPy\\n\") base = input(\"Which base? (2-36, 10", "tofile = raw_input(\"Output to file? (enter a filename, or just", "+ colwidth*columns) def calculateit(func, base, n, tofile): \"\"\"Writes first n", "tofile): \"\"\"Writes first n base-digits of a mpmath function to", "pi:\\n\" % (n, base)) print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10, columns=5)", "- skip) % (colwidth * columns) if rem: buf =", "(i + 1)*colwidth],) print(\":\", (linecount + 1)*perline) if (linecount +", "for i in range(columns): s += buf[:colwidth].ljust(colwidth + 1, \"", "to file\"\"\" prec = 100 intpart = libmp.numeral(3, base) if", "for decimal) \\n> \") digits = input(\"How many digits? (enter", "1 of 2: calculating binary value...\") prec = int(n*math.log(base, 2))", "runner\"\"\" base = 16 digits = 500 tofile = None", "= clock() - t print(\"Step 2 of 2: converting to", "n) d = libmp.numeral(d, base, n) step2_time = clock() -", "function to interact with user\"\"\" print(\"Compute digits of pi with", "- skip) // (colwidth * columns)): line = digits[skip +", "to interact with user\"\"\" print(\"Compute digits of pi with SymPy\\n\")", "just press enter\\nto print directly to the screen) \\n> \")", "= func(prec) step1_time = clock() - t print(\"Step 2 of", "buf[:colwidth].ljust(colwidth + 1, \" \") buf = buf[colwidth:] print(s +", "base, n) d = libmp.numeral(d, base, n) step2_time = clock()", "number, say, 10000)\\n> \") tofile = raw_input(\"Output to file? (enter", "digits of a fraction\"\"\" perline = colwidth * columns printed", "2)) + 10 t = clock() a = func(prec) step1_time", "printed + colwidth*columns) def calculateit(func, base, n, tofile): \"\"\"Writes first", "line = digits[skip + linecount*perline:skip + (linecount + 1)*perline] for", "= sys.stdout sys.stdout = tofile print(\"%i base-%i digits of pi:\\n\"", "colwidth * columns printed = 0 for linecount in range((len(digits)", "+= buf[:colwidth].ljust(colwidth + 1, \" \") buf = buf[colwidth:] print(s", "mpmath import functions as mpf_funs import math from time import", "#!/usr/bin/env python \"\"\"Pi digits example Example shows arbitrary precision using", "n digits of a fraction\"\"\" perline = colwidth * columns", "if tofile: out_ = sys.stdout sys.stdout = tofile print(\"%i base-%i", "columns)): line = digits[skip + linecount*perline:skip + (linecount + 1)*perline]", "screen) \\n> \") if tofile: tofile = open(tofile, \"w\") calculateit(pi,", "% 10 == 0: print printed += colwidth*columns rem =", "digits? (enter a big number, say, 10000)\\n> \") tofile =", "the computation of the digits of pi. \"\"\" from mpmath", "\":\", printed + colwidth*columns) def calculateit(func, base, n, tofile): \"\"\"Writes", "\"\"\"Writes first n base-digits of a mpmath function to file\"\"\"", "in range(columns): s += buf[:colwidth].ljust(colwidth + 1, \" \") buf", "digits of pi. \"\"\" from mpmath import libmp, pi from", "import clock import sys def display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty", "16 digits = 500 tofile = None calculateit(pi, base, digits,", "printed += colwidth*columns rem = (len(digits) - skip) % (colwidth", "the digits of pi. \"\"\" from mpmath import libmp, pi", "= open(tofile, \"w\") calculateit(pi, base, digits, tofile) def main(): \"\"\"A", "(len(digits) - skip) % (colwidth * columns) if rem: buf", "calculateit(pi, base, digits, tofile) def main(): \"\"\"A non-interactive runner\"\"\" base", "(2-36, 10 for decimal) \\n> \") digits = input(\"How many", "clock() a = func(prec) step1_time = clock() - t print(\"Step", "t = clock() a = func(prec) step1_time = clock() -", "step2_time), step1_time, step2_time)) def interactive(): \"\"\"Simple function to interact with", "% (n, base)) print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10, columns=5) if", "mpf_funs import math from time import clock import sys def", "with SymPy\\n\") base = input(\"Which base? (2-36, 10 for decimal)", "\"\"\"Pi digits example Example shows arbitrary precision using mpmath with", "display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty printer for first n digits", "% \\ ((step1_time + step2_time), step1_time, step2_time)) def interactive(): \"\"\"Simple", "= libmp.bin_to_radix(a.man, -a.exp, base, n) d = libmp.numeral(d, base, n)", "calculating binary value...\") prec = int(n*math.log(base, 2)) + 10 t", "t print(\"Step 2 of 2: converting to specified base...\") t", "\" \") buf = buf[colwidth:] print(s + \":\", printed +", "main(): \"\"\"A non-interactive runner\"\"\" base = 16 digits = 500", "i in range(columns): s += buf[:colwidth].ljust(colwidth + 1, \" \")", "print(s + \":\", printed + colwidth*columns) def calculateit(func, base, n,", "%f convert)\" % \\ ((step1_time + step2_time), step1_time, step2_time)) def", "to specified base...\") t = clock() d = libmp.bin_to_radix(a.man, -a.exp,", "if tofile: sys.stdout = out_ print(\"\\nFinished in %f seconds (%f", "a mpmath function to file\"\"\" prec = 100 intpart =", "= input(\"How many digits? (enter a big number, say, 10000)\\n>", "base...\") t = clock() d = libmp.bin_to_radix(a.man, -a.exp, base, n)", "\\n> \") digits = input(\"How many digits? (enter a big", "display_fraction(d, skip, colwidth=10, columns=5) if tofile: sys.stdout = out_ print(\"\\nFinished", "= raw_input(\"Output to file? (enter a filename, or just press", "tofile) def main(): \"\"\"A non-interactive runner\"\"\" base = 16 digits", "using mpmath with the computation of the digits of pi.", "= libmp.numeral(3, base) if intpart == 0: skip = 0", "+ 1)*perline] for i in range(columns): print(line[i*colwidth: (i + 1)*colwidth],)", "rem = (len(digits) - skip) % (colwidth * columns) if", "def interactive(): \"\"\"Simple function to interact with user\"\"\" print(\"Compute digits", "= 0 for linecount in range((len(digits) - skip) // (colwidth", "skip) % (colwidth * columns) if rem: buf = digits[-rem:]", "2: converting to specified base...\") t = clock() d =", "libmp.numeral(3, base) if intpart == 0: skip = 0 else:", "columns) if rem: buf = digits[-rem:] s = \"\" for", "of a fraction\"\"\" perline = colwidth * columns printed =", "+ 1, \" \") buf = buf[colwidth:] print(s + \":\",", "shows arbitrary precision using mpmath with the computation of the", "fraction\"\"\" perline = colwidth * columns printed = 0 for", "digits, tofile) def main(): \"\"\"A non-interactive runner\"\"\" base = 16", "+ 1)*perline) if (linecount + 1) % 10 == 0:", "len(intpart) print(\"Step 1 of 2: calculating binary value...\") prec =", "tofile = open(tofile, \"w\") calculateit(pi, base, digits, tofile) def main():", "output...\\n\") if tofile: out_ = sys.stdout sys.stdout = tofile print(\"%i", "value...\") prec = int(n*math.log(base, 2)) + 10 t = clock()", "from mpmath import functions as mpf_funs import math from time", "+ \":\", printed + colwidth*columns) def calculateit(func, base, n, tofile):", "(linecount + 1)*perline) if (linecount + 1) % 10 ==", "base? (2-36, 10 for decimal) \\n> \") digits = input(\"How", "pi with SymPy\\n\") base = input(\"Which base? (2-36, 10 for", "- t print(\"\\nWriting output...\\n\") if tofile: out_ = sys.stdout sys.stdout", "if rem: buf = digits[-rem:] s = \"\" for i", "= len(intpart) print(\"Step 1 of 2: calculating binary value...\") prec", "t print(\"\\nWriting output...\\n\") if tofile: out_ = sys.stdout sys.stdout =", "in %f seconds (%f calc, %f convert)\" % \\ ((step1_time", "with user\"\"\" print(\"Compute digits of pi with SymPy\\n\") base =", "tofile: tofile = open(tofile, \"w\") calculateit(pi, base, digits, tofile) def", "* columns printed = 0 for linecount in range((len(digits) -", "function to file\"\"\" prec = 100 intpart = libmp.numeral(3, base)", "def display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty printer for first n", "\") tofile = raw_input(\"Output to file? (enter a filename, or", "digits[-rem:] s = \"\" for i in range(columns): s +=", "sys def display_fraction(digits, skip=0, colwidth=10, columns=5): \"\"\"Pretty printer for first", "of 2: calculating binary value...\") prec = int(n*math.log(base, 2)) +", "big number, say, 10000)\\n> \") tofile = raw_input(\"Output to file?", "digits example Example shows arbitrary precision using mpmath with the", "= buf[colwidth:] print(s + \":\", printed + colwidth*columns) def calculateit(func,", "(linecount + 1)*perline] for i in range(columns): print(line[i*colwidth: (i +", "+= colwidth*columns rem = (len(digits) - skip) % (colwidth *", "converting to specified base...\") t = clock() d = libmp.bin_to_radix(a.man,", "import libmp, pi from mpmath import functions as mpf_funs import", "digits of pi with SymPy\\n\") base = input(\"Which base? (2-36,", "+ 10 t = clock() a = func(prec) step1_time =", "interact with user\"\"\" print(\"Compute digits of pi with SymPy\\n\") base", "(enter a big number, say, 10000)\\n> \") tofile = raw_input(\"Output", "raw_input(\"Output to file? (enter a filename, or just press enter\\nto", "clock() - t print(\"\\nWriting output...\\n\") if tofile: out_ = sys.stdout", "\"w\") calculateit(pi, base, digits, tofile) def main(): \"\"\"A non-interactive runner\"\"\"", "seconds (%f calc, %f convert)\" % \\ ((step1_time + step2_time),", "print printed += colwidth*columns rem = (len(digits) - skip) %", "pi. \"\"\" from mpmath import libmp, pi from mpmath import", "of the digits of pi. \"\"\" from mpmath import libmp,", "base-digits of a mpmath function to file\"\"\" prec = 100", "range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(\":\", (linecount + 1)*perline) if", "with the computation of the digits of pi. \"\"\" from", "a filename, or just press enter\\nto print directly to the", "a big number, say, 10000)\\n> \") tofile = raw_input(\"Output to", "precision using mpmath with the computation of the digits of", "first n base-digits of a mpmath function to file\"\"\" prec", "specified base...\") t = clock() d = libmp.bin_to_radix(a.man, -a.exp, base,", "\"\"\"Pretty printer for first n digits of a fraction\"\"\" perline", "base) if intpart == 0: skip = 0 else: skip", "\\ ((step1_time + step2_time), step1_time, step2_time)) def interactive(): \"\"\"Simple function", "tofile = None calculateit(pi, base, digits, tofile) if __name__ ==", "// (colwidth * columns)): line = digits[skip + linecount*perline:skip +", "mpmath with the computation of the digits of pi. \"\"\"", "tofile print(\"%i base-%i digits of pi:\\n\" % (n, base)) print(intpart,", "prec = int(n*math.log(base, 2)) + 10 t = clock() a", "+ 1) % 10 == 0: print printed += colwidth*columns", "libmp.bin_to_radix(a.man, -a.exp, base, n) d = libmp.numeral(d, base, n) step2_time", "i in range(columns): print(line[i*colwidth: (i + 1)*colwidth],) print(\":\", (linecount +", "print(line[i*colwidth: (i + 1)*colwidth],) print(\":\", (linecount + 1)*perline) if (linecount", "file? (enter a filename, or just press enter\\nto print directly", "print(\"\\nWriting output...\\n\") if tofile: out_ = sys.stdout sys.stdout = tofile", "digits = input(\"How many digits? (enter a big number, say,", "step2_time = clock() - t print(\"\\nWriting output...\\n\") if tofile: out_", "\\n> \") if tofile: tofile = open(tofile, \"w\") calculateit(pi, base,", "digits of pi:\\n\" % (n, base)) print(intpart, \".\\n\") display_fraction(d, skip,", "= colwidth * columns printed = 0 for linecount in", "1) % 10 == 0: print printed += colwidth*columns rem", "pi from mpmath import functions as mpf_funs import math from", "filename, or just press enter\\nto print directly to the screen)", "import functions as mpf_funs import math from time import clock", "print(\":\", (linecount + 1)*perline) if (linecount + 1) % 10", "input(\"How many digits? (enter a big number, say, 10000)\\n> \")", "-a.exp, base, n) d = libmp.numeral(d, base, n) step2_time =", "None calculateit(pi, base, digits, tofile) if __name__ == \"__main__\": interactive()", "print(\"Step 1 of 2: calculating binary value...\") prec = int(n*math.log(base,", "else: skip = len(intpart) print(\"Step 1 of 2: calculating binary", "= clock() - t print(\"\\nWriting output...\\n\") if tofile: out_ =", "time import clock import sys def display_fraction(digits, skip=0, colwidth=10, columns=5):", "print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10, columns=5) if tofile: sys.stdout =", "input(\"Which base? (2-36, 10 for decimal) \\n> \") digits =", "= input(\"Which base? (2-36, 10 for decimal) \\n> \") digits", "to file? (enter a filename, or just press enter\\nto print", "as mpf_funs import math from time import clock import sys", "(colwidth * columns)): line = digits[skip + linecount*perline:skip + (linecount", "linecount in range((len(digits) - skip) // (colwidth * columns)): line", "range(columns): s += buf[:colwidth].ljust(colwidth + 1, \" \") buf =", "* columns)): line = digits[skip + linecount*perline:skip + (linecount +", "n base-digits of a mpmath function to file\"\"\" prec =", "colwidth*columns rem = (len(digits) - skip) % (colwidth * columns)", "Example shows arbitrary precision using mpmath with the computation of", "= out_ print(\"\\nFinished in %f seconds (%f calc, %f convert)\"", "= digits[-rem:] s = \"\" for i in range(columns): s", "the screen) \\n> \") if tofile: tofile = open(tofile, \"w\")", "math from time import clock import sys def display_fraction(digits, skip=0,", "or just press enter\\nto print directly to the screen) \\n>", "printed = 0 for linecount in range((len(digits) - skip) //", "many digits? (enter a big number, say, 10000)\\n> \") tofile", "print directly to the screen) \\n> \") if tofile: tofile", "step1_time, step2_time)) def interactive(): \"\"\"Simple function to interact with user\"\"\"", "skip=0, colwidth=10, columns=5): \"\"\"Pretty printer for first n digits of", "\"\"\"Simple function to interact with user\"\"\" print(\"Compute digits of pi", "in range((len(digits) - skip) // (colwidth * columns)): line =", "(n, base)) print(intpart, \".\\n\") display_fraction(d, skip, colwidth=10, columns=5) if tofile:", "binary value...\") prec = int(n*math.log(base, 2)) + 10 t =", "1)*perline) if (linecount + 1) % 10 == 0: print", "rem: buf = digits[-rem:] s = \"\" for i in", "= libmp.numeral(d, base, n) step2_time = clock() - t print(\"\\nWriting", "prec = 100 intpart = libmp.numeral(3, base) if intpart ==", "a = func(prec) step1_time = clock() - t print(\"Step 2", "of a mpmath function to file\"\"\" prec = 100 intpart", "= 100 intpart = libmp.numeral(3, base) if intpart == 0:", "columns=5) if tofile: sys.stdout = out_ print(\"\\nFinished in %f seconds", "1, \" \") buf = buf[colwidth:] print(s + \":\", printed", "s = \"\" for i in range(columns): s += buf[:colwidth].ljust(colwidth", "base, n) step2_time = clock() - t print(\"\\nWriting output...\\n\") if", "\"\"\"A non-interactive runner\"\"\" base = 16 digits = 500 tofile", "print(\"Compute digits of pi with SymPy\\n\") base = input(\"Which base?", "libmp.numeral(d, base, n) step2_time = clock() - t print(\"\\nWriting output...\\n\")", "colwidth=10, columns=5): \"\"\"Pretty printer for first n digits of a", "if (linecount + 1) % 10 == 0: print printed", "from time import clock import sys def display_fraction(digits, skip=0, colwidth=10,", "def main(): \"\"\"A non-interactive runner\"\"\" base = 16 digits =" ]
[ "= [ migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),", "-*- coding: utf-8 -*- # Generated by Django 1.11.11 on", "options={ 'verbose_name': 'Service User', 'verbose_name_plural': 'Service Users', }, bases=(mailauth.models.PasswordMaskMixin, models.Model),", "import settings from django.db import migrations, models import django.db.models.deletion import", "('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='',", "'Service User', 'verbose_name_plural': 'Service Users', }, bases=(mailauth.models.PasswordMaskMixin, models.Model), ), ]", "import migrations, models import django.db.models.deletion import mailauth.models import uuid class", "verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True,", "fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')),", "on 2018-03-13 00:16 from __future__ import unicode_literals from django.conf import", "coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-03-13", "1.11.11 on 2018-03-13 00:16 from __future__ import unicode_literals from django.conf", "('mailauth', '0010_domain_redirect_to'), ] operations = [ migrations.CreateModel( name='MNServiceUser', fields=[ ('id',", "] operations = [ migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,", "models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128,", "primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')),", "serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description',", "00:16 from __future__ import unicode_literals from django.conf import settings from", "verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={", "models import django.db.models.deletion import mailauth.models import uuid class Migration(migrations.Migration): dependencies", "import uuid class Migration(migrations.Migration): dependencies = [ ('mailauth', '0010_domain_redirect_to'), ]", "('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),", "max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service User', 'verbose_name_plural':", "operations = [ migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,", "('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password',", "mailauth.models import uuid class Migration(migrations.Migration): dependencies = [ ('mailauth', '0010_domain_redirect_to'),", "default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service User',", "uuid class Migration(migrations.Migration): dependencies = [ ('mailauth', '0010_domain_redirect_to'), ] operations", "'0010_domain_redirect_to'), ] operations = [ migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True,", "dependencies = [ ('mailauth', '0010_domain_redirect_to'), ] operations = [ migrations.CreateModel(", "from __future__ import unicode_literals from django.conf import settings from django.db", "# Generated by Django 1.11.11 on 2018-03-13 00:16 from __future__", "= [ ('mailauth', '0010_domain_redirect_to'), ] operations = [ migrations.CreateModel( name='MNServiceUser',", "class Migration(migrations.Migration): dependencies = [ ('mailauth', '0010_domain_redirect_to'), ] operations =", "2018-03-13 00:16 from __future__ import unicode_literals from django.conf import settings", "Django 1.11.11 on 2018-03-13 00:16 from __future__ import unicode_literals from", "import mailauth.models import uuid class Migration(migrations.Migration): dependencies = [ ('mailauth',", "settings from django.db import migrations, models import django.db.models.deletion import mailauth.models", "__future__ import unicode_literals from django.conf import settings from django.db import", "('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service User', 'verbose_name_plural': 'Service", "Migration(migrations.Migration): dependencies = [ ('mailauth', '0010_domain_redirect_to'), ] operations = [", "<filename>authserver/mailauth/migrations/0011_mnserviceuser.py # -*- coding: utf-8 -*- # Generated by Django", "'verbose_name': 'Service User', 'verbose_name_plural': 'Service Users', }, bases=(mailauth.models.PasswordMaskMixin, models.Model), ),", "by Django 1.11.11 on 2018-03-13 00:16 from __future__ import unicode_literals", "import django.db.models.deletion import mailauth.models import uuid class Migration(migrations.Migration): dependencies =", "models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service User', 'verbose_name_plural': 'Service Users',", "from django.conf import settings from django.db import migrations, models import", "], options={ 'verbose_name': 'Service User', 'verbose_name_plural': 'Service Users', }, bases=(mailauth.models.PasswordMaskMixin,", "verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,", "[ ('mailauth', '0010_domain_redirect_to'), ] operations = [ migrations.CreateModel( name='MNServiceUser', fields=[", "-*- # Generated by Django 1.11.11 on 2018-03-13 00:16 from", "django.db import migrations, models import django.db.models.deletion import mailauth.models import uuid", "django.db.models.deletion import mailauth.models import uuid class Migration(migrations.Migration): dependencies = [", "Generated by Django 1.11.11 on 2018-03-13 00:16 from __future__ import", "to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service User', 'verbose_name_plural': 'Service Users', },", "('description', models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name':", "from django.db import migrations, models import django.db.models.deletion import mailauth.models import", "migrations, models import django.db.models.deletion import mailauth.models import uuid class Migration(migrations.Migration):", "max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)), ('user',", "migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4,", "<PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ],", "models.CharField(blank=True, default='', max_length=255)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Service", "django.conf import settings from django.db import migrations, models import django.db.models.deletion", "name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(default=uuid.uuid4, max_length=64,", "# -*- coding: utf-8 -*- # Generated by Django 1.11.11", "[ migrations.CreateModel( name='MNServiceUser', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username',", "import unicode_literals from django.conf import settings from django.db import migrations,", "models.CharField(default=uuid.uuid4, max_length=64, verbose_name='Username')), ('password', <PASSWORD>.models.<PASSWORD>(max_length=128, verbose_name='Password')), ('description', models.CharField(blank=True, default='', max_length=255)),", "utf-8 -*- # Generated by Django 1.11.11 on 2018-03-13 00:16", "unicode_literals from django.conf import settings from django.db import migrations, models" ]
[ "CLASS.match(line): # the end of a method return if 'self.get('", "logical_line or 'import tempest.lib' in logical_line): return msg = (\"T112:", "in line and 'self.list_resources(' not in line): continue if METHOD_GET_RESOURCE.match(logical_line):", "'glance', 'keystone', 'nova', 'swift', 'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE =", "ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename): return False if ignored_list_file is", "can not have any dependency on tempest ' 'config.') yield(0,", "avoid \" \"circular dependency\") yield (0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line,", "'keystone', 'nova', 'swift', 'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import", "in lines[line_number:]: if METHOD.match(line) or CLASS.match(line): # the end of", "line_number, lines): \"\"\"Check that service client names of GET should", "return for line in lines[line_number:]: if METHOD.match(line) or CLASS.match(line): #", "those tests, so just exclude the scenario tests. if 'tempest/scenario'", "path T115 \"\"\" if 'tempest/api/' not in filename: return if", "\"\"\" if \"tempest/api\" in filename or \"tempest/scenario\" in filename: res", "that tempest.lib should not import local tempest code T112 \"\"\"", "if 'tempest/api/' not in filename: return if not re.match(r'class .*Test.*\\(.*Admin.*\\):',", "= re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def", "the end of a method return if 'self.delete(' not in", "filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return if TEST_DEFINITION.match(physical_line): if", "tempest' in logical_line): return if ('from tempest.lib' in logical_line or", "not in line and ('self.show_resource(' not in line and 'self.list_resources('", "tempest.lib should not import local tempest code T112 \"\"\" if", "return if ('tempest.config' in logical_line or 'from tempest import config'", "'self.delete(' not in line and 'self.delete_resource(' not in line: continue", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "\"T117: Must apply `@decorators.attr(type=['negative'])`\" \" to all negative API tests\"", "specific language governing permissions and limitations # under the License.", "(%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def", "# not use this file except in compliance with the", "if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return if TEST_DEFINITION.match(physical_line): if not", "'ignored_list_T111.txt'): return for line in lines[line_number:]: if METHOD.match(line) or CLASS.match(line):", "False if ignored_list_file is not None: ignored_list = [] with", "clients import not allowed\" \" in tempest/api/* or tempest/scenario/* tests\"))", "= PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)), (\"T102: python clients import", "msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative", "logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115: All", "'nova', 'swift', 'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client'", "('tempest.config' in logical_line or 'from tempest import config' in logical_line", "True return if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return ( 0,", "= re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def", "tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line):", "# NOTE(mtreinish) Scenario tests always need service tags, but subdirs", "if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario tests", "argument shouldn't be mutable \"\"\" msg = \"N322: Method's default", "in filename or \"tempest/scenario\" in filename: res = PYTHON_CLIENT_RE.match(physical_line) if", "scenario tests. if 'tempest/scenario' not in filename: matches = SCENARIO_DECORATOR.match(physical_line)", "in compliance with the License. You may obtain # a", "scenario tests have service tags T104: Scenario tests require a", "re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE", "@core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a service tag isn't", "'tempest/lib/' in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class", "that service client names of DELETE should be consistent T111", "TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117: Must apply", "re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check", "have service tags T104: Scenario tests require a services decorator", "T104: Scenario tests require a services decorator \"\"\" if 'tempest/scenario/'", "return (physical_line.find(service_name), \"T107: service tag should not be in path\")", "N322: Method's default argument shouldn't be mutable \"\"\" msg =", "not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return for line in lines[line_number:]:", "You may obtain # a copy of the License at", "re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR", "need service tags, but subdirs are # created for services", "= matches.group(1).split(',') for service in services: service_name = service.strip().strip(\"'\") modulepath", "(0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests use", "= re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION", "= re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args", "doesn't use tempest config T114 \"\"\" if 'tempest/lib/' not in", "def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests should exist under admin", "filename: return if 'uuid.uuid4()' not in logical_line: return msg =", "a method return if 'self.get(' not in line and ('self.show_resource('", "delete_.+\") CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR =", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that", "logical_line): msg = ('T114: tempest.lib can not have any dependency", "tempest.lib' in logical_line or 'import tempest.lib' in logical_line): return msg", "2013 IBM Corp. # # Licensed under the Apache License,", "be consistent T110 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'):", "testtools.skip decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot", "re.match('tempest/(lib/)?services/.*', filename): return False if ignored_list_file is not None: ignored_list", "'tempest/scenario' not in filename: matches = SCENARIO_DECORATOR.match(physical_line) if matches: services", "always need service tags, but subdirs are # created for", "tempest.lib doesn't use tempest config T114 \"\"\" if 'tempest/lib/' not", "(\"T111: [DELETE /resources/<id>] methods should be \" \"delete_<resource name>\") yield", "dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests should exist under admin path", "under admin path T115 \"\"\" if 'tempest/api/' not in filename:", "not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return for line in lines[line_number:]:", "under the License is distributed on an \"AS IS\" BASIS,", "exclude the scenario tests. if 'tempest/scenario' not in filename: matches", "NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line,", "tempest/api & tempest/scenario tests T102: Cannot import OpenStack python clients", "= [] with open('tempest/hacking/' + ignored_list_file) as f: for line", "'tempest/api/' not in filename: return if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line):", "not in line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111:", "METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE =", "in line): continue if METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110: [GET", "in filename: if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104:", "(physical_line.find('def'), \"T105: (setUp|tearDown)Class can not be used in tests\") @core.flake8ext", "default argument shouldn't be mutable \"\"\" msg = \"N322: Method's", "= ['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron', 'ironic', 'heat', 'sahara']", "PY3 T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported", "have any dependency on tempest ' 'config.') yield(0, msg) @core.flake8ext", "no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do not have the testtools.skip decorator", "\"\"\" result = EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported 'message' Exception", "permissions and limitations # under the License. import os import", "this file except in compliance with the License. You may", "not import local tempest code to avoid \" \"circular dependency\")", "tag should only be added if the service name isn't", "dependency\") yield (0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that", "in logical_line: return msg = (\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex()", "if ignored_list_file is not None: ignored_list = [] with open('tempest/hacking/'", "def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib doesn't use tempest config", "created for services like heat which would cause false negatives", "in f: ignored_list.append(line.strip()) if filename in ignored_list: return False if", "already in the module path. T107 \"\"\" # NOTE(mtreinish) Scenario", "@core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client imports from tempest/api", "os import re from hacking import core import pycodestyle PYTHON_CLIENTS", "dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib doesn't use tempest config T114", "(\"[T116] Unsupported 'message' Exception attribute in PY3\") if result: yield(0,", "= (\"[T116] Unsupported 'message' Exception attribute in PY3\") if result:", "modulepath: return (physical_line.find(service_name), \"T107: service tag should not be in", "= EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported 'message' Exception attribute in", "= (\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\")", "import not allowed\" \" in tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "config T114 \"\"\" if 'tempest/lib/' not in filename: return if", "filename or 'tempest/lib/' in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'),", "not have any dependency on tempest ' 'config.') yield(0, msg)", "dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib should not import local tempest", "\"N322: Method's default argument shouldn't be mutable!\" if mutable_default_args.match(logical_line): yield", "if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115: All admin tests", "= SCENARIO_DECORATOR.match(physical_line) if matches: services = matches.group(1).split(',') for service in", "(0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check", "PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)), (\"T102: python clients import not", "Corp. # # Licensed under the Apache License, Version 2.0", "filename: return if ('tempest.config' in logical_line or 'from tempest import", "be consistent T111 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'):", "tests should exist under admin path T115 \"\"\" if 'tempest/api/'", "_common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename): return False", "ignored_list.append(line.strip()) if filename in ignored_list: return False if not METHOD.match(physical_line):", "re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return if TEST_DEFINITION.match(physical_line):", "if pycodestyle.noqa(physical_line): return if 'tempest/test.py' in filename or 'tempest/lib/' in", "no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return if 'tempest/test.py' in filename or", "use \" \"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None):", "DELETE should be consistent T111 \"\"\" if not _common_service_clients_check(logical_line, physical_line,", "if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename):", "\"\"\"Check admin tests should exist under admin path T115 \"\"\"", "hacking import core import pycodestyle PYTHON_CLIENTS = ['cinder', 'glance', 'keystone',", "file except in compliance with the License. You may obtain", "be specified at the end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return", "\"\"\" if 'tempest/lib/' not in filename: return if ('tempest.config' in", "res: return (physical_line.find(res.group(1)), (\"T102: python clients import not allowed\" \"", "msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib should not", "@core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception attribute in PY3", "return ( 0, \"T117: Must apply `@decorators.attr(type=['negative'])`\" \" to all", "def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client imports from tempest/api &", "tests T102: Cannot import OpenStack python clients \"\"\" if \"tempest/api\"", "and '/test_' in filename: if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return", "(0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib should", "\"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return for line", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return if 'tempest/test.py'", "filename in ignored_list: return False if not METHOD.match(physical_line): return False", "re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def .+\")", "tests require a service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if", "line_number, lines): \"\"\"Check that service client names of DELETE should", "tempest.lib' in logical_line): return msg = (\"T112: tempest.lib should not", "return 0, msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that mutable object", "method return if 'self.delete(' not in line and 'self.delete_resource(' not", "Copyright 2013 IBM Corp. # # Licensed under the Apache", "tests have service tags T104: Scenario tests require a services", "under the Apache License, Version 2.0 (the \"License\"); you may", "METHOD = re.compile(r\"^ def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE", "re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\")", "if matches: services = matches.group(1).split(',') for service in services: service_name", "def get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service client", "return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can not be used in tests\")", "the end of a method return if 'self.get(' not in", "\"\"\" # NOTE(mtreinish) Scenario tests always need service tags, but", "yield (0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib", "or 'from tempest import config' in logical_line or 'oslo_config' in", "\" or show_<resource name>\") yield (0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line,", "path.' yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception", "``@decorators.attr(type=['negative'])`` applied to negative tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if", "\"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return for line", "should only be added if the service name isn't already", "0, \"T117: Must apply `@decorators.attr(type=['negative'])`\" \" to all negative API", "if pycodestyle.noqa(physical_line): return False return True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line,", ".+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS", "not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario tests require a service", "\" \"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if", "should exist under admin path T115 \"\"\" if 'tempest/api/' not", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "admin tests should exist under admin path.' yield(0, msg) @core.flake8ext", "yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to", "logical_line or 'import tempest' in logical_line): return if ('from tempest.lib'", "PY3\") if result: yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check", "tests always need service tags, but subdirs are # created", "return if not ('from tempest' in logical_line or 'import tempest'", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "to in writing, software # distributed under the License is", "as default argument N322: Method's default argument shouldn't be mutable", "'oslo_config' in logical_line): msg = ('T114: tempest.lib can not have", "re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class .+\")", "instead of uuid.uuid4() T113 \"\"\" if 'tempest/lib/' in filename: return", "False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client imports from", "or agreed to in writing, software # distributed under the", "only be added if the service name isn't already in", "= True return if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return (", "required by applicable law or agreed to in writing, software", "in modulepath: return (physical_line.find(service_name), \"T107: service tag should not be", "mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods", "mutable!\" if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check", "service tag isn't in the module path A service tag", "methods do not have the testtools.skip decorator T109 \"\"\" if", "mutable \"\"\" msg = \"N322: Method's default argument shouldn't be", "yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception attribute", "T112 \"\"\" if 'tempest/lib/' not in filename: return if not", "attribute in PY3 T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line) msg =", "in the module path A service tag should only be", "/resources/<id>] methods should be \" \"delete_<resource name>\") yield (0, msg)", "decorator \"\"\" if 'tempest/scenario/' in filename and '/test_' in filename:", "imports from tempest/api & tempest/scenario tests T102: Cannot import OpenStack", "service client names of DELETE should be consistent T111 \"\"\"", "def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\")", "physical_line, filename, 'ignored_list_T110.txt'): return for line in lines[line_number:]: if METHOD.match(line)", "if \"tempest/api\" in filename or \"tempest/scenario\" in filename: res =", "if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return for line in", "Apache License, Version 2.0 (the \"License\"); you may # not", "('self.show_resource(' not in line and 'self.list_resources(' not in line): continue", "msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that", "if 'tempest/lib/' not in filename: return if ('tempest.config' in logical_line", "exist under admin path.' yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check", "a method return if 'self.delete(' not in line and 'self.delete_resource('", "re.compile(r\"^ def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def", "def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a service tag isn't in", "(\"T110: [GET /resources] methods should be list_<resource name>s\" \" or", "if METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111: [DELETE /resources/<id>] methods should", "return if ('from tempest.lib' in logical_line or 'import tempest.lib' in", "if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117: Must", "(physical_line.find(service_name), \"T107: service tag should not be in path\") @core.flake8ext", "result = EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported 'message' Exception attribute", "agreed to in writing, software # distributed under the License", "RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)')", "in logical_line or 'import tempest.lib' in logical_line): return msg =", "distributed under the License is distributed on an \"AS IS\"", "METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110: [GET /resources] methods should be", "import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client imports from tempest/api & tempest/scenario", "if service_name in modulepath: return (physical_line.find(service_name), \"T107: service tag should", "in line and 'self.delete_resource(' not in line: continue if METHOD_DELETE_RESOURCE.match(logical_line):", "not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115: All admin tests should", "logical_line): return if ('from tempest.lib' in logical_line or 'import tempest.lib'", "if not _HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117: Must apply `@decorators.attr(type=['negative'])`\"", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "\"\"\"Check that scenario tests have service tags T104: Scenario tests", "added if the service name isn't already in the module", "\"\"\"Check that tests use data_utils.rand_uuid() instead of uuid.uuid4() T113 \"\"\"", "for service in services: service_name = service.strip().strip(\"'\") modulepath = os.path.split(filename)[0]", "use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext", "_HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117: Must apply `@decorators.attr(type=['negative'])`\" \" to", "= re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)')", "should not be in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check", "yield (0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines):", "msg = \"N322: Method's default argument shouldn't be mutable!\" if", "instead use \" \"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename,", "Tests should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0,", "not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg", "service client names of GET should be consistent T110 \"\"\"", "import re from hacking import core import pycodestyle PYTHON_CLIENTS =", "of GET should be consistent T110 \"\"\" if not _common_service_clients_check(logical_line,", "physical_line, filename, 'ignored_list_T111.txt'): return for line in lines[line_number:]: if METHOD.match(line)", "not use this file except in compliance with the License.", "if not ('from tempest' in logical_line or 'import tempest' in", "tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename):", "ignored_list_file) as f: for line in f: ignored_list.append(line.strip()) if filename", "writing, software # distributed under the License is distributed on", "are # created for services like heat which would cause", "return if 'uuid.uuid4()' not in logical_line: return msg = (\"T113:", "that scenario tests have service tags T104: Scenario tests require", "consistent T110 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return if 'tempest/test.py' in filename", "Cannot use testtools.skip decorator; instead use \" \"decorators.skip_because from tempest.lib\")", "\" \"delete_<resource name>\") yield (0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename):", "to negative tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename):", "no_mutable_default_args(logical_line): \"\"\"Check that mutable object isn't used as default argument", "argument shouldn't be mutable!\" if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext", "the License. You may obtain # a copy of the", "in filename: return if ('tempest.config' in logical_line or 'from tempest", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check", "use this file except in compliance with the License. You", "(\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield", "unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception attribute in PY3 T116 \"\"\"", "get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service client names", "from tempest/api & tempest/scenario tests T102: Cannot import OpenStack python", "with open('tempest/hacking/' + ignored_list_file) as f: for line in f:", "show_<resource name>\") yield (0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename,", "Must apply `@decorators.attr(type=['negative'])`\" \" to all negative API tests\" )", "or CLASS.match(line): # the end of a method return if", "False if not METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line): return False", "filename): \"\"\"Check admin tests should exist under admin path T115", "a service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return", "True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that", "for line in lines[line_number:]: if METHOD.match(line) or CLASS.match(line): # the", "('T114: tempest.lib can not have any dependency on tempest '", "All admin tests should exist under admin path.' yield(0, msg)", "def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do not have the testtools.skip", "continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111: [DELETE /resources/<id>] methods", "tags, but subdirs are # created for services like heat", "if 'tempest/lib/' not in filename: return if not ('from tempest'", "f: ignored_list.append(line.strip()) if filename in ignored_list: return False if not", "service tag should not be in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line,", "end of rand_name() argument T108 \"\"\" msg = \"T108: hyphen", "client names of DELETE should be consistent T111 \"\"\" if", "def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that scenario tests have service", "\" in tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename,", "Scenario tests require a services decorator \"\"\" if 'tempest/scenario/' in", "clients \"\"\" if \"tempest/api\" in filename or \"tempest/scenario\" in filename:", "if 'tempest/test.py' in filename or 'tempest/lib/' in filename: return if", "services = matches.group(1).split(',') for service in services: service_name = service.strip().strip(\"'\")", "that tempest.lib doesn't use tempest config T114 \"\"\" if 'tempest/lib/'", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "(0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do not", "T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported 'message'", "if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return if", "@core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib doesn't use tempest", "if not re.match('tempest/(lib/)?services/.*', filename): return False if ignored_list_file is not", "tempest.lib can not have any dependency on tempest ' 'config.')", "exist under admin path T115 \"\"\" if 'tempest/api/' not in", "Scenario tests require a service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename):", "filename): msg = 'T115: All admin tests should exist under", "\"License\"); you may # not use this file except in", "SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can not be used in", "(0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib doesn't", "path A service tag should only be added if the", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "Unsupported 'message' exception attribute in PY3 T116 \"\"\" result =", "return if 'tempest/test.py' in filename or 'tempest/lib/' in filename: return", "'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS))", "express or implied. See the # License for the specific", "if ('tempest.config' in logical_line or 'from tempest import config' in", "\"\"\"Check that tempest.lib should not import local tempest code T112", "not METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line): return False return True", "subdirs are # created for services like heat which would", "local tempest code to avoid \" \"circular dependency\") yield (0,", "service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a service tag isn't in the", "names of GET should be consistent T110 \"\"\" if not", "the Apache License, Version 2.0 (the \"License\"); you may #", "service in services: service_name = service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if", "(physical_line.find('def'), \"T104: Scenario tests require a service decorator\") @core.flake8ext def", "filename: res = PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)), (\"T102: python", "in logical_line or 'oslo_config' in logical_line): msg = ('T114: tempest.lib", "the end of rand_name() argument T108 \"\"\" msg = \"T108:", "tag isn't in the module path A service tag should", "logical_line or 'from tempest import config' in logical_line or 'oslo_config'", "See the # License for the specific language governing permissions", "Method's default argument shouldn't be mutable \"\"\" msg = \"N322:", "false negatives for # those tests, so just exclude the", "'/test_' in filename: if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'),", "T111 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return for", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do not have", "the testtools.skip decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109:", ".*Test.*\\(.*Admin.*\\):', logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115:", "not in logical_line: return msg = (\"T113: Tests should use", "NOTE(mtreinish) Scenario tests always need service tags, but subdirs are", "= (\"T110: [GET /resources] methods should be list_<resource name>s\" \"", "= os.path.split(filename)[0] if service_name in modulepath: return (physical_line.find(service_name), \"T107: service", "re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg =", "\"\"\" if 'tempest/api/' not in filename: return if not re.match(r'class", "services: service_name = service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if service_name in", "code T112 \"\"\" if 'tempest/lib/' not in filename: return if", "\"T107: service tag should not be in path\") @core.flake8ext def", "in filename: return if not ('from tempest' in logical_line or", "law or agreed to in writing, software # distributed under", "or 'import tempest' in logical_line): return if ('from tempest.lib' in", "return if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*',", "'swift', 'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client' %", "\"\"\"Check for client imports from tempest/api & tempest/scenario tests T102:", "test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE =", "admin path T115 \"\"\" if 'tempest/api/' not in filename: return", "'uuid.uuid4()' not in logical_line: return msg = (\"T113: Tests should", "T102: Cannot import OpenStack python clients \"\"\" if \"tempest/api\" in", "module path A service tag should only be added if", "Scenario tests always need service tags, but subdirs are #", "implied. See the # License for the specific language governing", "applied to negative tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*',", "if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that", "decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot use", "@core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do not have the", "filename, line_number, lines): \"\"\"Check that service client names of GET", "end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext def", "for client imports from tempest/api & tempest/scenario tests T102: Cannot", "allowed\" \" in tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line,", "tempest code T112 \"\"\" if 'tempest/lib/' not in filename: return", "core import pycodestyle PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova', 'swift',", "re from hacking import core import pycodestyle PYTHON_CLIENTS = ['cinder',", "def no_mutable_default_args(logical_line): \"\"\"Check that mutable object isn't used as default", "the module path A service tag should only be added", "names of DELETE should be consistent T111 \"\"\" if not", "and 'self.delete_resource(' not in line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg", "filename: matches = SCENARIO_DECORATOR.match(physical_line) if matches: services = matches.group(1).split(',') for", "of DELETE should be consistent T111 \"\"\" if not _common_service_clients_check(logical_line,", "# created for services like heat which would cause false", "uuid.uuid4() T113 \"\"\" if 'tempest/lib/' in filename: return if 'uuid.uuid4()'", "'message' Exception attribute in PY3\") if result: yield(0, msg) @core.flake8ext", "METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111: [DELETE /resources/<id>] methods should be", "msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that mutable object isn't used", "filename: return if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if not", "= re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext", "in logical_line): return msg = (\"T112: tempest.lib should not import", "(setUp|tearDown)Class can not be used in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line,", "Unsupported 'message' Exception attribute in PY3\") if result: yield(0, msg)", "return if 'self.get(' not in line and ('self.show_resource(' not in", "'T115: All admin tests should exist under admin path.' yield(0,", "= \"T108: hyphen should not be specified at the end", "RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that mutable", "r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for", "services like heat which would cause false negatives for #", "should be list_<resource name>s\" \" or show_<resource name>\") yield (0,", "'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION", "'|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR", "\"\"\" if 'tempest/scenario/' in filename and '/test_' in filename: if", "matches.group(1).split(',') for service in services: service_name = service.strip().strip(\"'\") modulepath =", "filename): if pycodestyle.noqa(physical_line): return if 'tempest/test.py' in filename or 'tempest/lib/'", "re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION =", "if res: return (physical_line.find(res.group(1)), (\"T102: python clients import not allowed\"", "module path. T107 \"\"\" # NOTE(mtreinish) Scenario tests always need", "if result: yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])``", "return False if ignored_list_file is not None: ignored_list = []", "METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS =", "tempest code to avoid \" \"circular dependency\") yield (0, msg)", "that service client names of GET should be consistent T110", "0, msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that mutable object isn't", "import pycodestyle PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron',", "msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests should exist", "object isn't used as default argument N322: Method's default argument", "False return True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines):", "filename): return False if ignored_list_file is not None: ignored_list =", "[DELETE /resources/<id>] methods should be \" \"delete_<resource name>\") yield (0,", "(\"T112: tempest.lib should not import local tempest code to avoid", "'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def", "the service name isn't already in the module path. T107", "client imports from tempest/api & tempest/scenario tests T102: Cannot import", "CLASS.match(line): # the end of a method return if 'self.delete('", "the License. import os import re from hacking import core", "client names of GET should be consistent T110 \"\"\" if", "(list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE", "attribute in PY3\") if result: yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line,", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "not be used in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check", "return False if pycodestyle.noqa(physical_line): return False return True @core.flake8ext def", "or 'import tempest.lib' in logical_line): return msg = (\"T112: tempest.lib", "'tempest/lib/' not in filename: return if ('tempest.config' in logical_line or", "not _HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117: Must apply `@decorators.attr(type=['negative'])`\" \"", "in line and ('self.show_resource(' not in line and 'self.list_resources(' not", "# # Licensed under the Apache License, Version 2.0 (the", "def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen at the end of", "line in lines[line_number:]: if METHOD.match(line) or CLASS.match(line): # the end", "tests use data_utils.rand_uuid() instead of uuid.uuid4() T113 \"\"\" if 'tempest/lib/'", "return msg = (\"T110: [GET /resources] methods should be list_<resource", "\"T108: hyphen should not be specified at the end of", "Cannot import OpenStack python clients \"\"\" if \"tempest/api\" in filename", "should not import local tempest code T112 \"\"\" if 'tempest/lib/'", "import os import re from hacking import core import pycodestyle", "service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return if", "filename: return if not ('from tempest' in logical_line or 'import", "name>\") yield (0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that", "f: for line in f: ignored_list.append(line.strip()) if filename in ignored_list:", "`@decorators.attr(type=['negative'])`\" \" to all negative API tests\" ) _HAVE_NEGATIVE_DECORATOR =", "\"tempest/scenario\" in filename: res = PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)),", "T110 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return for", "of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check", "if METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110: [GET /resources] methods should", "be mutable!\" if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line):", "\"\"\"Check that methods do not have the testtools.skip decorator T109", "SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\")", "use data_utils.rand_uuid() instead of uuid.uuid4() T113 \"\"\" if 'tempest/lib/' in", "'self.get(' not in line and ('self.show_resource(' not in line and", "obtain # a copy of the License at # #", "[GET /resources] methods should be list_<resource name>s\" \" or show_<resource", "tests should exist under admin path.' yield(0, msg) @core.flake8ext def", "require a service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line):", "be used in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that", "service name isn't already in the module path. T107 \"\"\"", "line and 'self.list_resources(' not in line): continue if METHOD_GET_RESOURCE.match(logical_line): return", "not ('from tempest' in logical_line or 'import tempest' in logical_line):", "/resources] methods should be list_<resource name>s\" \" or show_<resource name>\")", "from hacking import core import pycodestyle PYTHON_CLIENTS = ['cinder', 'glance',", "name>s\" \" or show_<resource name>\") yield (0, msg) @core.flake8ext def", "return if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return ( 0, \"T117:", "( 0, \"T117: Must apply `@decorators.attr(type=['negative'])`\" \" to all negative", "def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename): return", "Version 2.0 (the \"License\"); you may # not use this", "should not be specified at the end of rand_name()\" if", "(0, \"T109: Cannot use testtools.skip decorator; instead use \" \"decorators.skip_because", "of a method return if 'self.delete(' not in line and", "dependency on tempest ' 'config.') yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line,", "tempest' in logical_line or 'import tempest' in logical_line): return if", "return if not re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115: All admin", "line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111: [DELETE /resources/<id>]", "no hyphen at the end of rand_name() argument T108 \"\"\"", "\"\"\"Check that mutable object isn't used as default argument N322:", "['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron', 'ironic', 'heat', 'sahara'] PYTHON_CLIENT_RE", "not None: ignored_list = [] with open('tempest/hacking/' + ignored_list_file) as", "if 'tempest/lib/' in filename: return if 'uuid.uuid4()' not in logical_line:", "for # those tests, so just exclude the scenario tests.", "require a services decorator \"\"\" if 'tempest/scenario/' in filename and", "\"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot use testtools.skip decorator;", "not in line): continue if METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110:", "License for the specific language governing permissions and limitations #", "line): continue if METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110: [GET /resources]", "filename): \"\"\"Check that tempest.lib should not import local tempest code", "in logical_line or 'from tempest import config' in logical_line or", "\"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR =", "service tags T104: Scenario tests require a services decorator \"\"\"", "do not have the testtools.skip decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line):", "yield (0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests", "not re.match('tempest/(lib/)?services/.*', filename): return False if ignored_list_file is not None:", "filename): \"\"\"Check for client imports from tempest/api & tempest/scenario tests", "GET should be consistent T110 \"\"\" if not _common_service_clients_check(logical_line, physical_line,", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "heat which would cause false negatives for # those tests,", "filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename): return False if ignored_list_file", "T114 \"\"\" if 'tempest/lib/' not in filename: return if ('tempest.config'", "open('tempest/hacking/' + ignored_list_file) as f: for line in f: ignored_list.append(line.strip())", "tempest config T114 \"\"\" if 'tempest/lib/' not in filename: return", "= re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)')", "consistent T111 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return", "TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def .+\") METHOD_GET_RESOURCE =", "any dependency on tempest ' 'config.') yield(0, msg) @core.flake8ext def", "EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False", "def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests use data_utils.rand_uuid() instead of", "yield (0, \"T109: Cannot use testtools.skip decorator; instead use \"", "isn't already in the module path. T107 \"\"\" # NOTE(mtreinish)", "= re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR", "scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that scenario tests have service tags", "if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario tests require a", "negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative tests. T117 \"\"\"", "return msg = (\"T111: [DELETE /resources/<id>] methods should be \"", "data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext def", "from tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*',", "def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception attribute in PY3 T116", "OpenStack python clients \"\"\" if \"tempest/api\" in filename or \"tempest/scenario\"", "if filename in ignored_list: return False if not METHOD.match(physical_line): return", "service_name in modulepath: return (physical_line.find(service_name), \"T107: service tag should not", "@core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib should not import", "default argument N322: Method's default argument shouldn't be mutable \"\"\"", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", ".+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR =", "tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that scenario tests", "code to avoid \" \"circular dependency\") yield (0, msg) @core.flake8ext", "msg = (\"T111: [DELETE /resources/<id>] methods should be \" \"delete_<resource", "apply `@decorators.attr(type=['negative'])`\" \" to all negative API tests\" ) _HAVE_NEGATIVE_DECORATOR", "filename): \"\"\"Check that a service tag isn't in the module", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "on tempest ' 'config.') yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename):", "filename): \"\"\"Check that tests use data_utils.rand_uuid() instead of uuid.uuid4() T113", "delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service client names", "path. T107 \"\"\" # NOTE(mtreinish) Scenario tests always need service", "like heat which would cause false negatives for # those", "def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib should not import local", "'message' exception attribute in PY3 T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line)", "in filename: return if 'uuid.uuid4()' not in logical_line: return msg", "admin path.' yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message'", "filename, line_number, lines): \"\"\"Check that service client names of DELETE", "should be consistent T111 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename,", "msg = 'T115: All admin tests should exist under admin", "return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can not be", "\"delete_<resource name>\") yield (0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check", "governing permissions and limitations # under the License. import os", "be mutable \"\"\" msg = \"N322: Method's default argument shouldn't", "'config.') yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests", "T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR", "in filename and '/test_' in filename: if TEST_DEFINITION.match(physical_line): if not", "compliance with the License. You may obtain # a copy", "tags T104: Scenario tests require a services decorator \"\"\" if", "in services: service_name = service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if service_name", ".+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^ def .+\") METHOD_GET_RESOURCE", "os.path.split(filename)[0] if service_name in modulepath: return (physical_line.find(service_name), \"T107: service tag", "re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR =", "return if 'self.delete(' not in line and 'self.delete_resource(' not in", "@core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check that mutable object isn't used as", "@core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen at the end", "= re.compile(r\"^ def .+\") METHOD_GET_RESOURCE = re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE =", "hyphen at the end of rand_name() argument T108 \"\"\" msg", "('from tempest.lib' in logical_line or 'import tempest.lib' in logical_line): return", "import OpenStack python clients \"\"\" if \"tempest/api\" in filename or", "msg = (\"T110: [GET /resources] methods should be list_<resource name>s\"", "data_utils.rand_uuid() instead of uuid.uuid4() T113 \"\"\" if 'tempest/lib/' in filename:", "end of a method return if 'self.get(' not in line", "TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR =", "under admin path.' yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported", "\"T104: Scenario tests require a service decorator\") @core.flake8ext def no_setup_teardown_class_for_tests(physical_line,", "# Copyright 2013 IBM Corp. # # Licensed under the", "the # License for the specific language governing permissions and", "so just exclude the scenario tests. if 'tempest/scenario' not in", "if METHOD.match(line) or CLASS.match(line): # the end of a method", "# # Unless required by applicable law or agreed to", "= re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename):", "msg = (\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of", "IBM Corp. # # Licensed under the Apache License, Version", "line in f: ignored_list.append(line.strip()) if filename in ignored_list: return False", "in ignored_list: return False if not METHOD.match(physical_line): return False if", "_HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return", "\"\"\"Check that service client names of GET should be consistent", "modulepath = os.path.split(filename)[0] if service_name in modulepath: return (physical_line.find(service_name), \"T107:", "be \" \"delete_<resource name>\") yield (0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line,", "not in filename: return if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return", "tests. if 'tempest/scenario' not in filename: matches = SCENARIO_DECORATOR.match(physical_line) if", "return msg = (\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead", "the module path. T107 \"\"\" # NOTE(mtreinish) Scenario tests always", "line and ('self.show_resource(' not in line and 'self.list_resources(' not in", "be list_<resource name>s\" \" or show_<resource name>\") yield (0, msg)", "import local tempest code to avoid \" \"circular dependency\") yield", "\"tempest/api\" in filename or \"tempest/scenario\" in filename: res = PYTHON_CLIENT_RE.match(physical_line)", "@core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests should exist under", "re.match(r'.\\/tempest\\/api\\/.*\\/admin\\/.*', filename): msg = 'T115: All admin tests should exist", "hyphen should not be specified at the end of rand_name()\"", "'self.list_resources(' not in line): continue if METHOD_GET_RESOURCE.match(logical_line): return msg =", "PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*')", "under the License. import os import re from hacking import", "return True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check", "= (\"T112: tempest.lib should not import local tempest code to", "lines[line_number:]: if METHOD.match(line) or CLASS.match(line): # the end of a", "if 'self.get(' not in line and ('self.show_resource(' not in line", "\"circular dependency\") yield (0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check", "previous_logical): \"\"\"Check that scenario tests have service tags T104: Scenario", "not in filename: return if ('tempest.config' in logical_line or 'from", "logical_line, filename, line_number, lines): \"\"\"Check that service client names of", "CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile(", "= ('T114: tempest.lib can not have any dependency on tempest", "should be \" \"delete_<resource name>\") yield (0, msg) @core.flake8ext def", "msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line): \"\"\"Check Unsupported 'message' exception attribute in", "no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen at the end of rand_name()", "use tempest config T114 \"\"\" if 'tempest/lib/' not in filename:", "a services decorator \"\"\" if 'tempest/scenario/' in filename and '/test_'", "have the testtools.skip decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0,", "filename or \"tempest/scenario\" in filename: res = PYTHON_CLIENT_RE.match(physical_line) if res:", "2.0 (the \"License\"); you may # not use this file", "the scenario tests. if 'tempest/scenario' not in filename: matches =", "not be in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no", "T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot use testtools.skip", "def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative tests. T117", "= re.compile(r\"^\\s*def (list|show)\\_.+\") METHOD_DELETE_RESOURCE = re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class", "filename): \"\"\"Check no hyphen at the end of rand_name() argument", "import config' in logical_line or 'oslo_config' in logical_line): msg =", "for services like heat which would cause false negatives for", "that a service tag isn't in the module path A", "@core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service", "\"\"\" msg = \"N322: Method's default argument shouldn't be mutable!\"", "T108 \"\"\" msg = \"T108: hyphen should not be specified", "return False if not METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line): return", "METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line): return False return True @core.flake8ext", "return False return True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename, line_number,", "in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen at", "if not _common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return for line in", "_common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T110.txt'): return for line in lines[line_number:]: if", "to avoid \" \"circular dependency\") yield (0, msg) @core.flake8ext def", "= 'T115: All admin tests should exist under admin path.'", "NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True return if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR:", "return (physical_line.find('def'), \"T104: Scenario tests require a service decorator\") @core.flake8ext", "used as default argument N322: Method's default argument shouldn't be", "yield (0, msg) @core.flake8ext def no_testtools_skip_decorator(logical_line): \"\"\"Check that methods do", "T107 \"\"\" # NOTE(mtreinish) Scenario tests always need service tags,", "that methods do not have the testtools.skip decorator T109 \"\"\"", "A service tag should only be added if the service", "of rand_name() argument T108 \"\"\" msg = \"T108: hyphen should", "msg = ('T114: tempest.lib can not have any dependency on", "by applicable law or agreed to in writing, software #", "\"T105: (setUp|tearDown)Class can not be used in tests\") @core.flake8ext def", "should be consistent T110 \"\"\" if not _common_service_clients_check(logical_line, physical_line, filename,", "= False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client imports", "False if pycodestyle.noqa(physical_line): return False return True @core.flake8ext def get_resources_on_service_clients(physical_line,", "in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a service", "not in filename: matches = SCENARIO_DECORATOR.match(physical_line) if matches: services =", "\"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR", "not have the testtools.skip decorator T109 \"\"\" if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield", "+ ignored_list_file) as f: for line in f: ignored_list.append(line.strip()) if", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "in tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical):", "filename): \"\"\"Check that tempest.lib doesn't use tempest config T114 \"\"\"", "path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen at the", "in PY3\") if result: yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename):", "argument T108 \"\"\" msg = \"T108: hyphen should not be", "\"\"\"Check that tempest.lib doesn't use tempest config T114 \"\"\" if", "python clients import not allowed\" \" in tempest/api/* or tempest/scenario/*", "lines): \"\"\"Check that service client names of GET should be", "'tempest/lib/' not in filename: return if not ('from tempest' in", "TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario tests require", "filename and '/test_' in filename: if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical):", "that tests use data_utils.rand_uuid() instead of uuid.uuid4() T113 \"\"\" if", "'heat', 'sahara'] PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION =", "services decorator \"\"\" if 'tempest/scenario/' in filename and '/test_' in", "return (physical_line.find(res.group(1)), (\"T102: python clients import not allowed\" \" in", "not in line and 'self.delete_resource(' not in line: continue if", "= (\"T111: [DELETE /resources/<id>] methods should be \" \"delete_<resource name>\")", "argument N322: Method's default argument shouldn't be mutable \"\"\" msg", "ignored_list_file is not None: ignored_list = [] with open('tempest/hacking/' +", "in filename or 'tempest/lib/' in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return", "@core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests use data_utils.rand_uuid() instead", "filename, 'ignored_list_T111.txt'): return for line in lines[line_number:]: if METHOD.match(line) or", "logical_line or 'oslo_config' in logical_line): msg = ('T114: tempest.lib can", "decorator; instead use \" \"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line, physical_line,", "filename, 'ignored_list_T110.txt'): return for line in lines[line_number:]: if METHOD.match(line) or", "can not be used in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename):", "be in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename): \"\"\"Check no hyphen", "pycodestyle.noqa(physical_line): return if 'tempest/test.py' in filename or 'tempest/lib/' in filename:", "name isn't already in the module path. T107 \"\"\" #", "in filename: res = PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)), (\"T102:", "and limitations # under the License. import os import re", "may obtain # a copy of the License at #", "default argument shouldn't be mutable!\" if mutable_default_args.match(logical_line): yield (0, msg)", "msg = \"T108: hyphen should not be specified at the", "EX_ATTRIBUTE.search(logical_line) msg = (\"[T116] Unsupported 'message' Exception attribute in PY3\")", "Unless required by applicable law or agreed to in writing,", "SCENARIO_DECORATOR.match(physical_line) if matches: services = matches.group(1).split(',') for service in services:", "\"\"\" if 'tempest/lib/' in filename: return if 'uuid.uuid4()' not in", "local tempest code T112 \"\"\" if 'tempest/lib/' not in filename:", "in logical_line): msg = ('T114: tempest.lib can not have any", "in filename: return if not re.match(r'class .*Test.*\\(.*Admin.*\\):', logical_line): return if", "'import tempest' in logical_line): return if ('from tempest.lib' in logical_line", "_HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def import_no_clients_in_api_and_scenario_tests(physical_line, filename): \"\"\"Check for client", "matches = SCENARIO_DECORATOR.match(physical_line) if matches: services = matches.group(1).split(',') for service", "that mutable object isn't used as default argument N322: Method's", "end of a method return if 'self.delete(' not in line", "('from tempest' in logical_line or 'import tempest' in logical_line): return", "msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests use data_utils.rand_uuid()", "[] with open('tempest/hacking/' + ignored_list_file) as f: for line in", "'tempest/lib/' in filename: return if 'uuid.uuid4()' not in logical_line: return", "re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR = False @core.flake8ext def", "logical_line): return msg = (\"T112: tempest.lib should not import local", "applicable law or agreed to in writing, software # distributed", "re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))') NEGATIVE_TEST_DECORATOR = re.compile( r'\\s*@decorators\\.attr\\(type=.*negative.*\\)') _HAVE_NEGATIVE_DECORATOR", "in filename: matches = SCENARIO_DECORATOR.match(physical_line) if matches: services = matches.group(1).split(',')", "(physical_line.find(res.group(1)), (\"T102: python clients import not allowed\" \" in tempest/api/*", "tempest ' 'config.') yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check", "just exclude the scenario tests. if 'tempest/scenario' not in filename:", "(setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def", "not in line and 'self.list_resources(' not in line): continue if", "'import tempest.lib' in logical_line): return msg = (\"T112: tempest.lib should", "OF ANY KIND, either express or implied. See the #", "'tempest/scenario/' in filename and '/test_' in filename: if TEST_DEFINITION.match(physical_line): if", "rand_name() argument T108 \"\"\" msg = \"T108: hyphen should not", "or show_<resource name>\") yield (0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line,", "= re.compile(r\"^\\s*def delete_.+\") CLASS = re.compile(r\"^class .+\") EX_ATTRIBUTE = re.compile(r'(\\s+|\\()(e|ex|exc|exception).message(\\s+|\\))')", "specified at the end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0,", "return msg = (\"T112: tempest.lib should not import local tempest", "in logical_line or 'import tempest' in logical_line): return if ('from", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can", "mutable object isn't used as default argument N322: Method's default", "continue if METHOD_GET_RESOURCE.match(logical_line): return msg = (\"T110: [GET /resources] methods", "if ('from tempest.lib' in logical_line or 'import tempest.lib' in logical_line):", "= re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD", "line and 'self.delete_resource(' not in line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return", "mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD = re.compile(r\"^", "used in tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a", "= \"N322: Method's default argument shouldn't be mutable!\" if mutable_default_args.match(logical_line):", "methods should be list_<resource name>s\" \" or show_<resource name>\") yield", "physical_line, filename, ignored_list_file=None): if not re.match('tempest/(lib/)?services/.*', filename): return False if", "testtools.skip decorator; instead use \" \"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line,", "isn't used as default argument N322: Method's default argument shouldn't", "name>\") yield (0, msg) @core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number,", "the end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext", "be added if the service name isn't already in the", "Method's default argument shouldn't be mutable!\" if mutable_default_args.match(logical_line): yield (0,", "logical_line: return msg = (\"T113: Tests should use data_utils.rand_uuid()/rand_uuid_hex() \"", "filename, previous_logical): \"\"\"Check that scenario tests have service tags T104:", "should use data_utils.rand_uuid()/rand_uuid_hex() \" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg)", "@core.flake8ext def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service", "or 'oslo_config' in logical_line): msg = ('T114: tempest.lib can not", "in line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg = (\"T111: [DELETE", "T115 \"\"\" if 'tempest/api/' not in filename: return if not", "result: yield(0, msg) @core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied", "PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron', 'ironic', 'heat',", "either express or implied. See the # License for the", "cause false negatives for # those tests, so just exclude", "as f: for line in f: ignored_list.append(line.strip()) if filename in", "re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\") TESTTOOLS_SKIP_DECORATOR = re.compile(r'\\s*@testtools\\.skip\\((.*)\\)') METHOD =", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "use_rand_uuid_instead_of_uuid4(logical_line, filename): \"\"\"Check that tests use data_utils.rand_uuid() instead of uuid.uuid4()", "# those tests, so just exclude the scenario tests. if", "may # not use this file except in compliance with", "or 'tempest/lib/' in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105:", "tempest import config' in logical_line or 'oslo_config' in logical_line): msg", "and 'self.list_resources(' not in line): continue if METHOD_GET_RESOURCE.match(logical_line): return msg", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "tempest/scenario tests T102: Cannot import OpenStack python clients \"\"\" if", "\"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename):", "yield (0, msg) @core.flake8ext def dont_import_local_tempest_into_lib(logical_line, filename): \"\"\"Check that tempest.lib", "of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext def no_mutable_default_args(logical_line):", "you may # not use this file except in compliance", "in logical_line): return if ('from tempest.lib' in logical_line or 'import", "use testtools.skip decorator; instead use \" \"decorators.skip_because from tempest.lib\") def", "filename: if TEST_DEFINITION.match(physical_line): if not SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario", "# the end of a method return if 'self.get(' not", "\"T109: Cannot use testtools.skip decorator; instead use \" \"decorators.skip_because from", "SCENARIO_DECORATOR.match(previous_logical): return (physical_line.find('def'), \"T104: Scenario tests require a service decorator\")", "which would cause false negatives for # those tests, so", "a service tag isn't in the module path A service", "re.compile(r'^\\s+def (setUp|tearDown)Class') SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args =", "in PY3 T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line) msg = (\"[T116]", "shouldn't be mutable!\" if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def", "= service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if service_name in modulepath: return", "# under the License. import os import re from hacking", "def delete_resources_on_service_clients(physical_line, logical_line, filename, line_number, lines): \"\"\"Check that service client", "pycodestyle PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron', 'ironic',", "in the module path. T107 \"\"\" # NOTE(mtreinish) Scenario tests", "\"\"\" msg = \"T108: hyphen should not be specified at", "if 'tempest/scenario' not in filename: matches = SCENARIO_DECORATOR.match(physical_line) if matches:", "or \"tempest/scenario\" in filename: res = PYTHON_CLIENT_RE.match(physical_line) if res: return", "if 'uuid.uuid4()' not in logical_line: return msg = (\"T113: Tests", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "not allowed\" \" in tempest/api/* or tempest/scenario/* tests\")) @core.flake8ext def", "tag should not be in path\") @core.flake8ext def no_hyphen_at_end_of_rand_name(logical_line, filename):", "if not METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line): return False return", "exception attribute in PY3 T116 \"\"\" result = EX_ATTRIBUTE.search(logical_line) msg", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "msg = (\"T112: tempest.lib should not import local tempest code", "\"\"\" if 'tempest/lib/' not in filename: return if not ('from", "tempest.lib should not import local tempest code to avoid \"", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "at the end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg", "'self.delete_resource(' not in line: continue if METHOD_DELETE_RESOURCE.match(logical_line): return msg =", "limitations # under the License. import os import re from", "admin tests should exist under admin path T115 \"\"\" if", "or tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that", "shouldn't be mutable \"\"\" msg = \"N322: Method's default argument", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "' 'config.') yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin", "\"\"\"Check no hyphen at the end of rand_name() argument T108", "# the end of a method return if 'self.delete(' not", "\" \"circular dependency\") yield (0, msg) @core.flake8ext def use_rand_uuid_instead_of_uuid4(logical_line, filename):", "global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if NEGATIVE_TEST_DECORATOR.match(physical_line): _HAVE_NEGATIVE_DECORATOR = True", "(\"T102: python clients import not allowed\" \" in tempest/api/* or", "config' in logical_line or 'oslo_config' in logical_line): msg = ('T114:", "\" to all negative API tests\" ) _HAVE_NEGATIVE_DECORATOR = False", "negatives for # those tests, so just exclude the scenario", "service tags, but subdirs are # created for services like", "for the specific language governing permissions and limitations # under", "SCENARIO_DECORATOR = re.compile(r'\\s*@.*services\\((.*)\\)') RAND_NAME_HYPHEN_RE = re.compile(r\".*rand_name\\(.+[\\-\\_][\\\"\\']\\)\") mutable_default_args = re.compile(r\"^\\s*def .+\\((.+=\\{\\}|.+=\\[\\])\")", "negative tests. T117 \"\"\" global _HAVE_NEGATIVE_DECORATOR if re.match(r'.\\/tempest\\/api\\/.*_negative.*', filename): if", "service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if service_name in modulepath: return (physical_line.find(service_name),", "TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot use testtools.skip decorator; instead use", "METHOD.match(line) or CLASS.match(line): # the end of a method return", "\"\"\"Check that a service tag isn't in the module path", "tests require a services decorator \"\"\" if 'tempest/scenario/' in filename", "at the end of rand_name() argument T108 \"\"\" msg =", "ignored_list: return False if not METHOD.match(physical_line): return False if pycodestyle.noqa(physical_line):", "service tag should only be added if the service name", "\"decorators.skip_because from tempest.lib\") def _common_service_clients_check(logical_line, physical_line, filename, ignored_list_file=None): if not", "& tempest/scenario tests T102: Cannot import OpenStack python clients \"\"\"", "uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that", "except in compliance with the License. You may obtain #", "\" \"instead of uuid.uuid4()/uuid.uuid4().hex\") yield (0, msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line,", "Exception attribute in PY3\") if result: yield(0, msg) @core.flake8ext def", "if TESTTOOLS_SKIP_DECORATOR.match(logical_line): yield (0, \"T109: Cannot use testtools.skip decorator; instead", "is not None: ignored_list = [] with open('tempest/hacking/' + ignored_list_file)", "should exist under admin path.' yield(0, msg) @core.flake8ext def unsupported_exception_attribute_PY3(logical_line):", "None: ignored_list = [] with open('tempest/hacking/' + ignored_list_file) as f:", "_HAVE_NEGATIVE_DECORATOR = True return if TEST_DEFINITION.match(physical_line): if not _HAVE_NEGATIVE_DECORATOR: return", "@core.flake8ext def negative_test_attribute_always_applied_to_negative_tests(physical_line, filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative tests.", "not in filename: return if not ('from tempest' in logical_line", "language governing permissions and limitations # under the License. import", "_common_service_clients_check(logical_line, physical_line, filename, 'ignored_list_T111.txt'): return for line in lines[line_number:]: if", "import local tempest code T112 \"\"\" if 'tempest/lib/' not in", "License. You may obtain # a copy of the License", "if 'self.delete(' not in line and 'self.delete_resource(' not in line:", "msg) @core.flake8ext def dont_use_config_in_tempest_lib(logical_line, filename): \"\"\"Check that tempest.lib doesn't use", "'from tempest import config' in logical_line or 'oslo_config' in logical_line):", "ANY KIND, either express or implied. See the # License", "# distributed under the License is distributed on an \"AS", "tempest/scenario/* tests\")) @core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that scenario", "lines): \"\"\"Check that service client names of DELETE should be", "of a method return if 'self.get(' not in line and", "# Unless required by applicable law or agreed to in", "filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can not", "import core import pycodestyle PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova',", "not be specified at the end of rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line):", "@core.flake8ext def no_setup_teardown_class_for_tests(physical_line, filename): if pycodestyle.noqa(physical_line): return if 'tempest/test.py' in", "matches: services = matches.group(1).split(',') for service in services: service_name =", "list_<resource name>s\" \" or show_<resource name>\") yield (0, msg) @core.flake8ext", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "@core.flake8ext def scenario_tests_need_service_tags(physical_line, filename, previous_logical): \"\"\"Check that scenario tests have", "tests\") @core.flake8ext def service_tags_not_in_module_path(physical_line, filename): \"\"\"Check that a service tag", "yield(0, msg) @core.flake8ext def dont_put_admin_tests_on_nonadmin_path(logical_line, filename): \"\"\"Check admin tests should", "tests, so just exclude the scenario tests. if 'tempest/scenario' not", "\"\"\"Check that service client names of DELETE should be consistent", "should not import local tempest code to avoid \" \"circular", "filename): \"\"\"Check ``@decorators.attr(type=['negative'])`` applied to negative tests. T117 \"\"\" global", "'tempest/test.py' in filename or 'tempest/lib/' in filename: return if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line):", "if 'tempest/scenario/' in filename and '/test_' in filename: if TEST_DEFINITION.match(physical_line):", "and ('self.show_resource(' not in line and 'self.list_resources(' not in line):", "methods should be \" \"delete_<resource name>\") yield (0, msg) @core.flake8ext", "of uuid.uuid4() T113 \"\"\" if 'tempest/lib/' in filename: return if", "isn't in the module path A service tag should only", "but subdirs are # created for services like heat which", "msg = (\"[T116] Unsupported 'message' Exception attribute in PY3\") if", "'ignored_list_T110.txt'): return for line in lines[line_number:]: if METHOD.match(line) or CLASS.match(line):", "method return if 'self.get(' not in line and ('self.show_resource(' not", "T113 \"\"\" if 'tempest/lib/' in filename: return if 'uuid.uuid4()' not", "if the service name isn't already in the module path.", "for line in f: ignored_list.append(line.strip()) if filename in ignored_list: return", "License. import os import re from hacking import core import", "rand_name()\" if RAND_NAME_HYPHEN_RE.match(logical_line): return 0, msg @core.flake8ext def no_mutable_default_args(logical_line): \"\"\"Check", "would cause false negatives for # those tests, so just", "python clients \"\"\" if \"tempest/api\" in filename or \"tempest/scenario\" in", "pycodestyle.noqa(physical_line): return False return True @core.flake8ext def get_resources_on_service_clients(physical_line, logical_line, filename,", "not import local tempest code T112 \"\"\" if 'tempest/lib/' not", "res = PYTHON_CLIENT_RE.match(physical_line) if res: return (physical_line.find(res.group(1)), (\"T102: python clients", "service_name = service.strip().strip(\"'\") modulepath = os.path.split(filename)[0] if service_name in modulepath:", "ignored_list = [] with open('tempest/hacking/' + ignored_list_file) as f: for", "\"\"\"Check Unsupported 'message' exception attribute in PY3 T116 \"\"\" result", "% '|'.join(PYTHON_CLIENTS)) TEST_DEFINITION = re.compile(r'^\\s*def test.*') SETUP_TEARDOWN_CLASS_DEFINITION = re.compile(r'^\\s+def (setUp|tearDown)Class')", "if SETUP_TEARDOWN_CLASS_DEFINITION.match(physical_line): return (physical_line.find('def'), \"T105: (setUp|tearDown)Class can not be used", "or implied. See the # License for the specific language" ]
[ "return 0 controller = Controller() server = SimpleXMLRPCServer.SimpleXMLRPCServer((\"d6349.mysql.zone.ee\", 7000)) server.register_instance(controller)", "return 0 def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on %i' %", "turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off %i' % (i)) return 0", "return 0 def set_analog(self, i, level): if (i == 1):", "(i)) return 0 def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off %i'", "self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0", "from K8055Controller import K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class Controller:", "1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0 controller = Controller() server", "K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0 def turn_on(self,", "on %i' % (i)) return 0 def turn_off(self, i): self.k8055.turn_off(i)", "SimpleXMLRPCServer import sys import logging from K8055Controller import K8055Controller logging.basicConfig()", "self.k8055.turn_on(i) controller_log.debug('turned on %i' % (i)) return 0 def turn_off(self,", "def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off %i' % (i)) return", "%i' % (i)) return 0 def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned", "__init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return", "self.k8055.reset() controller_log.debug(\"reset\") return 0 def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on", "set_analog(self, i, level): if (i == 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level)", "import K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class Controller: def __init__(self):", "i): self.k8055.turn_on(i) controller_log.debug('turned on %i' % (i)) return 0 def", "turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on %i' % (i)) return 0", "= K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0 def", "def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on %i' % (i)) return", "else: self.k8055.set_analog2(level) return 0 controller = Controller() server = SimpleXMLRPCServer.SimpleXMLRPCServer((\"d6349.mysql.zone.ee\",", "% (i)) return 0 def set_analog(self, i, level): if (i", "self.k8055.set_analog2(level) return 0 controller = Controller() server = SimpleXMLRPCServer.SimpleXMLRPCServer((\"d6349.mysql.zone.ee\", 7000))", "def set_analog(self, i, level): if (i == 1): self.k8055.set_analog1(level) else:", "def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0 def turn_on(self, i): self.k8055.turn_on(i)", "0 def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off %i' % (i))", "logging.getLogger(\"Controller\") class Controller: def __init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def", "return 0 def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off %i' %", "level): if (i == 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0", "(i == 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0 controller =", "import SimpleXMLRPCServer import sys import logging from K8055Controller import K8055Controller", "if (i == 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0 controller", "controller_log.debug('turned off %i' % (i)) return 0 def set_analog(self, i,", "import logging from K8055Controller import K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\")", "import sys import logging from K8055Controller import K8055Controller logging.basicConfig() controller_log", "reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0 def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned", "0 def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on %i' % (i))", "controller_log.debug('turned on %i' % (i)) return 0 def turn_off(self, i):", "Controller: def __init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset()", "% (i)) return 0 def turn_off(self, i): self.k8055.turn_off(i) controller_log.debug('turned off", "controller_log = logging.getLogger(\"Controller\") class Controller: def __init__(self): self.k8055 = K8055Controller()", "= logging.getLogger(\"Controller\") class Controller: def __init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\")", "K8055Controller import K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class Controller: def", "sys import logging from K8055Controller import K8055Controller logging.basicConfig() controller_log =", "off %i' % (i)) return 0 def set_analog(self, i, level):", "class Controller: def __init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def reset(self):", "0 controller = Controller() server = SimpleXMLRPCServer.SimpleXMLRPCServer((\"d6349.mysql.zone.ee\", 7000)) server.register_instance(controller) server.serve_forever()", "0 def set_analog(self, i, level): if (i == 1): self.k8055.set_analog1(level)", "self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0 controller = Controller() server =", "self.k8055.turn_off(i) controller_log.debug('turned off %i' % (i)) return 0 def set_analog(self,", "i, level): if (i == 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return", "%i' % (i)) return 0 def set_analog(self, i, level): if", "controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\") return 0 def turn_on(self, i):", "i): self.k8055.turn_off(i) controller_log.debug('turned off %i' % (i)) return 0 def", "logging from K8055Controller import K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class", "K8055Controller logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class Controller: def __init__(self): self.k8055", "== 1): self.k8055.set_analog1(level) else: self.k8055.set_analog2(level) return 0 controller = Controller()", "def __init__(self): self.k8055 = K8055Controller() controller_log.debug(\"initialized\") def reset(self): self.k8055.reset() controller_log.debug(\"reset\")", "(i)) return 0 def set_analog(self, i, level): if (i ==", "controller_log.debug(\"reset\") return 0 def turn_on(self, i): self.k8055.turn_on(i) controller_log.debug('turned on %i'", "logging.basicConfig() controller_log = logging.getLogger(\"Controller\") class Controller: def __init__(self): self.k8055 =" ]
[]
[ "trouble sleeping, changes in appetite or weight, loss of energy,", "ajay = SentimentIntensityAnalyzer() completeScore = 0 questionWeights = [0.05, 0.20,", "of this type of depression \" + \"include trouble sleeping,", "such as psychotherapy and medication, may also be \" +", "\" + \"for depression, such as psychotherapy and medication, may", "[] score = 0 count = 0 # print (count)", "depressive symptoms, \" + \"such as appetite and sleep changes,", "of the picture.\") else: return (\"The classic depression type, major", "natural daily \" + \"rhythms, in the eyes' sensitivity to", "result from alterations in the body's natural daily \" +", "in paragraph: #Split Paragraph on basis of '.' or ?", "\" + \"emerges as days get shorter in the fall", "to function day to \" + \"but feel low or", "return (\"The classic depression type, major depression is a state", "count += 1 completeScore += (score/count)*questionWeights[i] #print(completeScore) if (completeScore >=", "in range(10): results = [] score = 0 count =", "depression. Many \" + \"people with this type of depression", "energy, \" + \"and feeling worthless. Thoughts of death or", "#Split Paragraph on basis of '.' or ? or !.", "in the eyes' sensitivity to light, or in how chemical", "the picture.\") else: return (\"The classic depression type, major depression", "\"emerges as days get shorter in the fall and winter.", "time. Some depressive symptoms, \" + \"such as appetite and", "<filename>models2.py import nltk import re import sys from sys import", "Paragraph on basis of '.' or ? or !. for", "\"rhythms, in the eyes' sensitivity to light, or in how", "0.20, 0.10] print ans ansList = ans.split(\"$\") for j in", "+= 1 completeScore += (score/count)*questionWeights[i] #print(completeScore) if (completeScore >= 0.1):", "depression type are able to function day to \" +", "for i in range(10): results = [] score = 0", "This type of depression \" + \"emerges as days get", "\" + \"type of depression refers to low mood that", "major depression. Many \" + \"people with this type of", "Thoughts of death or suicide may occur. It is \"", "changes, low energy, low self-esteem, or \" + \"hopelessness, are", "+ \"change may result from alterations in the body's natural", "0 count = 0 # print (count) for paragraph in", "medication. For some people with \" + \"severe depression that", "dark \" + \"mood is all-consuming and one loses interest", "part of the picture.\") else: return (\"The classic depression type,", "[0.05, 0.20, 0.05, 0.05, 0.05, 0.20, 0.05, 0.05, 0.20, 0.10]", "def ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore = 0 questionWeights =", "as appetite and sleep changes, low energy, low self-esteem, or", "for l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss = ajay.polarity_scores(l) results.append(ss);", "1 completeScore += (score/count)*questionWeights[i] #print(completeScore) if (completeScore >= 0.1): return", "especially intense light source. The usual treatments \" + \"for", "\" + \"change may result from alterations in the body's", "winter. The mood \" + \"change may result from alterations", "usually pleasurable. Symptoms of this type of depression \" +", "j in range(10): print ansList[j] for i in range(10): results", "\" + \"but feel low or joyless much of the", "print(l) ss = ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score += ss['compound']", "source. The usual treatments \" + \"for depression, such as", "+ \"for depression, such as psychotherapy and medication, may also", "ones \" + \"that are usually pleasurable. Symptoms of this", "all-consuming and one loses interest in activities, even ones \"", "ans ansList = ans.split(\"$\") for j in range(10): print ansList[j]", "occur. It is \" + \"usually treated with psychotherapy and", "the eyes' sensitivity to light, or in how chemical \"", "eyes' sensitivity to light, or in how chemical \" +", "loses interest in activities, even ones \" + \"that are", "major depression is a state where a dark \" +", "# print(ss['compound']) score += ss['compound'] count += 1 completeScore +=", "\"that are usually pleasurable. Symptoms of this type of depression", "ansList = ans.split(\"$\") for j in range(10): print ansList[j] for", "(completeScore >= -0.1): return (\"Seasonal affective disorder (SAD). This type", "with this type of depression type are able to function", "feeling worthless. Thoughts of death or suicide may occur. It", "It is \" + \"usually treated with psychotherapy and medication.", "or antidepressant \" + \"medications, electroconvulsive therapy may be effective.\")", "(\"Persistent depressive disorder. Formerly called dysthymia, this \" + \"type", "(completeScore >= 0.1): return \"False Alarm! You don't have Depression.\"", "that has lasted for at least \" + \"two years", "type, major depression is a state where a dark \"", "line in paragraph: #Split Paragraph on basis of '.' or", "low mood that has lasted for at least \" +", "\" + \"two years but may not reach the intensity", "-0.4): return (\"Persistent depressive disorder. Formerly called dysthymia, this \"", "0 questionWeights = [0.05, 0.20, 0.05, 0.05, 0.05, 0.20, 0.05,", "SentimentIntensityAnalyzer def ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore = 0 questionWeights", "The leading \" + \"treatment is light therapy, which involves", "depression, such as psychotherapy and medication, may also be \"", "return (\"Persistent depressive disorder. Formerly called dysthymia, this \" +", "+ \"hopelessness, are usually part of the picture.\") else: return", "the fall and winter. The mood \" + \"change may", "depression type, major depression is a state where a dark", "0.05, 0.20, 0.05, 0.05, 0.20, 0.10] print ans ansList =", "in the fall and winter. The mood \" + \"change", "people with \" + \"severe depression that isn't alleviated with", "+ \"include trouble sleeping, changes in appetite or weight, loss", "from nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore", "+ \"rhythms, in the eyes' sensitivity to light, or in", "depression \" + \"include trouble sleeping, changes in appetite or", "questionWeights = [0.05, 0.20, 0.05, 0.05, 0.05, 0.20, 0.05, 0.05,", "leading \" + \"treatment is light therapy, which involves daily", "Some depressive symptoms, \" + \"such as appetite and sleep", "melatonin function. The leading \" + \"treatment is light therapy,", "for paragraph in ansList: for line in paragraph: #Split Paragraph", "interest in activities, even ones \" + \"that are usually", "the time. Some depressive symptoms, \" + \"such as appetite", "\"treatment is light therapy, which involves daily sessions sitting \"", "For some people with \" + \"severe depression that isn't", "# print (count) for paragraph in ansList: for line in", "to \" + \"but feel low or joyless much of", "\"and feeling worthless. Thoughts of death or suicide may occur.", "+= (score/count)*questionWeights[i] #print(completeScore) if (completeScore >= 0.1): return \"False Alarm!", "therapy, which involves daily sessions sitting \" + \"close to", "of depression \" + \"include trouble sleeping, changes in appetite", "(\"The classic depression type, major depression is a state where", "type of depression \" + \"include trouble sleeping, changes in", "or ? or !. for l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l)", "day to \" + \"but feel low or joyless much", "reach the intensity of major depression. Many \" + \"people", "from sys import argv from nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans):", "where a dark \" + \"mood is all-consuming and one", "or suicide may occur. It is \" + \"usually treated", "for j in range(10): print ansList[j] for i in range(10):", "some people with \" + \"severe depression that isn't alleviated", "Depression.\" elif (completeScore >= -0.1): return (\"Seasonal affective disorder (SAD).", "\" + \"usually treated with psychotherapy and medication. For some", "= [0.05, 0.20, 0.05, 0.05, 0.05, 0.20, 0.05, 0.05, 0.20,", "Formerly called dysthymia, this \" + \"type of depression refers", "in how chemical \" + \"messengers like serotonin and melatonin", "shorter in the fall and winter. The mood \" +", "are usually part of the picture.\") else: return (\"The classic", "type are able to function day to \" + \"but", "sessions sitting \" + \"close to an especially intense light", "+ \"and feeling worthless. Thoughts of death or suicide may", "+ \"but feel low or joyless much of the time.", "with psychotherapy or antidepressant \" + \"medications, electroconvulsive therapy may", "sleeping, changes in appetite or weight, loss of energy, \"", "+ \"severe depression that isn't alleviated with psychotherapy or antidepressant", "at least \" + \"two years but may not reach", "\" + \"close to an especially intense light source. The", "+ \"mood is all-consuming and one loses interest in activities,", "mood \" + \"change may result from alterations in the", "+ \"messengers like serotonin and melatonin function. The leading \"", "+ \"type of depression refers to low mood that has", "self-esteem, or \" + \"hopelessness, are usually part of the", "return \"False Alarm! You don't have Depression.\" elif (completeScore >=", "energy, low self-esteem, or \" + \"hopelessness, are usually part", "and sleep changes, low energy, low self-esteem, or \" +", "be \" + \"effective.\"); elif (completeScore >= -0.4): return (\"Persistent", "+ \"people with this type of depression type are able", "how chemical \" + \"messengers like serotonin and melatonin function.", "0.05, 0.05, 0.20, 0.10] print ans ansList = ans.split(\"$\") for", "You don't have Depression.\" elif (completeScore >= -0.1): return (\"Seasonal", "The mood \" + \"change may result from alterations in", "(score/count)*questionWeights[i] #print(completeScore) if (completeScore >= 0.1): return \"False Alarm! You", "refers to low mood that has lasted for at least", "changes in appetite or weight, loss of energy, \" +", "and melatonin function. The leading \" + \"treatment is light", "score = 0 count = 0 # print (count) for", "\"include trouble sleeping, changes in appetite or weight, loss of", "days get shorter in the fall and winter. The mood", "= 0 count = 0 # print (count) for paragraph", "also be \" + \"effective.\"); elif (completeScore >= -0.4): return", "sys from sys import argv from nltk.sentiment.vader import SentimentIntensityAnalyzer def", "on basis of '.' or ? or !. for l", "least \" + \"two years but may not reach the", "is all-consuming and one loses interest in activities, even ones", "\"for depression, such as psychotherapy and medication, may also be", "with psychotherapy and medication. For some people with \" +", "not reach the intensity of major depression. Many \" +", "\"hopelessness, are usually part of the picture.\") else: return (\"The", "may also be \" + \"effective.\"); elif (completeScore >= -0.4):", "The usual treatments \" + \"for depression, such as psychotherapy", "alleviated with psychotherapy or antidepressant \" + \"medications, electroconvulsive therapy", "depression \" + \"emerges as days get shorter in the", "in activities, even ones \" + \"that are usually pleasurable.", "0.20, 0.05, 0.05, 0.20, 0.10] print ans ansList = ans.split(\"$\")", "light therapy, which involves daily sessions sitting \" + \"close", "able to function day to \" + \"but feel low", "0 # print (count) for paragraph in ansList: for line", "which involves daily sessions sitting \" + \"close to an", "import re import sys from sys import argv from nltk.sentiment.vader", "import sys from sys import argv from nltk.sentiment.vader import SentimentIntensityAnalyzer", "appetite or weight, loss of energy, \" + \"and feeling", "paragraph in ansList: for line in paragraph: #Split Paragraph on", "involves daily sessions sitting \" + \"close to an especially", "\"type of depression refers to low mood that has lasted", "i in range(10): results = [] score = 0 count", "a dark \" + \"mood is all-consuming and one loses", "(completeScore >= -0.4): return (\"Persistent depressive disorder. Formerly called dysthymia,", "elif (completeScore >= -0.4): return (\"Persistent depressive disorder. Formerly called", "or joyless much of the time. Some depressive symptoms, \"", "\"people with this type of depression type are able to", "if (completeScore >= 0.1): return \"False Alarm! You don't have", "weight, loss of energy, \" + \"and feeling worthless. Thoughts", "import nltk import re import sys from sys import argv", "of depression refers to low mood that has lasted for", "= 0 questionWeights = [0.05, 0.20, 0.05, 0.05, 0.05, 0.20,", "medication, may also be \" + \"effective.\"); elif (completeScore >=", "completeScore = 0 questionWeights = [0.05, 0.20, 0.05, 0.05, 0.05,", ">= 0.1): return \"False Alarm! You don't have Depression.\" elif", "return (\"Seasonal affective disorder (SAD). This type of depression \"", "completeScore += (score/count)*questionWeights[i] #print(completeScore) if (completeScore >= 0.1): return \"False", "ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score += ss['compound'] count += 1", "low self-esteem, or \" + \"hopelessness, are usually part of", "this \" + \"type of depression refers to low mood", "+ \"effective.\"); elif (completeScore >= -0.4): return (\"Persistent depressive disorder.", "range(10): results = [] score = 0 count = 0", "or \" + \"hopelessness, are usually part of the picture.\")", "re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss = ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score", "print ansList[j] for i in range(10): results = [] score", "alterations in the body's natural daily \" + \"rhythms, in", "range(10): print ansList[j] for i in range(10): results = []", "and medication. For some people with \" + \"severe depression", "disorder. Formerly called dysthymia, this \" + \"type of depression", "0.20, 0.05, 0.05, 0.05, 0.20, 0.05, 0.05, 0.20, 0.10] print", "for line in paragraph: #Split Paragraph on basis of '.'", "light, or in how chemical \" + \"messengers like serotonin", "even ones \" + \"that are usually pleasurable. Symptoms of", "years but may not reach the intensity of major depression.", "\"effective.\"); elif (completeScore >= -0.4): return (\"Persistent depressive disorder. Formerly", "import argv from nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans): ajay =", "with \" + \"severe depression that isn't alleviated with psychotherapy", "type of depression \" + \"emerges as days get shorter", "and one loses interest in activities, even ones \" +", "has lasted for at least \" + \"two years but", "in the body's natural daily \" + \"rhythms, in the", "paragraph: #Split Paragraph on basis of '.' or ? or", "pleasurable. Symptoms of this type of depression \" + \"include", "of the time. Some depressive symptoms, \" + \"such as", "(count) for paragraph in ansList: for line in paragraph: #Split", "daily \" + \"rhythms, in the eyes' sensitivity to light,", "in range(10): print ansList[j] for i in range(10): results =", "= SentimentIntensityAnalyzer() completeScore = 0 questionWeights = [0.05, 0.20, 0.05,", "for at least \" + \"two years but may not", "feel low or joyless much of the time. Some depressive", "\"messengers like serotonin and melatonin function. The leading \" +", "#print(completeScore) if (completeScore >= 0.1): return \"False Alarm! You don't", "a state where a dark \" + \"mood is all-consuming", "of '.' or ? or !. for l in re.split(r\"\\.|\\?|\\!\",paragraph):", "of death or suicide may occur. It is \" +", "this type of depression type are able to function day", "+ \"close to an especially intense light source. The usual", "+ \"usually treated with psychotherapy and medication. For some people", "picture.\") else: return (\"The classic depression type, major depression is", "(\"Seasonal affective disorder (SAD). This type of depression \" +", "loss of energy, \" + \"and feeling worthless. Thoughts of", "psychotherapy or antidepressant \" + \"medications, electroconvulsive therapy may be", "to light, or in how chemical \" + \"messengers like", "joyless much of the time. Some depressive symptoms, \" +", "and winter. The mood \" + \"change may result from", "are usually pleasurable. Symptoms of this type of depression \"", "type of depression type are able to function day to", "+ \"that are usually pleasurable. Symptoms of this type of", "low energy, low self-esteem, or \" + \"hopelessness, are usually", "\" + \"severe depression that isn't alleviated with psychotherapy or", "\" + \"messengers like serotonin and melatonin function. The leading", "treatments \" + \"for depression, such as psychotherapy and medication,", "+= ss['compound'] count += 1 completeScore += (score/count)*questionWeights[i] #print(completeScore) if", "or !. for l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss =", "disorder (SAD). This type of depression \" + \"emerges as", "the intensity of major depression. Many \" + \"people with", "intense light source. The usual treatments \" + \"for depression,", "argv from nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans): ajay = SentimentIntensityAnalyzer()", "depression that isn't alleviated with psychotherapy or antidepressant \" +", "from alterations in the body's natural daily \" + \"rhythms,", "function. The leading \" + \"treatment is light therapy, which", "or weight, loss of energy, \" + \"and feeling worthless.", "0.05, 0.20, 0.10] print ans ansList = ans.split(\"$\") for j", "+ \"such as appetite and sleep changes, low energy, low", "\" + \"effective.\"); elif (completeScore >= -0.4): return (\"Persistent depressive", "to an especially intense light source. The usual treatments \"", "SentimentIntensityAnalyzer() completeScore = 0 questionWeights = [0.05, 0.20, 0.05, 0.05,", "sensitivity to light, or in how chemical \" + \"messengers", "is a state where a dark \" + \"mood is", "ss = ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score += ss['compound'] count", "mood that has lasted for at least \" + \"two", "print(ss['compound']) score += ss['compound'] count += 1 completeScore += (score/count)*questionWeights[i]", "treated with psychotherapy and medication. For some people with \"", "one loses interest in activities, even ones \" + \"that", "light source. The usual treatments \" + \"for depression, such", "\" + \"rhythms, in the eyes' sensitivity to light, or", "may occur. It is \" + \"usually treated with psychotherapy", "classic depression type, major depression is a state where a", "nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore =", "low or joyless much of the time. Some depressive symptoms,", "but may not reach the intensity of major depression. Many", "get shorter in the fall and winter. The mood \"", "\" + \"that are usually pleasurable. Symptoms of this type", "Alarm! You don't have Depression.\" elif (completeScore >= -0.1): return", "the body's natural daily \" + \"rhythms, in the eyes'", "activities, even ones \" + \"that are usually pleasurable. Symptoms", "ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore = 0 questionWeights = [0.05,", "psychotherapy and medication, may also be \" + \"effective.\"); elif", "of energy, \" + \"and feeling worthless. Thoughts of death", "of depression \" + \"emerges as days get shorter in", "death or suicide may occur. It is \" + \"usually", "\"close to an especially intense light source. The usual treatments", "0.05, 0.05, 0.20, 0.05, 0.05, 0.20, 0.10] print ans ansList", "score += ss['compound'] count += 1 completeScore += (score/count)*questionWeights[i] #print(completeScore)", "state where a dark \" + \"mood is all-consuming and", "Many \" + \"people with this type of depression type", "# print(l) ss = ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score +=", "print (count) for paragraph in ansList: for line in paragraph:", "\"but feel low or joyless much of the time. Some", "of major depression. Many \" + \"people with this type", ">= -0.4): return (\"Persistent depressive disorder. Formerly called dysthymia, this", "= [] score = 0 count = 0 # print", "re import sys from sys import argv from nltk.sentiment.vader import", "l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss = ajay.polarity_scores(l) results.append(ss); #", "import SentimentIntensityAnalyzer def ajay(ans): ajay = SentimentIntensityAnalyzer() completeScore = 0", "\"two years but may not reach the intensity of major", "\"severe depression that isn't alleviated with psychotherapy or antidepressant \"", ">= -0.1): return (\"Seasonal affective disorder (SAD). This type of", "is \" + \"usually treated with psychotherapy and medication. For", "ss['compound'] count += 1 completeScore += (score/count)*questionWeights[i] #print(completeScore) if (completeScore", "? or !. for l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss", "isn't alleviated with psychotherapy or antidepressant \" + \"medications, electroconvulsive", "print ans ansList = ans.split(\"$\") for j in range(10): print", "may result from alterations in the body's natural daily \"", "depressive disorder. Formerly called dysthymia, this \" + \"type of", "affective disorder (SAD). This type of depression \" + \"emerges", "\" + \"and feeling worthless. Thoughts of death or suicide", "else: return (\"The classic depression type, major depression is a", "don't have Depression.\" elif (completeScore >= -0.1): return (\"Seasonal affective", "\"usually treated with psychotherapy and medication. For some people with", "\"such as appetite and sleep changes, low energy, low self-esteem,", "+ \"emerges as days get shorter in the fall and", "+ \"two years but may not reach the intensity of", "-0.1): return (\"Seasonal affective disorder (SAD). This type of depression", "much of the time. Some depressive symptoms, \" + \"such", "ansList: for line in paragraph: #Split Paragraph on basis of", "lasted for at least \" + \"two years but may", "elif (completeScore >= -0.1): return (\"Seasonal affective disorder (SAD). This", "depression refers to low mood that has lasted for at", "0.05, 0.05, 0.05, 0.20, 0.05, 0.05, 0.20, 0.10] print ans", "that isn't alleviated with psychotherapy or antidepressant \" + \"medications,", "\"change may result from alterations in the body's natural daily", "'.' or ? or !. for l in re.split(r\"\\.|\\?|\\!\",paragraph): #", "\" + \"include trouble sleeping, changes in appetite or weight,", "0.1): return \"False Alarm! You don't have Depression.\" elif (completeScore", "= ans.split(\"$\") for j in range(10): print ansList[j] for i", "\"mood is all-consuming and one loses interest in activities, even", "in ansList: for line in paragraph: #Split Paragraph on basis", "!. for l in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss = ajay.polarity_scores(l)", "appetite and sleep changes, low energy, low self-esteem, or \"", "symptoms, \" + \"such as appetite and sleep changes, low", "sleep changes, low energy, low self-esteem, or \" + \"hopelessness,", "= 0 # print (count) for paragraph in ansList: for", "this type of depression \" + \"include trouble sleeping, changes", "worthless. Thoughts of death or suicide may occur. It is", "called dysthymia, this \" + \"type of depression refers to", "or in how chemical \" + \"messengers like serotonin and", "is light therapy, which involves daily sessions sitting \" +", "usual treatments \" + \"for depression, such as psychotherapy and", "0.10] print ans ansList = ans.split(\"$\") for j in range(10):", "\" + \"people with this type of depression type are", "have Depression.\" elif (completeScore >= -0.1): return (\"Seasonal affective disorder", "fall and winter. The mood \" + \"change may result", "\" + \"hopelessness, are usually part of the picture.\") else:", "an especially intense light source. The usual treatments \" +", "results.append(ss); # print(ss['compound']) score += ss['compound'] count += 1 completeScore", "function day to \" + \"but feel low or joyless", "(SAD). This type of depression \" + \"emerges as days", "dysthymia, this \" + \"type of depression refers to low", "daily sessions sitting \" + \"close to an especially intense", "are able to function day to \" + \"but feel", "count = 0 # print (count) for paragraph in ansList:", "usually part of the picture.\") else: return (\"The classic depression", "= ajay.polarity_scores(l) results.append(ss); # print(ss['compound']) score += ss['compound'] count +=", "suicide may occur. It is \" + \"usually treated with", "ans.split(\"$\") for j in range(10): print ansList[j] for i in", "body's natural daily \" + \"rhythms, in the eyes' sensitivity", "may not reach the intensity of major depression. Many \"", "\"False Alarm! You don't have Depression.\" elif (completeScore >= -0.1):", "\" + \"treatment is light therapy, which involves daily sessions", "chemical \" + \"messengers like serotonin and melatonin function. The", "sitting \" + \"close to an especially intense light source.", "psychotherapy and medication. For some people with \" + \"severe", "nltk import re import sys from sys import argv from", "of depression type are able to function day to \"", "to low mood that has lasted for at least \"", "in re.split(r\"\\.|\\?|\\!\",paragraph): # print(l) ss = ajay.polarity_scores(l) results.append(ss); # print(ss['compound'])", "intensity of major depression. Many \" + \"people with this", "\" + \"mood is all-consuming and one loses interest in", "basis of '.' or ? or !. for l in", "+ \"treatment is light therapy, which involves daily sessions sitting", "and medication, may also be \" + \"effective.\"); elif (completeScore", "ansList[j] for i in range(10): results = [] score =", "serotonin and melatonin function. The leading \" + \"treatment is", "sys import argv from nltk.sentiment.vader import SentimentIntensityAnalyzer def ajay(ans): ajay", "as days get shorter in the fall and winter. The", "like serotonin and melatonin function. The leading \" + \"treatment", "results = [] score = 0 count = 0 #", "in appetite or weight, loss of energy, \" + \"and", "Symptoms of this type of depression \" + \"include trouble", "\" + \"such as appetite and sleep changes, low energy,", "depression is a state where a dark \" + \"mood", "as psychotherapy and medication, may also be \" + \"effective.\");" ]
[ "Okta.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals import logging", "also use assumerole to assign the role logging.debug(\"Authenticate user with", "# vim: set filetype=python ts=4 sw=4 # -*- coding: utf-8", "from tokendito import settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves AWS", "aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml", "standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves AWS credentials after authenticating with", "after authenticating with Okta.\"\"\" # Set some required initial values", "assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials( assume_role_response,", "helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials after authenticating with Okta.\") #", "some required initial values args = helpers.setup(args) logging.debug(\"tokendito retrieves AWS", "standard_library from tokendito import aws_helpers from tokendito import helpers from", "__future__ import absolute_import, division, print_function, unicode_literals import logging from future", "division, print_function, unicode_literals import logging from future import standard_library from", "required initial values args = helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials", ") assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials(", "the role logging.debug(\"Authenticate user with Okta and AWS.\") secret_session_token =", "and AWS also use assumerole to assign the role logging.debug(\"Authenticate", "to assign the role logging.debug(\"Authenticate user with Okta and AWS.\")", "filetype=python ts=4 sw=4 # -*- coding: utf-8 -*- \"\"\"This module", "secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml )", "import aws_helpers from tokendito import helpers from tokendito import okta_helpers", "okta_helpers from tokendito import settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves", "settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves AWS credentials after authenticating", "from tokendito import okta_helpers from tokendito import settings standard_library.install_aliases() def", "AWS also use assumerole to assign the role logging.debug(\"Authenticate user", "AWS credentials after authenticating with Okta.\"\"\" from __future__ import absolute_import,", "tokendito import settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves AWS credentials", "user specific information helpers.process_options(args) # Authenticate okta and AWS also", "unicode_literals import logging from future import standard_library from tokendito import", "import okta_helpers from tokendito import settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito", "information helpers.process_options(args) # Authenticate okta and AWS also use assumerole", "= aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials( assume_role_response, role_name, settings.aws_region,", "\"\"\"Tokendito retrieves AWS credentials after authenticating with Okta.\"\"\" # Set", "Okta and AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password )", "sw=4 # -*- coding: utf-8 -*- \"\"\"This module retrieves AWS", "logging from future import standard_library from tokendito import aws_helpers from", "settings.okta_password ) saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response,", "role logging.debug(\"Authenticate user with Okta and AWS.\") secret_session_token = okta_helpers.authenticate_user(", "-*- \"\"\"This module retrieves AWS credentials after authenticating with Okta.\"\"\"", "use assumerole to assign the role logging.debug(\"Authenticate user with Okta", "tokendito import okta_helpers from tokendito import settings standard_library.install_aliases() def cli(args):", "with Okta.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals import", "logging.debug(\"tokendito retrieves AWS credentials after authenticating with Okta.\") # Collect", "helpers.process_options(args) # Authenticate okta and AWS also use assumerole to", "utf-8 -*- \"\"\"This module retrieves AWS credentials after authenticating with", "role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials( assume_role_response, role_name,", "logging.debug(\"Authenticate user with Okta and AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org,", "module retrieves AWS credentials after authenticating with Okta.\"\"\" from __future__", "from tokendito import helpers from tokendito import okta_helpers from tokendito", "helpers from tokendito import okta_helpers from tokendito import settings standard_library.install_aliases()", "and organize user specific information helpers.process_options(args) # Authenticate okta and", "= okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string, saml_xml = aws_helpers.authenticate_to_roles(", "# Authenticate okta and AWS also use assumerole to assign", "import settings standard_library.install_aliases() def cli(args): \"\"\"Tokendito retrieves AWS credentials after", "retrieves AWS credentials after authenticating with Okta.\"\"\" from __future__ import", "args = helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials after authenticating with", "tokendito import helpers from tokendito import okta_helpers from tokendito import", "credentials after authenticating with Okta.\"\"\" from __future__ import absolute_import, division,", "import logging from future import standard_library from tokendito import aws_helpers", "Okta.\") # Collect and organize user specific information helpers.process_options(args) #", "= helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials after authenticating with Okta.\")", "import absolute_import, division, print_function, unicode_literals import logging from future import", "set filetype=python ts=4 sw=4 # -*- coding: utf-8 -*- \"\"\"This", "from __future__ import absolute_import, division, print_function, unicode_literals import logging from", "assumerole to assign the role logging.debug(\"Authenticate user with Okta and", "assign the role logging.debug(\"Authenticate user with Okta and AWS.\") secret_session_token", "okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token,", "authenticating with Okta.\"\"\" from __future__ import absolute_import, division, print_function, unicode_literals", "credentials after authenticating with Okta.\"\"\" # Set some required initial", "vim: set filetype=python ts=4 sw=4 # -*- coding: utf-8 -*-", "Authenticate okta and AWS also use assumerole to assign the", "okta and AWS also use assumerole to assign the role", "after authenticating with Okta.\") # Collect and organize user specific", "Set some required initial values args = helpers.setup(args) logging.debug(\"tokendito retrieves", "aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials( assume_role_response, role_name, settings.aws_region, settings.aws_output", "Collect and organize user specific information helpers.process_options(args) # Authenticate okta", "saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name =", "coding: utf-8 -*- \"\"\"This module retrieves AWS credentials after authenticating", "from tokendito import aws_helpers from tokendito import helpers from tokendito", "values args = helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials after authenticating", "initial values args = helpers.setup(args) logging.debug(\"tokendito retrieves AWS credentials after", "retrieves AWS credentials after authenticating with Okta.\") # Collect and", "with Okta and AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password", "secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string, saml_xml =", "print_function, unicode_literals import logging from future import standard_library from tokendito", "saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name = aws_helpers.select_assumeable_role(", "with Okta.\") # Collect and organize user specific information helpers.process_options(args)", "-*- coding: utf-8 -*- \"\"\"This module retrieves AWS credentials after", "cli(args): \"\"\"Tokendito retrieves AWS credentials after authenticating with Okta.\"\"\" #", "# Set some required initial values args = helpers.setup(args) logging.debug(\"tokendito", "import helpers from tokendito import okta_helpers from tokendito import settings", "from future import standard_library from tokendito import aws_helpers from tokendito", "# Collect and organize user specific information helpers.process_options(args) # Authenticate", "\"\"\"This module retrieves AWS credentials after authenticating with Okta.\"\"\" from", "AWS credentials after authenticating with Okta.\"\"\" # Set some required", "ts=4 sw=4 # -*- coding: utf-8 -*- \"\"\"This module retrieves", "after authenticating with Okta.\"\"\" from __future__ import absolute_import, division, print_function,", "user with Okta and AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username,", "import standard_library from tokendito import aws_helpers from tokendito import helpers", "authenticating with Okta.\"\"\" # Set some required initial values args", "settings.okta_aws_app_url ) assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response)", "aws_helpers from tokendito import helpers from tokendito import okta_helpers from", "AWS credentials after authenticating with Okta.\") # Collect and organize", "credentials after authenticating with Okta.\") # Collect and organize user", "settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url", ") saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name", "authenticating with Okta.\") # Collect and organize user specific information", "# -*- coding: utf-8 -*- \"\"\"This module retrieves AWS credentials", "and AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string,", "organize user specific information helpers.process_options(args) # Authenticate okta and AWS", "specific information helpers.process_options(args) # Authenticate okta and AWS also use", "= aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url ) assume_role_response, role_name = aws_helpers.select_assumeable_role( saml_response_string,", "Okta.\"\"\" # Set some required initial values args = helpers.setup(args)", "def cli(args): \"\"\"Tokendito retrieves AWS credentials after authenticating with Okta.\"\"\"", "absolute_import, division, print_function, unicode_literals import logging from future import standard_library", "retrieves AWS credentials after authenticating with Okta.\"\"\" # Set some", "with Okta.\"\"\" # Set some required initial values args =", "saml_response_string, saml_xml ) aws_helpers.ensure_keys_work(assume_role_response) helpers.set_local_credentials( assume_role_response, role_name, settings.aws_region, settings.aws_output )", "AWS.\") secret_session_token = okta_helpers.authenticate_user( settings.okta_org, settings.okta_username, settings.okta_password ) saml_response_string, saml_xml", "future import standard_library from tokendito import aws_helpers from tokendito import", "settings.okta_username, settings.okta_password ) saml_response_string, saml_xml = aws_helpers.authenticate_to_roles( secret_session_token, settings.okta_aws_app_url )", "tokendito import aws_helpers from tokendito import helpers from tokendito import" ]
[]
[ "return TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc", "self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if field_el.tag == 'subtopic': text =", "f = codecs.getreader(self._encoding or 'utf8')(f) for line in f: if", "= lang def queries_iter(self): with self._queries_dlc.stream() as f: f =", "self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map = qtype_map or", "'tut': TitleUrlTextDoc, }[parser] self._docs_namespace = namespace self._docs_lang = lang self._expected_file_count", "= codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_markup = None, ''", "GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id: str", "field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint,", "as f: f = codecs.getreader(self._encoding or 'utf8')(f) for line in", "topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if topic_el.tag in", "= False if in_tag: doc_text += line if line.startswith('<'): if", "line == '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text()", "'').strip() elif line == '</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id, doc_text", "= expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint = count_hint if expected_file_count", "self._content_tags): in_tag = False if in_tag: doc_text += line if", "== 2: qid, did, score = *cols, '0' yield GenericScoredDoc(qid,", "# Default content tags from Anserini's TrecCollection CONTENT_TAGS = 'TEXT", "Path(path).is_dir(): for child in path.iterdir(): yield from self._docs_iter(child) def _parser_bs(self,", "class TrecPrel(NamedTuple): query_id: str doc_id: str relevance: int method: int", "HEAD TTL DD DATE LP LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self,", "in self._path_globs): file = tarf.extractfile(block) if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file)", "file_count = 0 for glob in sorted(self._path_globs): for path in", "self._parser(f) elif Path(path).is_dir(): for child in path.iterdir(): yield from self._docs_iter(child)", "in self._content_tags): in_tag = False if in_tag: doc_text += line", "doc_id: str text: str marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id: str", "line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag = True", "for line in f: query_id, text = line.split(':', 1) text", "5: raise RuntimeError(f'expected 5 columns, got {len(cols)}') qid, did, rel,", "description: str narrative: str class TrecSubtopic(NamedTuple): number: str text: str", "self._qtype def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class", "number of files.') else: yield from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs:", "<filename>ir_datasets/formats/trec.py import io import codecs import tarfile import re import", "reading = target match_any = True break if not match_any", "raise RuntimeError(f'expected 5 columns, got {len(cols)}') qid, did, rel, method,", "1 if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag", "encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype = qtype", "queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None, namespace=None,", "tag in self._content_tags): in_tag = True def _parser_tut(self, stream): f", "line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line == '</DOC>\\n':", "in streaming mode (r|) with self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream,", "'<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries): def", "query_ids yield self._qtype(*item) def queries_cls(self): return self._qtype def queries_namespace(self): return", "!= self._expected_file_count: raise RuntimeError(f'found {file_count} files of the expected {self._expected_file_count}", "from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count = 0 # tarfile,", "did, int(rel), int(method), float(iprob)) def qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs):", "if self._path_globs: file_count = 0 for glob in sorted(self._path_globs): for", "doc_text = None, '' in_tag = False for line in", "self._queries_lang = lang self._remove_tags = remove_tags def queries_path(self): return self._queries_dlc.path()", "queries_path(self): return self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream() as f: f", "from query_ids yield self._qtype(*item) def queries_cls(self): return self._qtype def queries_namespace(self):", "if expected_file_count is not None: assert self._path_globs is not None,", "doc_title, doc_url, doc_text = None, None, None, '' in_tag =", "_ in self._qtype._fields] if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number']", "if len(cols) != 5: raise RuntimeError(f'expected 5 columns, got {len(cols)}')", "TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def", "of the expected {self._expected_file_count} matching the following: {self._path_globs} under {self._docs_dlc.path()}.", "line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id, doc_title,", "docs_dlc self._encoding = encoding self._path_globs = path_globs self._content_tags = content_tags", "= codecs.getreader('utf8')(f) for line in f: if line == '\\n':", "did, score = cols yield TrecQrel(qid, did, int(score), it) def", "any(fnmatch(block.name, g) for g in self._path_globs): file = tarf.extractfile(block) if", "lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self): if self.docs_store().built(): return", "sure that directories are linked such that these globs match", "'description', '<narr> *(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries): def __init__(self, queries_dlc,", "namespace self._queries_lang = lang def queries_path(self): return self._queries_dlc.path() def queries_iter(self):", "number: str text: str type: str class TrecQrel(NamedTuple): query_id: str", "doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': yield", "text = ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if", "elif len(cols) == 2: qid, did, score = *cols, '0'", "line in f: if line.startswith('</top>'): assert len(fields) == len(self._qtype._fields), fields", "mode='r|gz') as tarf: for block in tarf: if any(fnmatch(block.name, g)", "'' else: if line.startswith('</TEXT>'): in_tag = False if in_tag: doc_text", "f: f = codecs.getreader('utf8')(f) for line in f: cols =", "return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self,", "under {self._docs_dlc.path()}. Make sure that directories are linked such that", "in qtype._fields} self._encoding = encoding self._subtopics_key = subtopics_key self._queries_namespace =", "return self._queries_dlc.path() def queries_iter(self): fields, reading = {}, None with", "streaming mode (r|) with self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream, mode='r|gz')", "for attr in topic_el.attrib: if attr in self._qtype_map: text =", "qrels_dlc self._qrels_defs = qrels_defs def qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self):", "TITLE HL HEAD TTL DD DATE LP LEADPARA'.split() class TrecDocs(BaseDocs):", "with tarfile.open(fileobj=stream, mode='r|gz') as tarf: for block in tarf: if", "str text: str marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id: str title:", "qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc = queries_dlc self._qtype", "as ET from fnmatch import fnmatch from pathlib import Path", "sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield from self._docs_iter(path) if self._expected_file_count is", "match_any = False for tag, target in self._qtype_map.items(): match =", "self._queries_namespace def queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc,", "= encoding self._subtopics_key = subtopics_key self._queries_namespace = namespace self._queries_lang =", "self._path_globs is not None, \"expected_file_count only supported with path_globs\" def", "docs_count(self): if self.docs_store().built(): return self.docs_store().count() def docs_namespace(self): return self._docs_namespace def", "= item[qid_field].strip() # remove whitespace from query_ids yield self._qtype(*item) def", "in f: if line == '\\n': continue # ignore blank", "'utf8')(f) for line in f: query_id, text = line.split(':', 1)", "lang self._remove_tags = remove_tags def queries_path(self): return self._queries_dlc.path() def queries_iter(self):", "ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_markup =", "'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics = [] for", "self._parser_text, 'tut': self._parser_tut, }[parser] self._doc = { 'BS4': TrecDoc, 'text':", "def qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc", "globs match the correct number of files.') else: with self._docs_dlc.stream()", "size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self): if self.docs_store().built(): return self.docs_store().count() def", "TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)):", "= text if field_el.tag == 'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'],", "float(iprob)) def qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc):", "'' else: if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags):", "remove whitespace from query_ids yield self._qtype(*item) def queries_cls(self): return self._qtype", "for glob in sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count +=", "path_globs self._content_tags = content_tags self._parser = { 'BS4': self._parser_bs, 'text':", "tarf.extractfile(block) if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count", "if in_tag == 1: doc_markup += line def _parser_text(self, stream):", "item[self._qtype._fields.index(field)] = text for field_el in topic_el: if field_el.tag in", "= codecs.getreader(self._encoding or 'utf8')(f) for line in f: query_id, text", "len(self._qtype._fields), fields for tag in self._remove_tags: fields = {k: v.replace(tag,", "yield from self._parser(f) elif Path(path).is_dir(): for child in path.iterdir(): yield", "= remove_tags def queries_path(self): return self._queries_dlc.path() def queries_iter(self): fields, reading", "True def docs_cls(self): return self._doc def docs_store(self, field='doc_id'): return PickleLz4FullStore(", "line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>',", "for tag, target in self._qtype_map.items(): match = re.match(tag, line) if", "= namespace self._queries_lang = lang self._remove_tags = remove_tags def queries_path(self):", "# tarfile, find globs, open in streaming mode (r|) with", "self._queries_lang = lang def queries_path(self): return self._queries_dlc.path() def queries_iter(self): with", "xml.etree.ElementTree as ET from fnmatch import fnmatch from pathlib import", "field_el in topic_el: if field_el.tag in self._qtype_map: text = ''.join(field_el.itertext())", "assert len(fields) == len(self._qtype._fields), fields for tag in self._remove_tags: fields", "{}, None match_any = False for tag, target in self._qtype_map.items():", "in self._qtype._fields] if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics", "qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream() as", "in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics = [] for attr", "doc_text += line if line.startswith('<TEXT>'): in_tag = True def docs_cls(self):", "= None, None, None, '' else: if line.startswith('</TEXT>'): in_tag =", "find globs, open in streaming mode (r|) with self._docs_dlc.stream() as", "import Path from typing import NamedTuple import ir_datasets from ir_datasets.indices", "elif line == '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text =", "yield GenericQuery(query_id, text) def queries_path(self): return self._queries_dlc.path() def queries_cls(self): return", "def queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace def queries_lang(self):", "field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for field_el in topic_el:", "queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries): def", "doc_id, doc_markup = None, '' else: if in_tag: doc_markup +=", "self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field]", "scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f: f", "expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc self._encoding = encoding self._path_globs", "def queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs):", "only supported with path_globs\" def docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore", "= line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n',", "= {k: v.replace(tag, '') for k, v in fields.items()} yield", "= text.rstrip('\\n') yield GenericQuery(query_id, text) def queries_path(self): return self._queries_dlc.path() def", "None, \"expected_file_count only supported with path_globs\" def docs_path(self, force=True): return", "in self._qtype_map.items(): match = re.match(tag, line) if match: fields[target] =", "if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url", "scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as", "}[parser] self._doc = { 'BS4': TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc,", "'' else: if in_tag: doc_markup += line if line.startswith('</'): if", "'utf8')(f) for line in f: if line.startswith('</top>'): assert len(fields) ==", "self._qtype = qtype self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP self._encoding =", "self._doc = { 'BS4': TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser]", "= 0 for glob in sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)):", "self._qtype(*(fields[f].strip() for f in self._qtype._fields)) fields, reading = {}, None", "'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key in", "in_tag -= 1 if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in", "if topic_el.tag in self._qtype_map: text = ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag]", "qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs = qrels_defs def qrels_path(self):", "doc_text += line if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in", "query_id: str doc_id: str relevance: int iteration: str class TrecPrel(NamedTuple):", "lang=None): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map = qtype_map", "in self._content_tags): in_tag = True def _parser_tut(self, stream): f =", "TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc = queries_dlc", "= qrels_defs def qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream()", "line) if match: fields[target] = line[match.end():] reading = target match_any", "== len(self._qtype._fields), fields for tag in self._remove_tags: fields = {k:", "glob in sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1", "= scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream()", "@ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count = 0", "class TrecQrel(NamedTuple): query_id: str doc_id: str relevance: int iteration: str", "raise RuntimeError(f'expected 4 columns, got {len(cols)}') qid, it, did, score", "assert self._path_globs is not None, \"expected_file_count only supported with path_globs\"", "{self._docs_dlc.path()}. Make sure that directories are linked such that these", "class TrecDoc(NamedTuple): doc_id: str text: str marked_up_doc: str class TitleUrlTextDoc(NamedTuple):", "def queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None,", "qrels_iter(self): with self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line", "return self._doc def docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(),", "str marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id: str title: str url:", "import tarfile import re import gzip import xml.etree.ElementTree as ET", "did, int(score), it) def qrels_cls(self): return TrecQrel def qrels_defs(self): return", "stream: with tarfile.open(fileobj=stream, mode='r|gz') as tarf: for block in tarf:", "narrative: str class TrecSubtopic(NamedTuple): number: str text: str type: str", "DATE LP LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None, path_globs=None,", "return self._queries_lang class TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc =", "class TrecQuery(NamedTuple): query_id: str title: str description: str narrative: str", "return self._docs_namespace def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP = { '<num>", "GenericQuery(query_id, text) def queries_path(self): return self._queries_dlc.path() def queries_cls(self): return GenericQuery", "None match_any = False for tag, target in self._qtype_map.items(): match", "def _parser_text(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id,", "io import codecs import tarfile import re import gzip import", "in_tag = False if in_tag: doc_text += line if line.startswith('<TEXT>'):", "{file_count} files of the expected {self._expected_file_count} matching the following: {self._path_globs}", "yield from self._parser(f) def _docs_iter(self, path): if Path(path).is_file(): if str(path).endswith('.gz'):", "doc_title, doc_url, doc_text) doc_id, doc_title, doc_url, doc_text = None, None,", "= qtype_map or DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace = namespace", "if line == '\\n': continue # ignore blank lines cols", "if line.startswith('</TEXT>'): in_tag = False if in_tag: doc_text += line", "= None, '' else: if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag", "= codecs.getreader('utf8')(f) for line in f: cols = line.rstrip().split() if", "= qtype self._qtype_map = qtype_map or {f: f for f", "topic_el: if field_el.tag in self._qtype_map: text = ''.join(field_el.itertext()) field =", "return self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream() as f: f =", "False if in_tag: doc_text += line if line.startswith('<'): if any(line.startswith(f'<{tag}>')", "+= line if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags):", "self._queries_namespace def queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc,", "qid_field = self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() # remove whitespace from", "line.rstrip().split() if len(cols) == 6: qid, _, did, _, score,", "len(cols) == 2: qid, did, score = *cols, '0' yield", "content_tags self._parser = { 'BS4': self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut,", "doc_markup += line if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in", "TrecQuery(NamedTuple): query_id: str title: str description: str narrative: str class", "= { 'BS4': TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace", "'').strip() elif line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text)", "doc_id, doc_text = None, '' in_tag = False for line", "return self._docs_lang DEFAULT_QTYPE_MAP = { '<num> *(Number:)?': 'query_id', '<title> *(Topic:)?':", "= cols yield TrecQrel(qid, did, int(score), it) def qrels_cls(self): return", "codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_markup = None, '' in_tag", "line if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag", "TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None,", "doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line == '</DOC>\\n': yield", "return self.docs_store().count() def docs_namespace(self): return self._docs_namespace def docs_lang(self): return self._docs_lang", "encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc", "self._doc def docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field,", "with self._docs_dlc.stream() as f: yield from self._parser(f) def _docs_iter(self, path):", "self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line in f:", "method: int iprob: float # Default content tags from Anserini's", "self._queries_namespace = namespace self._queries_lang = lang self._remove_tags = remove_tags def", "field = self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if topic_el.tag in self._qtype_map:", "with path_globs\" def docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self):", "any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag += 1 if in_tag", "self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream() as f: f", "self._qtype_map: text = ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text", "RuntimeError(f'found {file_count} files of the expected {self._expected_file_count} matching the following:", "= docs_dlc self._encoding = encoding self._path_globs = path_globs self._content_tags =", "''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] =", "self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics',", "sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield from", "= lang self._expected_file_count = expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint =", "if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag -=", "tag in self._remove_tags: fields = {k: v.replace(tag, '') for k,", "these globs match the correct number of files.') else: with", "len(cols) == 6: qid, _, did, _, score, _ =", "return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count", "= None, '' else: if in_tag: doc_markup += line if", "f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_title, doc_url, doc_text", "Default content tags from Anserini's TrecCollection CONTENT_TAGS = 'TEXT HEADLINE", "class TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None,", "= tarf.extractfile(block) if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield from self._parser(file)", "continue # ignore blank lines cols = line.rstrip().split() if len(cols)", "= lang self._remove_tags = remove_tags def queries_path(self): return self._queries_dlc.path() def", "HL HEAD TTL DD DATE LP LEADPARA'.split() class TrecDocs(BaseDocs): def", "globs match the correct number of files.') else: yield from", "marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id: str title: str url: str", "def __init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None,", "LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4',", "text if field_el.tag == 'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text,", "f: f = codecs.getreader('utf8')(f) for line in f: if line", "= line.rstrip().split() if len(cols) != 4: raise RuntimeError(f'expected 4 columns,", "in self._remove_tags: fields = {k: v.replace(tag, '') for k, v", "self._queries_dlc = queries_dlc self._encoding = encoding self._queries_namespace = namespace self._queries_lang", "return self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None, namespace=None, lang=None):", "self._queries_lang class TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc", "relevance: int method: int iprob: float # Default content tags", "int iteration: str class TrecPrel(NamedTuple): query_id: str doc_id: str relevance:", "lang def queries_path(self): return self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream() as", "as tarf: for block in tarf: if any(fnmatch(block.name, g) for", "f in qtype._fields} self._encoding = encoding self._subtopics_key = subtopics_key self._queries_namespace", "False if in_tag: doc_text += line if line.startswith('<TEXT>'): in_tag =", "def docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'],", "ET.fromstring(f.read()): item = [None for _ in self._qtype._fields] if 'number'", "1 if self._expected_file_count is not None: if file_count != self._expected_file_count:", "str class TrecQrel(NamedTuple): query_id: str doc_id: str relevance: int iteration:", "line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip()", "qtype._fields} self._encoding = encoding self._subtopics_key = subtopics_key self._queries_namespace = namespace", "or 'utf8')(f) for topic_el in ET.fromstring(f.read()): item = [None for", "line.startswith('<TEXT>'): in_tag = True def docs_cls(self): return self._doc def docs_store(self,", "qtype_map or {f: f for f in qtype._fields} self._encoding =", "= namespace self._queries_lang = lang def queries_iter(self): with self._queries_dlc.stream() as", "codecs.getreader('utf8')(f) for line in f: cols = line.rstrip().split() if len(cols)", "= qtype_map or {f: f for f in qtype._fields} self._encoding", "= 0 # tarfile, find globs, open in streaming mode", "yield TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup = None, '' else:", "doc_id, doc_title, doc_url, doc_text = None, None, None, '' else:", "if line.startswith('<TEXT>'): in_tag = True def docs_cls(self): return self._doc def", "target match_any = True break if not match_any and reading", "''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if field_el.tag ==", "import ir_datasets from ir_datasets.indices import PickleLz4FullStore from .base import GenericDoc,", "text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields:", "if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field = self._qtype._fields.index('query_id')", "queries_path(self): return self._queries_dlc.path() def queries_cls(self): return GenericQuery def queries_namespace(self): return", "def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels):", "str relevance: int iteration: str class TrecPrel(NamedTuple): query_id: str doc_id:", "line in f: cols = line.rstrip().split() if len(cols) == 6:", "files.') else: with self._docs_dlc.stream() as f: yield from self._parser(f) def", "doc_text) doc_id, doc_title, doc_url, doc_text = None, None, None, ''", "= path_globs self._content_tags = content_tags self._parser = { 'BS4': self._parser_bs,", "in f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if", "count_hint=self._count_hint, ) def docs_count(self): if self.docs_store().built(): return self.docs_store().count() def docs_namespace(self):", "int(rel), int(method), float(iprob)) def qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs): def", "queries_path(self): return self._queries_dlc.path() def queries_iter(self): fields, reading = {}, None", "g) for g in self._path_globs): file = tarf.extractfile(block) if block.name.endswith('.gz'):", "from self._parser(file) file_count += 1 if self._expected_file_count is not None:", "self._parser = { 'BS4': self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut, }[parser]", "of files.') else: with self._docs_dlc.stream() as f: yield from self._parser(f)", "as f: yield from self._parser(f) def _docs_iter(self, path): if Path(path).is_file():", "for line in f: if line.startswith('</top>'): assert len(fields) == len(self._qtype._fields),", "= topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if topic_el.tag", "self._parser(f) def _docs_iter(self, path): if Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path,", "item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() #", "reading = {}, None with self._queries_dlc.stream() as f: f =", "f: cols = line.rstrip().split() if len(cols) == 6: qid, _,", "lang self._expected_file_count = expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint = count_hint", "= target match_any = True break if not match_any and", "HEADLINE TITLE HL HEAD TTL DD DATE LP LEADPARA'.split() class", "str doc_id: str relevance: int method: int iprob: float #", "docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if", "not match_any and reading and not line.startswith('<'): fields[reading] += line", "str text: str type: str class TrecQrel(NamedTuple): query_id: str doc_id:", "import fnmatch from pathlib import Path from typing import NamedTuple", "float # Default content tags from Anserini's TrecCollection CONTENT_TAGS =", "such that these globs match the correct number of files.')", "count_hint if expected_file_count is not None: assert self._path_globs is not", "if in_tag: doc_markup += line if line.startswith('</'): if any(line.startswith(f'</{tag}>') for", "tag in self._content_tags): in_tag -= 1 if line.startswith('<'): if any(line.startswith(f'<{tag}>')", "'<title> *(Topic:)?': 'title', '<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative' }", "self._qtype = qtype self._qtype_map = qtype_map or {f: f for", "content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc", "for f in qtype._fields} self._encoding = encoding self._subtopics_key = subtopics_key", "def queries_path(self): return self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream() as f:", "TitleUrlTextDoc(NamedTuple): doc_id: str title: str url: str text: str class", "namespace self._queries_lang = lang def queries_iter(self): with self._queries_dlc.stream() as f:", "TrecPrel(qid, did, int(rel), int(method), float(iprob)) def qrels_cls(self): return TrecPrel class", "data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self): if self.docs_store().built():", "with path.open('rb') as f: yield from self._parser(f) elif Path(path).is_dir(): for", "self._content_tags): in_tag = True def _parser_tut(self, stream): f = codecs.getreader(self._encoding", "= ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if field_el.tag", "str relevance: int method: int iprob: float # Default content", "*(Topic:)?': 'title', '<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative' } class", "if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag +=", "stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_title, doc_url,", "if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title", "None, None, '' in_tag = False for line in f:", "= line.split(':', 1) text = text.rstrip('\\n') yield GenericQuery(query_id, text) def", "doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': soup", "qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream() as f: f", "f: if line.startswith('</top>'): assert len(fields) == len(self._qtype._fields), fields for tag", "if in_tag: doc_text += line if line.startswith('<TEXT>'): in_tag = True", "= encoding self._path_globs = path_globs self._content_tags = content_tags self._parser =", "+= line if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags):", "BaseQrels class TrecDoc(NamedTuple): doc_id: str text: str marked_up_doc: str class", "self._docs_namespace = namespace self._docs_lang = lang self._expected_file_count = expected_file_count self._docstore_size_hint", "self._docs_iter(path) if self._expected_file_count is not None: if file_count != self._expected_file_count:", "the expected {self._expected_file_count} matching the following: {self._path_globs} under {self._docs_dlc.path()}. Make", "return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f: f =", "self._queries_lang class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc", "self._expected_file_count: raise RuntimeError(f'found {file_count} files of the expected {self._expected_file_count} matching", "None, '' else: if in_tag: doc_markup += line if line.startswith('</'):", "in fields.items()} yield self._qtype(*(fields[f].strip() for f in self._qtype._fields)) fields, reading", "if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line ==", "line == '\\n': continue # ignore blank lines cols =", "self._remove_tags: fields = {k: v.replace(tag, '') for k, v in", "subtopics_key self._queries_namespace = namespace self._queries_lang = lang def queries_path(self): return", "from ir_datasets.indices import PickleLz4FullStore from .base import GenericDoc, GenericQuery, GenericScoredDoc,", "int method: int iprob: float # Default content tags from", "f: yield from self._parser(f) else: with path.open('rb') as f: yield", "self._queries_dlc.path() def queries_iter(self): fields, reading = {}, None with self._queries_dlc.stream()", "1 yield from self._docs_iter(path) if self._expected_file_count is not None: if", "import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple):", "from .base import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels", "tag in self._content_tags): in_tag = False if in_tag: doc_text +=", "self._qtype._fields)) fields, reading = {}, None match_any = False for", "None, '' else: if line.startswith('</TEXT>'): in_tag = False if in_tag:", "'text': self._parser_text, 'tut': self._parser_tut, }[parser] self._doc = { 'BS4': TrecDoc,", "field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if field_el.tag == 'subtopic':", "TrecPrel(NamedTuple): query_id: str doc_id: str relevance: int method: int iprob:", "as f: f = codecs.getreader('utf8')(f) for line in f: cols", "int(method), float(iprob)) def qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self,", "for tag in self._content_tags): in_tag += 1 if in_tag ==", "if len(cols) == 6: qid, _, did, _, score, _", "in_tag = True def _parser_tut(self, stream): f = codecs.getreader(self._encoding or", "it, did, score = cols yield TrecQrel(qid, did, int(score), it)", "'').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if", "'utf8')(stream, errors='replace') doc_id, doc_title, doc_url, doc_text = None, None, None,", "queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc = queries_dlc self._encoding = encoding", "def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP = { '<num> *(Number:)?': 'query_id',", "GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id: str text:", "if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag = True def", "text = line.split(':', 1) text = text.rstrip('\\n') yield GenericQuery(query_id, text)", "== '</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id, doc_text = None, ''", "[None for _ in self._qtype._fields] if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')]", "if in_tag: doc_text += line if line.startswith('<'): if any(line.startswith(f'<{tag}>') for", "= qrels_dlc self._qrels_defs = qrels_defs def qrels_path(self): return self._qrels_dlc.path() def", "self._encoding = encoding self._queries_namespace = namespace self._queries_lang = lang def", "text = text.rstrip('\\n') yield GenericQuery(query_id, text) def queries_path(self): return self._queries_dlc.path()", "self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with", "self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f: f = codecs.getreader('utf8')(f)", "= subtopics_key self._queries_namespace = namespace self._queries_lang = lang def queries_path(self):", "yield self._qtype(*(fields[f].strip() for f in self._qtype._fields)) fields, reading = {},", "the following: {self._path_globs} under {self._docs_dlc.path()}. Make sure that directories are", "_ = cols elif len(cols) == 2: qid, did, score", "def docs_count(self): if self.docs_store().built(): return self.docs_store().count() def docs_namespace(self): return self._docs_namespace", "self._parser(file) file_count += 1 if self._expected_file_count is not None: if", "line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag -= 1", "query_id, text = line.split(':', 1) text = text.rstrip('\\n') yield GenericQuery(query_id,", "'</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id, doc_title, doc_url, doc_text", "= line[match.end():] reading = target match_any = True break if", "self._queries_lang = lang def queries_iter(self): with self._queries_dlc.stream() as f: f", "in f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif", "subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics)", "self._path_globs): file = tarf.extractfile(block) if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield", "= content_tags self._parser = { 'BS4': self._parser_bs, 'text': self._parser_text, 'tut':", "'tut': self._parser_tut, }[parser] self._doc = { 'BS4': TrecDoc, 'text': GenericDoc,", "self._qtype_map: text = topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)] = text", "doc_markup = None, '' in_tag = False for line in", "import gzip import xml.etree.ElementTree as ET from fnmatch import fnmatch", "import io import codecs import tarfile import re import gzip", "for block in tarf: if any(fnmatch(block.name, g) for g in", "in path.iterdir(): yield from self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup =", "namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc self._encoding =", "self._docs_dlc = docs_dlc self._encoding = encoding self._path_globs = path_globs self._content_tags", "match: fields[target] = line[match.end():] reading = target match_any = True", "import xml.etree.ElementTree as ET from fnmatch import fnmatch from pathlib", "1) text = text.rstrip('\\n') yield GenericQuery(query_id, text) def queries_path(self): return", "str description: str narrative: str class TrecSubtopic(NamedTuple): number: str text:", "in_tag = False if in_tag: doc_text += line if line.startswith('<'):", "len(fields) == len(self._qtype._fields), fields for tag in self._remove_tags: fields =", "match_any and reading and not line.startswith('<'): fields[reading] += line def", "def queries_iter(self): with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or", "= ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for field_el", "in_tag: doc_markup += line if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag", "whitespace from query_ids yield self._qtype(*item) def queries_cls(self): return self._qtype def", "from self._parser(f) else: with path.open('rb') as f: yield from self._parser(f)", "line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title,", "class TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None,", "self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f)", "4: raise RuntimeError(f'expected 4 columns, got {len(cols)}') qid, it, did,", "encoding=None, namespace=None, lang=None): self._queries_dlc = queries_dlc self._encoding = encoding self._queries_namespace", "= line.rstrip().split() if len(cols) != 5: raise RuntimeError(f'expected 5 columns,", "line[match.end():] reading = target match_any = True break if not", "== '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text() yield", "= self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() # remove whitespace from query_ids", "'' in_tag = False for line in f: if line.startswith('<DOCNO>'):", "for field_el in topic_el: if field_el.tag in self._qtype_map: text =", "__init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc =", "{}, None with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or", "self._content_tags = content_tags self._parser = { 'BS4': self._parser_bs, 'text': self._parser_text,", "doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url = line.replace('<URL>',", "return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self,", "if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics = []", "namespace=None, lang=None): self._queries_dlc = queries_dlc self._encoding = encoding self._queries_namespace =", "fnmatch from pathlib import Path from typing import NamedTuple import", "or 'utf8')(stream, errors='replace') doc_id, doc_title, doc_url, doc_text = None, None,", "'\\n': continue # ignore blank lines cols = line.rstrip().split() if", "return self._queries_dlc.path() def queries_cls(self): return GenericQuery def queries_namespace(self): return self._queries_namespace", "cols = line.rstrip().split() if len(cols) != 4: raise RuntimeError(f'expected 4", "parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc self._encoding", "supported with path_globs\" def docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def", "= line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': yield GenericDoc(doc_id,", "for topic_el in ET.fromstring(f.read()): item = [None for _ in", "path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self):", "expected_file_count is not None: assert self._path_globs is not None, \"expected_file_count", "def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count = 0 for", "soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text() yield TrecDoc(doc_id, text,", "if str(path).endswith('.gz'): with gzip.open(path, 'rb') as f: yield from self._parser(f)", "self._docs_lang DEFAULT_QTYPE_MAP = { '<num> *(Number:)?': 'query_id', '<title> *(Topic:)?': 'title',", "qid, did, rel, method, iprob = cols yield TrecPrel(qid, did,", "iprob: float # Default content tags from Anserini's TrecCollection CONTENT_TAGS", "if Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path, 'rb') as f: yield", "tarfile import re import gzip import xml.etree.ElementTree as ET from", "qtype_map or DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace = namespace self._queries_lang", "import NamedTuple import ir_datasets from ir_datasets.indices import PickleLz4FullStore from .base", "= { '<num> *(Number:)?': 'query_id', '<title> *(Topic:)?': 'title', '<desc> *(Description:)?':", "or DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace = namespace self._queries_lang =", "= namespace self._docs_lang = lang self._expected_file_count = expected_file_count self._docstore_size_hint =", "= BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text() yield TrecDoc(doc_id, text, doc_markup)", "raise RuntimeError(f'found {file_count} files of the expected {self._expected_file_count} matching the", "qrels_cls(self): return TrecPrel class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc =", "'').strip() if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'):", "any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag = True def _parser_tut(self,", "TrecSubtopic(NamedTuple): number: str text: str type: str class TrecQrel(NamedTuple): query_id:", "file_count += 1 yield from self._docs_iter(path) if self._expected_file_count is not", "qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype =", "line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url =", "or 'utf8')(f) for line in f: query_id, text = line.split(':',", "def qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream()", "of files.') else: yield from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count", "errors='replace') doc_id, doc_title, doc_url, doc_text = None, None, None, ''", "line.startswith('<'): fields[reading] += line def queries_cls(self): return self._qtype def queries_namespace(self):", "DD DATE LP LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None,", "the correct number of files.') else: yield from self._docs_iter(self._docs_dlc.path()) else:", "tag in self._content_tags): in_tag += 1 if in_tag == 1:", "self._expected_file_count is not None: if file_count != self._expected_file_count: raise RuntimeError(f'found", "len(cols) != 5: raise RuntimeError(f'expected 5 columns, got {len(cols)}') qid,", "else: if line.startswith('</TEXT>'): in_tag = False if in_tag: doc_text +=", "import re import gzip import xml.etree.ElementTree as ET from fnmatch", "CONTENT_TAGS = 'TEXT HEADLINE TITLE HL HEAD TTL DD DATE", "'</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id, doc_text = None, '' else:", "[] for attr in topic_el.attrib: if attr in self._qtype_map: text", "TrecQrel(NamedTuple): query_id: str doc_id: str relevance: int iteration: str class", "path.iterdir(): yield from self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup", "self._encoding = encoding self._path_globs = path_globs self._content_tags = content_tags self._parser", "BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text() yield TrecDoc(doc_id, text, doc_markup) doc_id,", "relevance: int iteration: str class TrecPrel(NamedTuple): query_id: str doc_id: str", "doc_url, doc_text) doc_id, doc_title, doc_url, doc_text = None, None, None,", "in_tag = True def docs_cls(self): return self._doc def docs_store(self, field='doc_id'):", "= True def _parser_tut(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream,", "self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding", "self._path_globs: file_count = 0 for glob in sorted(self._path_globs): for path", "f = codecs.getreader(self._encoding or 'utf8')(f) for topic_el in ET.fromstring(f.read()): item", "fields, reading = {}, None match_any = False for tag,", "self._queries_dlc.path() def queries_cls(self): return GenericQuery def queries_namespace(self): return self._queries_namespace def", "ignore blank lines cols = line.rstrip().split() if len(cols) != 4:", "doc_id, doc_text = None, '' else: if line.startswith('</'): if any(line.startswith(f'</{tag}>')", "cols = line.rstrip().split() if len(cols) != 5: raise RuntimeError(f'expected 5", "f = codecs.getreader(self._encoding or 'utf8')(f) for line in f: query_id,", "yield from self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f", "TrecQrel def qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self): with", "query_id: str doc_id: str relevance: int method: int iprob: float", "soup.get_text() yield TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup = None, ''", "text.rstrip('\\n') yield GenericQuery(query_id, text) def queries_path(self): return self._queries_dlc.path() def queries_cls(self):", "self._qtype._fields] if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics =", "path): if Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path, 'rb') as f:", "str title: str description: str narrative: str class TrecSubtopic(NamedTuple): number:", "for tag in self._content_tags): in_tag -= 1 if line.startswith('<'): if", "re import gzip import xml.etree.ElementTree as ET from fnmatch import", "self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream, mode='r|gz') as tarf: for block", "or {f: f for f in qtype._fields} self._encoding = encoding", "f in self._qtype._fields)) fields, reading = {}, None match_any =", "== '\\n': continue # ignore blank lines cols = line.rstrip().split()", "self._qtype_map = qtype_map or {f: f for f in qtype._fields}", "BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id,", "self._content_tags): in_tag += 1 if in_tag == 1: doc_markup +=", "iteration: str class TrecPrel(NamedTuple): query_id: str doc_id: str relevance: int", "line in f: if line == '\\n': continue # ignore", "field_el.tag in self._qtype_map: text = ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)]", "for child in path.iterdir(): yield from self._docs_iter(child) def _parser_bs(self, stream):", "docs_namespace(self): return self._docs_namespace def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP = {", "{self._path_globs} under {self._docs_dlc.path()}. Make sure that directories are linked such", "None, None, None, '' in_tag = False for line in", "self._content_tags): in_tag -= 1 if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag", "*(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries): def __init__(self,", "line in f: query_id, text = line.split(':', 1) text =", "not None, \"expected_file_count only supported with path_globs\" def docs_path(self, force=True):", "it) def qrels_cls(self): return TrecQrel def qrels_defs(self): return self._qrels_defs class", "def qrels_cls(self): return TrecQrel def qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels):", "in_tag: doc_text += line if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag", "(r|) with self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream, mode='r|gz') as tarf:", "for line in f: if line == '\\n': continue #", "1: doc_markup += line def _parser_text(self, stream): f = codecs.getreader(self._encoding", "match_any = True break if not match_any and reading and", "block in tarf: if any(fnmatch(block.name, g) for g in self._path_globs):", "'').strip() if line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line", "break if not match_any and reading and not line.startswith('<'): fields[reading]", "self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if topic_el.tag in self._qtype_map: text =", "in topic_el: if field_el.tag in self._qtype_map: text = ''.join(field_el.itertext()) field", "TrecQrel(qid, did, int(score), it) def qrels_cls(self): return TrecQrel def qrels_defs(self):", "encoding self._queries_namespace = namespace self._queries_lang = lang self._remove_tags = remove_tags", "in sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield", "= queries_dlc self._encoding = encoding self._queries_namespace = namespace self._queries_lang =", "'').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif", "qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype", "queries_iter(self): with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or 'utf8')(f)", "stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_text =", "fields, reading = {}, None with self._queries_dlc.stream() as f: f", "None: if file_count != self._expected_file_count: raise RuntimeError(f'found {file_count} files of", "in self._qtype._fields)) fields, reading = {}, None match_any = False", "fnmatch import fnmatch from pathlib import Path from typing import", "expected {self._expected_file_count} matching the following: {self._path_globs} under {self._docs_dlc.path()}. Make sure", "{self._expected_file_count} matching the following: {self._path_globs} under {self._docs_dlc.path()}. Make sure that", "line if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag", "+= line if line.startswith('<TEXT>'): in_tag = True def docs_cls(self): return", "False for tag, target in self._qtype_map.items(): match = re.match(tag, line)", "def _parser_tut(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id,", "self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count = 0 # tarfile, find", "RuntimeError(f'expected 5 columns, got {len(cols)}') qid, did, rel, method, iprob", "if field_el.tag == 'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type']))", "qid, it, did, score = cols yield TrecQrel(qid, did, int(score),", "force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs:", "score = cols yield TrecQrel(qid, did, int(score), it) def qrels_cls(self):", "def __init__(self, queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc = queries_dlc self._encoding", "doc_text = None, '' else: if line.startswith('</'): if any(line.startswith(f'</{tag}>') for", "DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace = namespace self._queries_lang = lang", "line if line.startswith('<TEXT>'): in_tag = True def docs_cls(self): return self._doc", "queries_dlc self._qtype = qtype self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP self._encoding", "'lxml') text = soup.get_text() yield TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup", "1 if in_tag == 1: doc_markup += line def _parser_text(self,", "= queries_dlc self._qtype = qtype self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP", "if self._path_globs: file_count = 0 # tarfile, find globs, open", "def queries_cls(self): return GenericQuery def queries_namespace(self): return self._queries_namespace def queries_lang(self):", "__init__(self, queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc = queries_dlc self._encoding =", "codecs.getreader('utf8')(f) for line in f: if line == '\\n': continue", "self._docstore_size_hint = docstore_size_hint self._count_hint = count_hint if expected_file_count is not", "self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for field_el in topic_el: if field_el.tag", "= ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_markup", "elif line == '</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id, doc_text =", "f for f in qtype._fields} self._encoding = encoding self._subtopics_key =", "queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels): def", "__init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path() def", "6: qid, _, did, _, score, _ = cols elif", "file = gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count += 1 if", "in ET.fromstring(f.read()): item = [None for _ in self._qtype._fields] if", "not None: if file_count != self._expected_file_count: raise RuntimeError(f'found {file_count} files", "5 columns, got {len(cols)}') qid, did, rel, method, iprob =", "file_count != self._expected_file_count: raise RuntimeError(f'found {file_count} files of the expected", "is not None: assert self._path_globs is not None, \"expected_file_count only", "def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries):", "TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None):", "queries_dlc self._qtype = qtype self._qtype_map = qtype_map or {f: f", "else: with self._docs_dlc.stream() as f: yield from self._parser(f) def _docs_iter(self,", "from self._docs_iter(path) if self._expected_file_count is not None: if file_count !=", "if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag = False if", "in f: if line.startswith('</top>'): assert len(fields) == len(self._qtype._fields), fields for", "= cols yield TrecPrel(qid, did, int(rel), int(method), float(iprob)) def qrels_cls(self):", "codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_title, doc_url, doc_text = None,", "0 # tarfile, find globs, open in streaming mode (r|)", "TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs =", "cols yield TrecQrel(qid, did, int(score), it) def qrels_cls(self): return TrecQrel", "for g in self._path_globs): file = tarf.extractfile(block) if block.name.endswith('.gz'): file", "line == '</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id, doc_text = None,", "namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map", "= False for tag, target in self._qtype_map.items(): match = re.match(tag,", "open in streaming mode (r|) with self._docs_dlc.stream() as stream: with", "GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id:", "self._queries_namespace = namespace self._queries_lang = lang def queries_path(self): return self._queries_dlc.path()", "g in self._path_globs): file = tarf.extractfile(block) if block.name.endswith('.gz'): file =", "return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels): def __init__(self,", "ignore blank lines cols = line.rstrip().split() if len(cols) != 5:", "field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field =", "doc_text) doc_id, doc_text = None, '' else: if line.startswith('</'): if", "str text: str class TrecQuery(NamedTuple): query_id: str title: str description:", "tags from Anserini's TrecCollection CONTENT_TAGS = 'TEXT HEADLINE TITLE HL", "def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path()", "qid, _, did, _, score, _ = cols elif len(cols)", "int(score), it) def qrels_cls(self): return TrecQrel def qrels_defs(self): return self._qrels_defs", "if any(fnmatch(block.name, g) for g in self._path_globs): file = tarf.extractfile(block)", "with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or 'utf8')(f) for", "f: query_id, text = line.split(':', 1) text = text.rstrip('\\n') yield", "= qtype self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP self._encoding = encoding", "in self._content_tags): in_tag += 1 if in_tag == 1: doc_markup", "if attr in self._qtype_map: text = topic_el.attrib[attr] field = self._qtype_map[attr]", "text: str class TrecQuery(NamedTuple): query_id: str title: str description: str", "item[qid_field] = item[qid_field].strip() # remove whitespace from query_ids yield self._qtype(*item)", "self._docs_lang = lang self._expected_file_count = expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint", "'utf8')(stream, errors='replace') doc_id, doc_text = None, '' in_tag = False", "= encoding self._queries_namespace = namespace self._queries_lang = lang self._remove_tags =", "+= line def _parser_text(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream,", "+= line def queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace", "not None: assert self._path_globs is not None, \"expected_file_count only supported", "f: f = codecs.getreader(self._encoding or 'utf8')(f) for topic_el in ET.fromstring(f.read()):", "Anserini's TrecCollection CONTENT_TAGS = 'TEXT HEADLINE TITLE HL HEAD TTL", "TrecCollection CONTENT_TAGS = 'TEXT HEADLINE TITLE HL HEAD TTL DD", "if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag += 1 if", "namespace self._queries_lang = lang self._remove_tags = remove_tags def queries_path(self): return", "mode (r|) with self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream, mode='r|gz') as", "f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_markup = None,", "docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint,", "if field_el.tag in self._qtype_map: text = ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag]", "docstore_size_hint self._count_hint = count_hint if expected_file_count is not None: assert", "in self._qtype_map: text = topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)] =", "self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or 'utf8')(f) for line", "if file_count != self._expected_file_count: raise RuntimeError(f'found {file_count} files of the", "'rb') as f: yield from self._parser(f) else: with path.open('rb') as", "codecs.getreader(self._encoding or 'utf8')(f) for line in f: if line.startswith('</top>'): assert", "= self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] = text if field_el.tag == 'subtopic': text", "= { 'BS4': self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut, }[parser] self._doc", "directories are linked such that these globs match the correct", "else: if in_tag: doc_markup += line if line.startswith('</'): if any(line.startswith(f'</{tag}>')", "Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path, 'rb') as f: yield from", "gzip import xml.etree.ElementTree as ET from fnmatch import fnmatch from", "f: f = codecs.getreader(self._encoding or 'utf8')(f) for line in f:", "str class TitleUrlTextDoc(NamedTuple): doc_id: str title: str url: str text:", "yield from self._parser(f) else: with path.open('rb') as f: yield from", "lines cols = line.rstrip().split() if len(cols) != 5: raise RuntimeError(f'expected", "text = soup.get_text() yield TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup =", "codecs.getreader(self._encoding or 'utf8')(f) for topic_el in ET.fromstring(f.read()): item = [None", "Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count = 0 for glob in sorted(self._path_globs):", "self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or 'utf8')(f) for topic_el", "# ignore blank lines cols = line.rstrip().split() if len(cols) !=", "v.replace(tag, '') for k, v in fields.items()} yield self._qtype(*(fields[f].strip() for", "doc_url, doc_text = None, None, None, '' in_tag = False", "from self._parser(f) def _docs_iter(self, path): if Path(path).is_file(): if str(path).endswith('.gz'): with", "line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title =", "encoding self._path_globs = path_globs self._content_tags = content_tags self._parser = {", "line.replace('<TITLE>', '').replace('</TITLE>\\n', '').strip() if line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip()", "cols yield TrecPrel(qid, did, int(rel), int(method), float(iprob)) def qrels_cls(self): return", "or 'utf8')(f) for line in f: if line.startswith('</top>'): assert len(fields)", "namespace self._docs_lang = lang self._expected_file_count = expected_file_count self._docstore_size_hint = docstore_size_hint", "= 'TEXT HEADLINE TITLE HL HEAD TTL DD DATE LP", "remove_tags def queries_path(self): return self._queries_dlc.path() def queries_iter(self): fields, reading =", "f = codecs.getreader('utf8')(f) for line in f: if line ==", "{len(cols)}') qid, did, rel, method, iprob = cols yield TrecPrel(qid,", "= line.rstrip().split() if len(cols) == 6: qid, _, did, _,", "= codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_title, doc_url, doc_text =", "in_tag == 1: doc_markup += line def _parser_text(self, stream): f", "== '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id, doc_title, doc_url,", "codecs.getreader(self._encoding or 'utf8')(f) for line in f: query_id, text =", "line def queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace def", "in_tag: doc_text += line if line.startswith('<TEXT>'): in_tag = True def", "files.') else: yield from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count =", "0 for glob in sorted(self._path_globs): for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count", "from fnmatch import fnmatch from pathlib import Path from typing", "str type: str class TrecQrel(NamedTuple): query_id: str doc_id: str relevance:", "text = topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if", "= {}, None match_any = False for tag, target in", "text) def queries_path(self): return self._queries_dlc.path() def queries_cls(self): return GenericQuery def", "self._encoding = encoding self._subtopics_key = subtopics_key self._queries_namespace = namespace self._queries_lang", "str url: str text: str class TrecQuery(NamedTuple): query_id: str title:", "as f: yield from self._parser(f) else: with path.open('rb') as f:", "'utf8')(f) for topic_el in ET.fromstring(f.read()): item = [None for _", "yield TrecPrel(qid, did, int(rel), int(method), float(iprob)) def qrels_cls(self): return TrecPrel", "str class TrecPrel(NamedTuple): query_id: str doc_id: str relevance: int method:", "title: str url: str text: str class TrecQuery(NamedTuple): query_id: str", "yield from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count = 0 #", "doc_id: str title: str url: str text: str class TrecQuery(NamedTuple):", "correct number of files.') else: with self._docs_dlc.stream() as f: yield", "queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc = queries_dlc", "TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace = namespace self._docs_lang", "lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc self._encoding = encoding", "else: with path.open('rb') as f: yield from self._parser(f) elif Path(path).is_dir():", "tag, target in self._qtype_map.items(): match = re.match(tag, line) if match:", "that these globs match the correct number of files.') else:", "self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace =", "'').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': yield GenericDoc(doc_id, doc_text) doc_id,", "fields for tag in self._remove_tags: fields = {k: v.replace(tag, '')", "= {}, None with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding", "re.match(tag, line) if match: fields[target] = line[match.end():] reading = target", "+= 1 yield from self._docs_iter(path) if self._expected_file_count is not None:", "self._qtype(*item) def queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace def", "for path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield from self._docs_iter(path)", "str narrative: str class TrecSubtopic(NamedTuple): number: str text: str type:", "return GenericQuery def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang", "RuntimeError(f'expected 4 columns, got {len(cols)}') qid, it, did, score =", "qrels_cls(self): return TrecQrel def qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels): def", "class TrecSubtopic(NamedTuple): number: str text: str type: str class TrecQrel(NamedTuple):", "is not None, \"expected_file_count only supported with path_globs\" def docs_path(self,", "\"expected_file_count only supported with path_globs\" def docs_path(self, force=True): return self._docs_dlc.path(force)", "number of files.') else: with self._docs_dlc.stream() as f: yield from", "doc_title, doc_url, doc_text = None, None, None, '' else: if", "item[self._qtype._fields.index(field)] = text if field_el.tag == 'subtopic': text = ''.join(field_el.itertext())", "self._qrels_dlc = qrels_dlc self._qrels_defs = qrels_defs def qrels_path(self): return self._qrels_dlc.path()", "def qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream() as f:", "def scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f:", "f = codecs.getreader('utf8')(f) for line in f: cols = line.rstrip().split()", "self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding", "text: str type: str class TrecQrel(NamedTuple): query_id: str doc_id: str", "self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut, }[parser] self._doc = { 'BS4':", "namespace=None, lang=None): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map =", "= codecs.getreader(self._encoding or 'utf8')(f) for line in f: if line.startswith('</top>'):", "= tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() # remove", "-= 1 if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags):", "+= 1 if in_tag == 1: doc_markup += line def", "None: assert self._path_globs is not None, \"expected_file_count only supported with", "line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n':", "None with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding or 'utf8')(f)", "{ '<num> *(Number:)?': 'query_id', '<title> *(Topic:)?': 'title', '<desc> *(Description:)?': 'description',", "doc_markup = None, '' else: if in_tag: doc_markup += line", "pathlib import Path from typing import NamedTuple import ir_datasets from", "topic_el in ET.fromstring(f.read()): item = [None for _ in self._qtype._fields]", "PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def", "def queries_path(self): return self._queries_dlc.path() def queries_iter(self): fields, reading = {},", "fields = {k: v.replace(tag, '') for k, v in fields.items()}", "len(cols) != 4: raise RuntimeError(f'expected 4 columns, got {len(cols)}') qid,", "content tags from Anserini's TrecCollection CONTENT_TAGS = 'TEXT HEADLINE TITLE", "doc_id, doc_title, doc_url, doc_text = None, None, None, '' in_tag", "expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint = count_hint if expected_file_count is", "self._docs_namespace def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP = { '<num> *(Number:)?':", "correct number of files.') else: yield from self._docs_iter(self._docs_dlc.path()) else: if", "stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace')", "score, _ = cols elif len(cols) == 2: qid, did,", "TitleUrlTextDoc, }[parser] self._docs_namespace = namespace self._docs_lang = lang self._expected_file_count =", "from self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f =", "tarfile.open(fileobj=stream, mode='r|gz') as tarf: for block in tarf: if any(fnmatch(block.name,", "in_tag += 1 if in_tag == 1: doc_markup += line", "doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>',", "lang def queries_iter(self): with self._queries_dlc.stream() as f: f = codecs.getreader(self._encoding", "= self._qtype_map[attr] item[self._qtype._fields.index(field)] = text if topic_el.tag in self._qtype_map: text", "TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup = None, '' else: if", "self._subtopics_key = subtopics_key self._queries_namespace = namespace self._queries_lang = lang def", "yield self._qtype(*item) def queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace", ".base import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class", "doc_id: str relevance: int iteration: str class TrecPrel(NamedTuple): query_id: str", "'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace = namespace self._docs_lang =", "typing import NamedTuple import ir_datasets from ir_datasets.indices import PickleLz4FullStore from", "as stream: with tarfile.open(fileobj=stream, mode='r|gz') as tarf: for block in", "errors='replace') doc_id, doc_markup = None, '' in_tag = False for", "errors='replace') doc_id, doc_text = None, '' in_tag = False for", "fields[target] = line[match.end():] reading = target match_any = True break", "return self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream() as f: f =", "queries_iter(self): fields, reading = {}, None with self._queries_dlc.stream() as f:", "k, v in fields.items()} yield self._qtype(*(fields[f].strip() for f in self._qtype._fields))", "subtopics = [] for attr in topic_el.attrib: if attr in", "= True break if not match_any and reading and not", "codecs import tarfile import re import gzip import xml.etree.ElementTree as", "def docs_namespace(self): return self._docs_namespace def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP =", "tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() # remove whitespace", "line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag = False", "scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line", "'').strip() elif line == '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text", "}[parser] self._docs_namespace = namespace self._docs_lang = lang self._expected_file_count = expected_file_count", "= count_hint if expected_file_count is not None: assert self._path_globs is", "path.open('rb') as f: yield from self._parser(f) elif Path(path).is_dir(): for child", "topic_el.attrib['number'] subtopics = [] for attr in topic_el.attrib: if attr", "'').replace('</URL>\\n', '').strip() elif line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url,", "__init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None,", "yield from self._docs_iter(path) if self._expected_file_count is not None: if file_count", "str(path).endswith('.gz'): with gzip.open(path, 'rb') as f: yield from self._parser(f) else:", "class TrecColonQueries(BaseQueries): def __init__(self, queries_dlc, encoding=None, namespace=None, lang=None): self._queries_dlc =", "int iprob: float # Default content tags from Anserini's TrecCollection", "line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': yield GenericDoc(doc_id, doc_text)", "True def _parser_tut(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace')", "self._count_hint = count_hint if expected_file_count is not None: assert self._path_globs", "in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield from self._docs_iter(path) if self._expected_file_count", "as f: f = codecs.getreader('utf8')(f) for line in f: if", "2: qid, did, score = *cols, '0' yield GenericScoredDoc(qid, did,", "files of the expected {self._expected_file_count} matching the following: {self._path_globs} under", "= text for field_el in topic_el: if field_el.tag in self._qtype_map:", "did, _, score, _ = cols elif len(cols) == 2:", "qtype self._qtype_map = qtype_map or DEFAULT_QTYPE_MAP self._encoding = encoding self._queries_namespace", "title: str description: str narrative: str class TrecSubtopic(NamedTuple): number: str", "if line.startswith('</top>'): assert len(fields) == len(self._qtype._fields), fields for tag in", "str doc_id: str relevance: int iteration: str class TrecPrel(NamedTuple): query_id:", "= line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'): doc_title = line.replace('<TITLE>', '').replace('</TITLE>\\n',", "= re.match(tag, line) if match: fields[target] = line[match.end():] reading =", "doc_markup += line def _parser_text(self, stream): f = codecs.getreader(self._encoding or", "str class TrecQuery(NamedTuple): query_id: str title: str description: str narrative:", "for tag in self._content_tags): in_tag = True def _parser_tut(self, stream):", "linked such that these globs match the correct number of", "columns, got {len(cols)}') qid, did, rel, method, iprob = cols", "TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self): return", "self.docs_store().built(): return self.docs_store().count() def docs_namespace(self): return self._docs_namespace def docs_lang(self): return", "_docs_iter(self, path): if Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path, 'rb') as", "topic_el.attrib: item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics = [] for attr in", "tarfile, find globs, open in streaming mode (r|) with self._docs_dlc.stream()", "line.rstrip().split() if len(cols) != 4: raise RuntimeError(f'expected 4 columns, got", "self._expected_file_count = expected_file_count self._docstore_size_hint = docstore_size_hint self._count_hint = count_hint if", "topic_el.tag in self._qtype_map: text = ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)]", "from typing import NamedTuple import ir_datasets from ir_datasets.indices import PickleLz4FullStore", "globs, open in streaming mode (r|) with self._docs_dlc.stream() as stream:", "f: yield from self._parser(f) def _docs_iter(self, path): if Path(path).is_file(): if", "class TitleUrlTextDoc(NamedTuple): doc_id: str title: str url: str text: str", "with self._docs_dlc.stream() as stream: with tarfile.open(fileobj=stream, mode='r|gz') as tarf: for", "that directories are linked such that these globs match the", "fields.items()} yield self._qtype(*(fields[f].strip() for f in self._qtype._fields)) fields, reading =", "BaseDocs, BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id: str text: str", "for line in f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n',", "line.startswith('</top>'): assert len(fields) == len(self._qtype._fields), fields for tag in self._remove_tags:", "encoding self._queries_namespace = namespace self._queries_lang = lang def queries_iter(self): with", "= cols elif len(cols) == 2: qid, did, score =", "type: str class TrecQrel(NamedTuple): query_id: str doc_id: str relevance: int", "for f in self._qtype._fields)) fields, reading = {}, None match_any", "in self._qtype_map: text = ''.join(field_el.itertext()) field = self._qtype_map[field_el.tag] item[self._qtype._fields.index(field)] =", "in self._qtype_map: text = ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] =", "index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self): if self.docs_store().built(): return self.docs_store().count()", "else: if self._path_globs: file_count = 0 # tarfile, find globs,", "queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc", "None, None, '' else: if line.startswith('</TEXT>'): in_tag = False if", "in f: cols = line.rstrip().split() if len(cols) == 6: qid,", "= codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_text = None, ''", "if self._expected_file_count is not None: if file_count != self._expected_file_count: raise", "None, '' else: if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in", "qrels_defs def qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self): with self._qrels_dlc.stream() as", "blank lines cols = line.rstrip().split() if len(cols) != 4: raise", "init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, ) def docs_count(self): if", "field_el.tag == 'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if", "reading = {}, None match_any = False for tag, target", "BaseQueries, BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id: str text: str marked_up_doc:", "target in self._qtype_map.items(): match = re.match(tag, line) if match: fields[target]", "= namespace self._queries_lang = lang def queries_path(self): return self._queries_dlc.path() def", "item[self._qtype._fields.index(field)] = text if topic_el.tag in self._qtype_map: text = ''.join(topic_el.itertext())", "import codecs import tarfile import re import gzip import xml.etree.ElementTree", "docstore_size_hint=None, count_hint=None): self._docs_dlc = docs_dlc self._encoding = encoding self._path_globs =", "= gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count += 1 if self._expected_file_count", "= lang def queries_path(self): return self._queries_dlc.path() def queries_iter(self): with self._queries_dlc.stream()", "self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip() # remove whitespace from query_ids yield", "*(Number:)?': 'query_id', '<title> *(Topic:)?': 'title', '<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?':", "self._scoreddocs_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line in f:", "url: str text: str class TrecQuery(NamedTuple): query_id: str title: str", "def queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery,", "= False for line in f: if line.startswith('<DOCNO>'): doc_id =", "4 columns, got {len(cols)}') qid, it, did, score = cols", "lang=None, remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map =", "line.rstrip().split() if len(cols) != 5: raise RuntimeError(f'expected 5 columns, got", "if line.startswith('<URL>'): doc_url = line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line ==", "def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs = qrels_defs", "in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field] =", "with self._scoreddocs_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line in", "self._path_globs = path_globs self._content_tags = content_tags self._parser = { 'BS4':", "class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None,", "line def _parser_text(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace')", "= True def docs_cls(self): return self._doc def docs_store(self, field='doc_id'): return", "# remove whitespace from query_ids yield self._qtype(*item) def queries_cls(self): return", "*(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None,", "queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc", "= text if topic_el.tag in self._qtype_map: text = ''.join(topic_el.itertext()) field", "line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag += 1", "codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_text = None, '' in_tag", "''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for field_el in", "GenericDoc(doc_id, doc_text) doc_id, doc_text = None, '' else: if line.startswith('</'):", "TTL DD DATE LP LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self, docs_dlc,", "if match: fields[target] = line[match.end():] reading = target match_any =", "= queries_dlc self._qtype = qtype self._qtype_map = qtype_map or {f:", "line in f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip()", "count_hint=None): self._docs_dlc = docs_dlc self._encoding = encoding self._path_globs = path_globs", "= topic_el.attrib['number'] subtopics = [] for attr in topic_el.attrib: if", "topic_el.attrib: if attr in self._qtype_map: text = topic_el.attrib[attr] field =", "f: if line == '\\n': continue # ignore blank lines", "as f: yield from self._parser(f) elif Path(path).is_dir(): for child in", "= ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')]", "Path from typing import NamedTuple import ir_datasets from ir_datasets.indices import", "query_id: str title: str description: str narrative: str class TrecSubtopic(NamedTuple):", "file_count = 0 # tarfile, find globs, open in streaming", "doc_url, doc_text = None, None, None, '' else: if line.startswith('</TEXT>'):", "{f: f for f in qtype._fields} self._encoding = encoding self._subtopics_key", "match the correct number of files.') else: yield from self._docs_iter(self._docs_dlc.path())", "= self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for field_el in topic_el: if", "def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc", "in tarf: if any(fnmatch(block.name, g) for g in self._path_globs): file", "or 'utf8')(stream, errors='replace') doc_id, doc_markup = None, '' in_tag =", "self._queries_namespace = namespace self._queries_lang = lang def queries_iter(self): with self._queries_dlc.stream()", "'') for k, v in fields.items()} yield self._qtype(*(fields[f].strip() for f", "as f: f = codecs.getreader(self._encoding or 'utf8')(f) for topic_el in", "elif Path(path).is_dir(): for child in path.iterdir(): yield from self._docs_iter(child) def", "f: yield from self._parser(f) elif Path(path).is_dir(): for child in path.iterdir():", "False for line in f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>',", "attr in self._qtype_map: text = topic_el.attrib[attr] field = self._qtype_map[attr] item[self._qtype._fields.index(field)]", "and not line.startswith('<'): fields[reading] += line def queries_cls(self): return self._qtype", "if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag -= 1 if", "not line.startswith('<'): fields[reading] += line def queries_cls(self): return self._qtype def", "scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self): return self._scoreddocs_dlc.path() def scoreddocs_iter(self):", "queries_cls(self): return self._qtype def queries_namespace(self): return self._queries_namespace def queries_lang(self): return", "self._path_globs: file_count = 0 # tarfile, find globs, open in", "PickleLz4FullStore from .base import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries, BaseScoredDocs,", "if self.docs_store().built(): return self.docs_store().count() def docs_namespace(self): return self._docs_namespace def docs_lang(self):", "yield GenericDoc(doc_id, doc_text) doc_id, doc_text = None, '' else: if", "!= 5: raise RuntimeError(f'expected 5 columns, got {len(cols)}') qid, did,", "def scoreddocs_iter(self): with self._scoreddocs_dlc.stream() as f: f = codecs.getreader('utf8')(f) for", "def docs_cls(self): return self._doc def docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4',", "= [] for attr in topic_el.attrib: if attr in self._qtype_map:", "tarf: for block in tarf: if any(fnmatch(block.name, g) for g", "rel, method, iprob = cols yield TrecPrel(qid, did, int(rel), int(method),", "from pathlib import Path from typing import NamedTuple import ir_datasets", "= docstore_size_hint self._count_hint = count_hint if expected_file_count is not None:", "docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count = 0 for glob", "= soup.get_text() yield TrecDoc(doc_id, text, doc_markup) doc_id, doc_markup = None,", "in_tag = False for line in f: if line.startswith('<DOCNO>'): doc_id", "+= 1 if self._expected_file_count is not None: if file_count !=", "= line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': soup =", "line.startswith('</TEXT>'): in_tag = False if in_tag: doc_text += line if", "'BS4': TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace = namespace", "qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc = queries_dlc self._qtype =", "is not None: if file_count != self._expected_file_count: raise RuntimeError(f'found {file_count}", "attr in topic_el.attrib: if attr in self._qtype_map: text = topic_el.attrib[attr]", "got {len(cols)}') qid, did, rel, method, iprob = cols yield", "path_globs\" def docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if", "text = ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text for", "if len(cols) != 4: raise RuntimeError(f'expected 4 columns, got {len(cols)}')", "with self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f) for line in", "docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None):", "str title: str url: str text: str class TrecQuery(NamedTuple): query_id:", "else: yield from self._docs_iter(self._docs_dlc.path()) else: if self._path_globs: file_count = 0", "self._parser_tut, }[parser] self._doc = { 'BS4': TrecDoc, 'text': GenericDoc, 'tut':", "TrecDoc(NamedTuple): doc_id: str text: str marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id:", "doc_id, doc_markup = None, '' in_tag = False for line", "def docs_path(self, force=True): return self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir():", "in self._content_tags): in_tag -= 1 if line.startswith('<'): if any(line.startswith(f'<{tag}>') for", "in topic_el.attrib: if attr in self._qtype_map: text = topic_el.attrib[attr] field", "LP LEADPARA'.split() class TrecDocs(BaseDocs): def __init__(self, docs_dlc, encoding=None, path_globs=None, content_tags=CONTENT_TAGS,", "self._docs_dlc.stream() as f: yield from self._parser(f) def _docs_iter(self, path): if", "_parser_text(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_text", "for _ in self._qtype._fields] if 'number' in topic_el.attrib: item[self._qtype._fields.index('query_id')] =", "'').replace('</DOCNO>\\n', '').strip() elif line == '</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml')", "tarf: if any(fnmatch(block.name, g) for g in self._path_globs): file =", "for k, v in fields.items()} yield self._qtype(*(fields[f].strip() for f in", "== 6: qid, _, did, _, score, _ = cols", "gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count += 1 if self._expected_file_count is", "queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None,", "_parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or 'utf8')(stream,", "subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map", "Make sure that directories are linked such that these globs", "= None, '' in_tag = False for line in f:", "item[self._qtype._fields.index('query_id')] = topic_el.attrib['number'] subtopics = [] for attr in topic_el.attrib:", "if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag =", "self.docs_store().count() def docs_namespace(self): return self._docs_namespace def docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP", "'<num> *(Number:)?': 'query_id', '<title> *(Topic:)?': 'title', '<desc> *(Description:)?': 'description', '<narr>", "_, did, _, score, _ = cols elif len(cols) ==", "!= 4: raise RuntimeError(f'expected 4 columns, got {len(cols)}') qid, it,", "for tag in self._content_tags): in_tag = False if in_tag: doc_text", "== 'subtopic': text = ''.join(field_el.itertext()) subtopics.append(TrecSubtopic(field_el.attrib['number'], text, field_el.attrib['type'])) if self._subtopics_key", "if line.startswith('<'): if any(line.startswith(f'<{tag}>') for tag in self._content_tags): in_tag =", "method, iprob = cols yield TrecPrel(qid, did, int(rel), int(method), float(iprob))", "iprob = cols yield TrecPrel(qid, did, int(rel), int(method), float(iprob)) def", "matching the following: {self._path_globs} under {self._docs_dlc.path()}. Make sure that directories", "file = tarf.extractfile(block) if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield from", "lang=None): self._queries_dlc = queries_dlc self._encoding = encoding self._queries_namespace = namespace", "gzip.open(path, 'rb') as f: yield from self._parser(f) else: with path.open('rb')", "match the correct number of files.') else: with self._docs_dlc.stream() as", "path in sorted(Path(self._docs_dlc.path()).glob(glob)): file_count += 1 yield from self._docs_iter(path) if", "yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id, doc_title, doc_url, doc_text =", "{ 'BS4': self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut, }[parser] self._doc =", "'narrative' } class TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None,", "self._qtype_map.items(): match = re.match(tag, line) if match: fields[target] = line[match.end():]", "doc_id: str relevance: int method: int iprob: float # Default", "= None, None, None, '' in_tag = False for line", "GenericQuery def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class", "__init__(self, qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs = qrels_defs def", "ir_datasets.indices import PickleLz4FullStore from .base import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs,", "{k: v.replace(tag, '') for k, v in fields.items()} yield self._qtype(*(fields[f].strip()", "== 1: doc_markup += line def _parser_text(self, stream): f =", "_, score, _ = cols elif len(cols) == 2: qid,", "self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field = self._qtype._fields.index('query_id') item[qid_field] = item[qid_field].strip()", "text: str marked_up_doc: str class TitleUrlTextDoc(NamedTuple): doc_id: str title: str", "= line.replace('<URL>', '').replace('</URL>\\n', '').strip() elif line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id,", "yield TrecQrel(qid, did, int(score), it) def qrels_cls(self): return TrecQrel def", "TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f)", "cols = line.rstrip().split() if len(cols) == 6: qid, _, did,", "def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None, lang=None, remove_tags=('</title>',)): self._queries_dlc", "def queries_iter(self): fields, reading = {}, None with self._queries_dlc.stream() as", "blank lines cols = line.rstrip().split() if len(cols) != 5: raise", "= encoding self._queries_namespace = namespace self._queries_lang = lang def queries_iter(self):", "self._remove_tags = remove_tags def queries_path(self): return self._queries_dlc.path() def queries_iter(self): fields,", "child in path.iterdir(): yield from self._docs_iter(child) def _parser_bs(self, stream): BeautifulSoup", "text, doc_markup) doc_id, doc_markup = None, '' else: if in_tag:", "class TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream() as f: f =", "queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecXmlQueries(BaseQueries): def", "str class TrecSubtopic(NamedTuple): number: str text: str type: str class", "_parser_tut(self, stream): f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_title,", "'<narr> *(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery,", "GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace = namespace self._docs_lang = lang", "block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count += 1", "def queries_path(self): return self._queries_dlc.path() def queries_cls(self): return GenericQuery def queries_namespace(self):", "match = re.match(tag, line) if match: fields[target] = line[match.end():] reading", "from Anserini's TrecCollection CONTENT_TAGS = 'TEXT HEADLINE TITLE HL HEAD", "qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs = qrels_defs def qrels_path(self): return", "the correct number of files.') else: with self._docs_dlc.stream() as f:", "def _docs_iter(self, path): if Path(path).is_file(): if str(path).endswith('.gz'): with gzip.open(path, 'rb')", ") def docs_count(self): if self.docs_store().built(): return self.docs_store().count() def docs_namespace(self): return", "def _parser_bs(self, stream): BeautifulSoup = ir_datasets.lazy_libs.bs4().BeautifulSoup f = codecs.getreader(self._encoding or", "or 'utf8')(stream, errors='replace') doc_id, doc_text = None, '' in_tag =", "'</DOC>\\n': soup = BeautifulSoup(f'<OUTER>\\n{doc_markup}\\n</OUTER>', 'lxml') text = soup.get_text() yield TrecDoc(doc_id,", "for tag in self._remove_tags: fields = {k: v.replace(tag, '') for", "self._parser(f) else: with path.open('rb') as f: yield from self._parser(f) elif", "TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id, doc_title, doc_url, doc_text = None,", "return self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self): with self._qrels_dlc.stream() as f:", "qid, did, score = *cols, '0' yield GenericScoredDoc(qid, did, float(score))", "docs_cls(self): return self._doc def docs_store(self, field='doc_id'): return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter,", "NamedTuple import ir_datasets from ir_datasets.indices import PickleLz4FullStore from .base import", "doc_markup) doc_id, doc_markup = None, '' else: if in_tag: doc_markup", "item[qid_field].strip() # remove whitespace from query_ids yield self._qtype(*item) def queries_cls(self):", "ir_datasets from ir_datasets.indices import PickleLz4FullStore from .base import GenericDoc, GenericQuery,", "following: {self._path_globs} under {self._docs_dlc.path()}. Make sure that directories are linked", "self._encoding = encoding self._queries_namespace = namespace self._queries_lang = lang self._remove_tags", "cols elif len(cols) == 2: qid, did, score = *cols,", "docs_lang(self): return self._docs_lang DEFAULT_QTYPE_MAP = { '<num> *(Number:)?': 'query_id', '<title>", "are linked such that these globs match the correct number", "self._qtype_map: text = ''.join(topic_el.itertext()) field = self._qtype_map[topic_el.tag] item[self._qtype._fields.index(field)] = text", "return self._qtype def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang", "None, None, None, '' else: if line.startswith('</TEXT>'): in_tag = False", "self._docs_dlc.path(force) @ir_datasets.util.use_docstore def docs_iter(self): if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count =", "doc_text = None, None, None, '' else: if line.startswith('</TEXT>'): in_tag", "fields[reading] += line def queries_cls(self): return self._qtype def queries_namespace(self): return", "__init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc =", "from self._parser(f) elif Path(path).is_dir(): for child in path.iterdir(): yield from", "if Path(self._docs_dlc.path()).is_dir(): if self._path_globs: file_count = 0 for glob in", "line.split(':', 1) text = text.rstrip('\\n') yield GenericQuery(query_id, text) def queries_path(self):", "lines cols = line.rstrip().split() if len(cols) != 4: raise RuntimeError(f'expected", "def qrels_iter(self): with self._qrels_dlc.stream() as f: f = codecs.getreader('utf8')(f) for", "path_globs=None, content_tags=CONTENT_TAGS, parser='BS4', namespace=None, lang=None, expected_file_count=None, docstore_size_hint=None, count_hint=None): self._docs_dlc =", "file_count += 1 if self._expected_file_count is not None: if file_count", "any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag -= 1 if line.startswith('<'):", "f = codecs.getreader(self._encoding or 'utf8')(stream, errors='replace') doc_id, doc_text = None,", "'query_id', '<title> *(Topic:)?': 'title', '<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative'", "{ 'BS4': TrecDoc, 'text': GenericDoc, 'tut': TitleUrlTextDoc, }[parser] self._docs_namespace =", "'TEXT HEADLINE TITLE HL HEAD TTL DD DATE LP LEADPARA'.split()", "'title', '<desc> *(Description:)?': 'description', '<narr> *(Narrative:)?': 'narrative' } class TrecQueries(BaseQueries):", "import PickleLz4FullStore from .base import GenericDoc, GenericQuery, GenericScoredDoc, BaseDocs, BaseQueries,", "'utf8')(stream, errors='replace') doc_id, doc_markup = None, '' in_tag = False", "f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() if line.startswith('<TITLE>'):", "reading and not line.startswith('<'): fields[reading] += line def queries_cls(self): return", "queries_cls(self): return GenericQuery def queries_namespace(self): return self._queries_namespace def queries_lang(self): return", "self._queries_namespace def queries_lang(self): return self._queries_lang class TrecQrels(BaseQrels): def __init__(self, qrels_dlc,", "= [None for _ in self._qtype._fields] if 'number' in topic_el.attrib:", "columns, got {len(cols)}') qid, it, did, score = cols yield", "BaseScoredDocs, BaseQrels class TrecDoc(NamedTuple): doc_id: str text: str marked_up_doc: str", "doc_text = None, None, None, '' in_tag = False for", "elif line == '</DOC>\\n': yield TitleUrlTextDoc(doc_id, doc_title, doc_url, doc_text) doc_id,", "return PickleLz4FullStore( path=f'{self.docs_path(force=False)}.pklz4', init_iter_fn=self.docs_iter, data_cls=self.docs_cls(), lookup_field=field, index_fields=['doc_id'], size_hint=self._docstore_size_hint, count_hint=self._count_hint, )", "True break if not match_any and reading and not line.startswith('<'):", "class TrecQrels(BaseQrels): def __init__(self, qrels_dlc, qrels_defs): self._qrels_dlc = qrels_dlc self._qrels_defs", "any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag = False if in_tag:", "and reading and not line.startswith('<'): fields[reading] += line def queries_cls(self):", "got {len(cols)}') qid, it, did, score = cols yield TrecQrel(qid,", "encoding=None, subtopics_key='subtopics', namespace=None, lang=None): self._queries_dlc = queries_dlc self._qtype = qtype", "{len(cols)}') qid, it, did, score = cols yield TrecQrel(qid, did,", "remove_tags=('</title>',)): self._queries_dlc = queries_dlc self._qtype = qtype self._qtype_map = qtype_map", "return self._queries_lang class TrecXmlQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None,", "ET from fnmatch import fnmatch from pathlib import Path from", "encoding self._subtopics_key = subtopics_key self._queries_namespace = namespace self._queries_lang = lang", "in f: query_id, text = line.split(':', 1) text = text.rstrip('\\n')", "DEFAULT_QTYPE_MAP = { '<num> *(Number:)?': 'query_id', '<title> *(Topic:)?': 'title', '<desc>", "return TrecQrel def qrels_defs(self): return self._qrels_defs class TrecPrels(TrecQrels): def qrels_iter(self):", "did, rel, method, iprob = cols yield TrecPrel(qid, did, int(rel),", "with gzip.open(path, 'rb') as f: yield from self._parser(f) else: with", "} class TrecQueries(BaseQueries): def __init__(self, queries_dlc, qtype=TrecQuery, qtype_map=None, encoding=None, namespace=None,", "text, field_el.attrib['type'])) if self._subtopics_key in self._qtype._fields: item[self._qtype._fields.index('subtopics')] = tuple(subtopics) qid_field", "else: if line.startswith('</'): if any(line.startswith(f'</{tag}>') for tag in self._content_tags): in_tag", "text if topic_el.tag in self._qtype_map: text = ''.join(topic_el.itertext()) field =", "if block.name.endswith('.gz'): file = gzip.GzipFile(fileobj=file) yield from self._parser(file) file_count +=", "yield from self._parser(file) file_count += 1 if self._expected_file_count is not", "qtype self._qtype_map = qtype_map or {f: f for f in", "item = [None for _ in self._qtype._fields] if 'number' in", "class TrecScoredDocs(BaseScoredDocs): def __init__(self, scoreddocs_dlc): self._scoreddocs_dlc = scoreddocs_dlc def scoreddocs_path(self):", "queries_dlc self._encoding = encoding self._queries_namespace = namespace self._queries_lang = lang", "= codecs.getreader(self._encoding or 'utf8')(f) for topic_el in ET.fromstring(f.read()): item =", "text for field_el in topic_el: if field_el.tag in self._qtype_map: text", "'BS4': self._parser_bs, 'text': self._parser_text, 'tut': self._parser_tut, }[parser] self._doc = {", "def queries_namespace(self): return self._queries_namespace def queries_lang(self): return self._queries_lang class TrecColonQueries(BaseQueries):", "None, '' in_tag = False for line in f: if", "= False if in_tag: doc_text += line if line.startswith('<TEXT>'): in_tag", "if not match_any and reading and not line.startswith('<'): fields[reading] +=", "f: if line.startswith('<DOCNO>'): doc_id = line.replace('<DOCNO>', '').replace('</DOCNO>\\n', '').strip() elif line", "self._qrels_defs = qrels_defs def qrels_path(self): return self._qrels_dlc.path() def qrels_iter(self): with", "for line in f: cols = line.rstrip().split() if len(cols) ==", "these globs match the correct number of files.') else: yield", "v in fields.items()} yield self._qtype(*(fields[f].strip() for f in self._qtype._fields)) fields," ]
[ "files from list of URLs (default: download.yaml) into data directory", "to. snippet_only: Downloads only the first 5 kB of the", "-*- coding: utf-8 -*- from .utils import download_from_yaml def download(output_dir:", "they exist [false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir, snippet_only=snippet_only, ignore_cache=ignore_cache,", "URLs (default: download.yaml) into data directory (default: data/). Args: output_dir:", "exist [false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir, snippet_only=snippet_only, ignore_cache=ignore_cache, verbose=True)", "data directory (default: data/). Args: output_dir: A string pointing to", "[false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir, snippet_only=snippet_only, ignore_cache=ignore_cache, verbose=True) return", "python # -*- coding: utf-8 -*- from .utils import download_from_yaml", "bool, ignore_cache: bool = False) -> None: \"\"\"Downloads data files", "# -*- coding: utf-8 -*- from .utils import download_from_yaml def", "first 5 kB of the source, for testing and file", "data to. snippet_only: Downloads only the first 5 kB of", "output_dir: A string pointing to the location to download data", "5 kB of the source, for testing and file checks.", "#!/usr/bin/env python # -*- coding: utf-8 -*- from .utils import", "download.yaml) into data directory (default: data/). Args: output_dir: A string", "A string pointing to the location to download data to.", "Downloads only the first 5 kB of the source, for", "even if they exist [false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir,", "Args: output_dir: A string pointing to the location to download", "-*- from .utils import download_from_yaml def download(output_dir: str, snippet_only: bool,", "the source, for testing and file checks. ignore_cache: Ignore cache", "str, snippet_only: bool, ignore_cache: bool = False) -> None: \"\"\"Downloads", "checks. ignore_cache: Ignore cache and download files even if they", "coding: utf-8 -*- from .utils import download_from_yaml def download(output_dir: str,", "download_from_yaml def download(output_dir: str, snippet_only: bool, ignore_cache: bool = False)", "None: \"\"\"Downloads data files from list of URLs (default: download.yaml)", "data/). Args: output_dir: A string pointing to the location to", ".utils import download_from_yaml def download(output_dir: str, snippet_only: bool, ignore_cache: bool", "Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir, snippet_only=snippet_only, ignore_cache=ignore_cache, verbose=True) return None", "of URLs (default: download.yaml) into data directory (default: data/). Args:", "into data directory (default: data/). Args: output_dir: A string pointing", "of the source, for testing and file checks. ignore_cache: Ignore", "directory (default: data/). Args: output_dir: A string pointing to the", "\"\"\"Downloads data files from list of URLs (default: download.yaml) into", "Ignore cache and download files even if they exist [false]", "cache and download files even if they exist [false] Returns:", "bool = False) -> None: \"\"\"Downloads data files from list", "ignore_cache: bool = False) -> None: \"\"\"Downloads data files from", "if they exist [false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\", output_dir=output_dir, snippet_only=snippet_only,", "from .utils import download_from_yaml def download(output_dir: str, snippet_only: bool, ignore_cache:", "to download data to. snippet_only: Downloads only the first 5", "files even if they exist [false] Returns: None. \"\"\" download_from_yaml(yaml_file=\"download.yaml\",", "-> None: \"\"\"Downloads data files from list of URLs (default:", "from list of URLs (default: download.yaml) into data directory (default:", "to the location to download data to. snippet_only: Downloads only", "= False) -> None: \"\"\"Downloads data files from list of", "utf-8 -*- from .utils import download_from_yaml def download(output_dir: str, snippet_only:", "import download_from_yaml def download(output_dir: str, snippet_only: bool, ignore_cache: bool =", "file checks. ignore_cache: Ignore cache and download files even if", "False) -> None: \"\"\"Downloads data files from list of URLs", "testing and file checks. ignore_cache: Ignore cache and download files", "download files even if they exist [false] Returns: None. \"\"\"", "string pointing to the location to download data to. snippet_only:", "for testing and file checks. ignore_cache: Ignore cache and download", "ignore_cache: Ignore cache and download files even if they exist", "source, for testing and file checks. ignore_cache: Ignore cache and", "pointing to the location to download data to. snippet_only: Downloads", "data files from list of URLs (default: download.yaml) into data", "and download files even if they exist [false] Returns: None.", "the location to download data to. snippet_only: Downloads only the", "def download(output_dir: str, snippet_only: bool, ignore_cache: bool = False) ->", "snippet_only: bool, ignore_cache: bool = False) -> None: \"\"\"Downloads data", "(default: data/). Args: output_dir: A string pointing to the location", "download data to. snippet_only: Downloads only the first 5 kB", "download(output_dir: str, snippet_only: bool, ignore_cache: bool = False) -> None:", "only the first 5 kB of the source, for testing", "the first 5 kB of the source, for testing and", "(default: download.yaml) into data directory (default: data/). Args: output_dir: A", "and file checks. ignore_cache: Ignore cache and download files even", "kB of the source, for testing and file checks. ignore_cache:", "location to download data to. snippet_only: Downloads only the first", "list of URLs (default: download.yaml) into data directory (default: data/).", "snippet_only: Downloads only the first 5 kB of the source," ]
[ "self.module.fail_json(msg=\"Error on sending autosupport message to node %s: %s.\" %", "message from a node options: name: description: - The name", "%s: %s.\" % (node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self): params =", "not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module is required\") else: self.server", "api = 'support/autosupport/messages' dummy, error = self.rest_api.post(api, params) if error", "cserver) def apply(self): if not self.use_rest: self.ems_log_event() if self.module.check_mode: pass", "%s.\" % (node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self): params = dict()", "''' - name: Send message na_ontap_autosupport_invoke: name: node1 message: invoked", "= 'support/autosupport/messages' dummy, error = self.rest_api.post(api, params) if error is", "node_details in node_info.get_children()] return nodes def send_zapi_message(self, params, node_name): params['node-name']", "password }}\" ''' RETURN = ''' ''' import traceback from", "ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()", "% (node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self): params = dict() if", "for name in node_names: self.send_zapi_message(params, name) def ems_log_event(self): results =", "of the configured destination. type: str ''' EXAMPLES = '''", "self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes = list() node_obj =", "node_info = result.get_child_by_name('attributes-list') if node_info is not None: nodes =", "}}\" ''' RETURN = ''' ''' import traceback from ansible.module_utils.basic", "argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) #", "netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if not self.use_rest:", "= [self.parameters['name']] else: # simulate REST behavior by sending to", "of the node to send the message to. - Not", "'supported_by': 'certified' } DOCUMENTATION = ''' module: na_ontap_autosupport_invoke author: NetApp", "if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) > 0: node_info = result.get_child_by_name('attributes-list')", "uri: description: - send the AutoSupport message to the destination", "send AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: -", "# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)", "if error is not None: self.module.fail_json(msg=\"Error on sending autosupport message", "self.get_nodes() for name in node_names: self.send_zapi_message(params, name) def ems_log_event(self): results", "is not None: self.module.fail_json(msg=\"Error on sending autosupport message to node", "self.parameters['uri'] if self.use_rest: if self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name =", "from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module", "= NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) # REST API should be", "self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance',", "self.send_zapi_message(params, name) def ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module,", "netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info)", "name) def ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results)", "(see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from __future__ import", "}}\" password: \"{{ password }}\" ''' RETURN = ''' '''", "to_native(error)), exception=traceback.format_exc()) def send_message(self): params = dict() if self.parameters.get('autosupport_message'): params['message']", "list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info')", "or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from __future__ import absolute_import, division,", "''' module: na_ontap_autosupport_invoke author: NetApp Ansible Team (@carchi8py) <<EMAIL>> short_description:", "hostname }}\" username: \"{{ username }}\" password: \"{{ password }}\"", "sent in the subject line of the AutoSupport message. type:", "you specify instead of the configured destination. type: str '''", "nodes in the cluster. type: str autosupport_message: description: - Text", "- message version_added: 20.8.0 type: description: - Type of AutoSupport", "9.6 or higher. self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest =", "'1.1', 'status': ['preview'], 'supported_by': 'certified' } DOCUMENTATION = ''' module:", "- Send an AutoSupport message from a node options: name:", "if self.parameters.get('type'): params['type'] = self.parameters['type'] if self.parameters.get('uri'): params['uri'] = self.parameters['uri']", "option invokes AutoSupport on all nodes in the cluster. type:", "else: self.send_message() self.module.exit_json(changed=True) def main(): message = NetAppONTAPasupInvoke() message.apply() if", "- Text sent in the subject line of the AutoSupport", "description: - The name of the node to send the", "''' send ASUP message ''' def __init__(self): self.use_rest = False", "Not specifying this option invokes AutoSupport on all nodes in", "supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) # REST", "API should be used for ONTAP 9.6 or higher. self.rest_api", "test hostname: \"{{ hostname }}\" username: \"{{ username }}\" password:", "else: node_name = '*' api = 'support/autosupport/messages' dummy, error =", "= self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] = self.parameters['type'] if self.parameters.get('uri'): params['uri']", "DOCUMENTATION = ''' module: na_ontap_autosupport_invoke author: NetApp Ansible Team (@carchi8py)", ") self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) # REST API", "HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send ASUP message '''", "cluster node_names = self.get_nodes() for name in node_names: self.send_zapi_message(params, name)", "from a node options: name: description: - The name of", "type: str autosupport_message: description: - Text sent in the subject", "self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records')", "absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version':", "str ''' EXAMPLES = ''' - name: Send message na_ontap_autosupport_invoke:", "self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on sending autosupport", "= list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info =", "params['node.name'] = self.parameters['name'] node_name = params['node.name'] else: node_name = '*'", "node to send the message to. - Not specifying this", "error is not None: self.module.fail_json(msg=\"Error on sending autosupport message to", "nodes = list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info", "send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as", "self.module.fail_json(msg=\"the python NetApp-Lib module is required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)", "self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True) def main(): message = NetAppONTAPasupInvoke()", "'') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError", "True else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module is", "(node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self): params = dict() if self.parameters.get('autosupport_message'):", "node_info is not None: nodes = [node_details.get_child_content('node') for node_details in", "= self.parameters['name'] node_name = params['node.name'] else: node_name = '*' api", "= self.rest_api.post(api, params) if error is not None: self.module.fail_json(msg=\"Error on", "invoked test autosupport rest uri: http://1.2.3.4/delivery_uri type: test hostname: \"{{", "= ''' ''' import traceback from ansible.module_utils.basic import AnsibleModule from", "used for ONTAP 9.6 or higher. self.rest_api = OntapRestAPI(self.module) if", "- netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: - Send an AutoSupport message", "self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False,", "error = self.rest_api.post(api, params) if error is not None: self.module.fail_json(msg=\"Error", "import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {", "Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke '''", "exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) > 0: node_info =", "else: # simulate REST behavior by sending to all nodes", "destination you specify instead of the configured destination. type: str", "na_ontap_autosupport_invoke author: NetApp Ansible Team (@carchi8py) <<EMAIL>> short_description: NetApp ONTAP", "self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name = params['node.name'] else: node_name =", "%s: %s.\" % (node_name, error)) else: if self.parameters.get('name'): node_names =", "password: \"{{ password }}\" ''' RETURN = ''' ''' import", "uri=dict(required=False, type='str') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper", "exception=traceback.format_exc()) def send_message(self): params = dict() if self.parameters.get('autosupport_message'): params['message'] =", "'all' type: str uri: description: - send the AutoSupport message", "ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as", "node options: name: description: - The name of the node", "type='str') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper =", "if self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if self.use_rest: if self.parameters.get('name'): params['node.name']", "RETURN = ''' ''' import traceback from ansible.module_utils.basic import AnsibleModule", "'status': ['preview'], 'supported_by': 'certified' } DOCUMENTATION = ''' module: na_ontap_autosupport_invoke", "configured destination. type: str ''' EXAMPLES = ''' - name:", "try: result = self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error),", "error: self.module.fail_json(msg=\"Error on sending autosupport message to node %s: %s.\"", "name: Send message na_ontap_autosupport_invoke: name: node1 message: invoked test autosupport", "required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes = list()", "invokes AutoSupport on all nodes in the cluster. type: str", "Type of AutoSupport Collection to Issue. choices: ['test', 'performance', 'all']", "= ''' - name: Send message na_ontap_autosupport_invoke: name: node1 message:", "node1 message: invoked test autosupport rest uri: http://1.2.3.4/delivery_uri type: test", "choices=[ 'test', 'performance', 'all'], default='all'), uri=dict(required=False, type='str') )) self.module =", "specifying this option invokes AutoSupport on all nodes in the", "}}\" username: \"{{ username }}\" password: \"{{ password }}\" '''", "uri: http://1.2.3.4/delivery_uri type: test hostname: \"{{ hostname }}\" username: \"{{", "self.use_rest: if self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name = params['node.name'] else:", "Team (@carchi8py) <<EMAIL>> short_description: NetApp ONTAP send AutoSupport message extends_documentation_fragment:", "all nodes in the cluster node_names = self.get_nodes() for name", "as error: self.module.fail_json(msg=\"Error on sending autosupport message to node %s:", "an AutoSupport message from a node options: name: description: -", "autosupport message to node %s: %s.\" % (node_name, to_native(error)), exception=traceback.format_exc())", "'test', 'performance', 'all'], default='all'), uri=dict(required=False, type='str') )) self.module = AnsibleModule(", "self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters", "= netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj,", "% (node_name, error)) else: if self.parameters.get('name'): node_names = [self.parameters['name']] else:", "https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from __future__ import absolute_import, division, print_function", "the cluster. type: str autosupport_message: description: - Text sent in", "send the message to. - Not specifying this option invokes", ")) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule()", "dummy, error = self.rest_api.post(api, params) if error is not None:", "higher. self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest = True else:", "default: 'all' type: str uri: description: - send the AutoSupport", "desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as", "to Issue. choices: ['test', 'performance', 'all'] default: 'all' type: str", "the message to. - Not specifying this option invokes AutoSupport", "ASUP message ''' def __init__(self): self.use_rest = False self.argument_spec =", "in the cluster node_names = self.get_nodes() for name in node_names:", "- name: Send message na_ontap_autosupport_invoke: name: node1 message: invoked test", "import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils", "netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test',", "__init__(self): self.use_rest = False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'),", "send ASUP message ''' def __init__(self): self.use_rest = False self.argument_spec", "version_added: 20.8.0 type: description: - Type of AutoSupport Collection to", "type: description: - Type of AutoSupport Collection to Issue. choices:", "netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records'))", "try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on sending", "params = dict() if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'):", "__metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'],", "self.use_rest = True else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib", "= netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as error:", "if self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name = params['node.name'] else: node_name", "self.send_message() self.module.exit_json(changed=True) def main(): message = NetAppONTAPasupInvoke() message.apply() if __name__", "netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send ASUP message", "self.na_helper.set_parameters(self.module.params) # REST API should be used for ONTAP 9.6", "\\ int(result.get_child_content('num-records')) > 0: node_info = result.get_child_by_name('attributes-list') if node_info is", "netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if not self.use_rest: self.ems_log_event() if self.module.check_mode:", "version_added: '20.4.0' description: - Send an AutoSupport message from a", "params, node_name): params['node-name'] = node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try:", "str aliases: - message version_added: 20.8.0 type: description: - Type", "'performance', 'all'], default='all'), uri=dict(required=False, type='str') )) self.module = AnsibleModule( argument_spec=self.argument_spec,", "python NetApp-Lib module is required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def", "choices: ['test', 'performance', 'all'] default: 'all' type: str uri: description:", "= netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send ASUP message ''' def", "params['uri'] = self.parameters['uri'] if self.use_rest: if self.parameters.get('name'): params['node.name'] = self.parameters['name']", "ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\",", "username: \"{{ username }}\" password: \"{{ password }}\" ''' RETURN", "NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB", "= AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters =", "apply(self): if not self.use_rest: self.ems_log_event() if self.module.check_mode: pass else: self.send_message()", "on all nodes in the cluster. type: str autosupport_message: description:", "None: self.module.fail_json(msg=\"Error on sending autosupport message to node %s: %s.\"", "netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: - Send an AutoSupport message from", "name: description: - The name of the node to send", "return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if not self.use_rest: self.ems_log_event() if", "int(result.get_child_content('num-records')) > 0: node_info = result.get_child_by_name('attributes-list') if node_info is not", "the configured destination. type: str ''' EXAMPLES = ''' -", "params) if error is not None: self.module.fail_json(msg=\"Error on sending autosupport", "description: - send the AutoSupport message to the destination you", "} DOCUMENTATION = ''' module: na_ontap_autosupport_invoke author: NetApp Ansible Team", "HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module is required\") else: self.server =", "#!/usr/bin/python # (c) 2020, NetApp, Inc # GNU General Public", "ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send", "netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj, True)", "cluster. type: str autosupport_message: description: - Text sent in the", "autosupport_message: description: - Text sent in the subject line of", "message. type: str aliases: - message version_added: 20.8.0 type: description:", "main(): message = NetAppONTAPasupInvoke() message.apply() if __name__ == '__main__': main()", "self.use_rest = False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False,", "netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes = list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes", "instead of the configured destination. type: str ''' EXAMPLES =", "is not None: nodes = [node_details.get_child_content('node') for node_details in node_info.get_children()]", "if self.use_rest: if self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name = params['node.name']", "short_description: NetApp ONTAP send AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added:", "Text sent in the subject line of the AutoSupport message.", "self.parameters['type'] if self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if self.use_rest: if self.parameters.get('name'):", "node_names = [self.parameters['name']] else: # simulate REST behavior by sending", "params['type'] = self.parameters['type'] if self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if self.use_rest:", "netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error", "message to node %s: %s.\" % (node_name, error)) else: if", "to node %s: %s.\" % (node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self):", "''' ''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text", "and \\ int(result.get_child_content('num-records')) > 0: node_info = result.get_child_by_name('attributes-list') if node_info", "**params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on", "if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] = self.parameters['type']", "autosupport message to node %s: %s.\" % (node_name, error)) else:", "# (c) 2020, NetApp, Inc # GNU General Public License", "test autosupport rest uri: http://1.2.3.4/delivery_uri type: test hostname: \"{{ hostname", "import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI", "= '*' api = 'support/autosupport/messages' dummy, error = self.rest_api.post(api, params)", "import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): '''", "except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\", "= self.parameters['uri'] if self.use_rest: if self.parameters.get('name'): params['node.name'] = self.parameters['name'] node_name", "REST API should be used for ONTAP 9.6 or higher.", "get_nodes(self): nodes = list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes')", "ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified' }", "cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if", "''' EXAMPLES = ''' - name: Send message na_ontap_autosupport_invoke: name:", "error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) > 0:", "self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) > 0: node_info", "else: if self.parameters.get('name'): node_names = [self.parameters['name']] else: # simulate REST", "self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] = self.parameters['type'] if self.parameters.get('uri'): params['uri'] =", "= netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes = list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter')", "node %s: %s.\" % (node_name, error)) else: if self.parameters.get('name'): node_names", "Send an AutoSupport message from a node options: name: description:", "self.parameters.get('name'): node_names = [self.parameters['name']] else: # simulate REST behavior by", "description: - Send an AutoSupport message from a node options:", "type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'", "all nodes in the cluster. type: str autosupport_message: description: -", "<<EMAIL>> short_description: NetApp ONTAP send AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap", "should be used for ONTAP 9.6 or higher. self.rest_api =", "OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object):", "message ''' def __init__(self): self.use_rest = False self.argument_spec = netapp_utils.na_ontap_host_argument_spec()", "aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance', 'all'], default='all'), uri=dict(required=False, type='str') ))", "message: invoked test autosupport rest uri: http://1.2.3.4/delivery_uri type: test hostname:", "if self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True) def main(): message =", "%s.\" % (node_name, error)) else: if self.parameters.get('name'): node_names = [self.parameters['name']]", "line of the AutoSupport message. type: str aliases: - message", "default='all'), uri=dict(required=False, type='str') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True )", "Send message na_ontap_autosupport_invoke: name: node1 message: invoked test autosupport rest", "False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]),", "License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from", "na_ontap_autosupport_invoke ''' from __future__ import absolute_import, division, print_function __metaclass__ =", "EXAMPLES = ''' - name: Send message na_ontap_autosupport_invoke: name: node1", "type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance', 'all'], default='all'),", "on sending autosupport message to node %s: %s.\" % (node_name,", "to send the message to. - Not specifying this option", "na_ontap_autosupport_invoke: name: node1 message: invoked test autosupport rest uri: http://1.2.3.4/delivery_uri", "username }}\" password: \"{{ password }}\" ''' RETURN = '''", "[self.parameters['name']] else: # simulate REST behavior by sending to all", "desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes)", "node_names: self.send_zapi_message(params, name) def ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver =", "type: test hostname: \"{{ hostname }}\" username: \"{{ username }}\"", "AutoSupport message. type: str aliases: - message version_added: 20.8.0 type:", "node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as error:", "a node options: name: description: - The name of the", "''' RETURN = ''' ''' import traceback from ansible.module_utils.basic import", "dict() if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] =", "message version_added: 20.8.0 type: description: - Type of AutoSupport Collection", "def ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return", "def __init__(self): self.use_rest = False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False,", "OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest = True else: if not HAS_NETAPP_LIB:", "message na_ontap_autosupport_invoke: name: node1 message: invoked test autosupport rest uri:", "specify instead of the configured destination. type: str ''' EXAMPLES", "= netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[", "'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified' } DOCUMENTATION = '''", "AutoSupport message from a node options: name: description: - The", "ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import", "module is required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes", "to. - Not specifying this option invokes AutoSupport on all", "author: NetApp Ansible Team (@carchi8py) <<EMAIL>> short_description: NetApp ONTAP send", "be used for ONTAP 9.6 or higher. self.rest_api = OntapRestAPI(self.module)", "subject line of the AutoSupport message. type: str aliases: -", "def apply(self): if not self.use_rest: self.ems_log_event() if self.module.check_mode: pass else:", "the AutoSupport message. type: str aliases: - message version_added: 20.8.0", "message to node %s: %s.\" % (node_name, to_native(error)), exception=traceback.format_exc()) def", "results = netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver)", "- Type of AutoSupport Collection to Issue. choices: ['test', 'performance',", "not self.use_rest: self.ems_log_event() if self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True) def", "vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if not self.use_rest: self.ems_log_event()", "description: - Text sent in the subject line of the", "= params['node.name'] else: node_name = '*' api = 'support/autosupport/messages' dummy,", "= [node_details.get_child_content('node') for node_details in node_info.get_children()] return nodes def send_zapi_message(self,", "GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) '''", "name: node1 message: invoked test autosupport rest uri: http://1.2.3.4/delivery_uri type:", "self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest = True else: if", "= node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except", "result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) > 0: node_info = result.get_child_by_name('attributes-list') if", "division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1',", "if node_info is not None: nodes = [node_details.get_child_content('node') for node_details", "simulate REST behavior by sending to all nodes in the", "= dict() if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'): params['type']", "'20.4.0' description: - Send an AutoSupport message from a node", "['preview'], 'supported_by': 'certified' } DOCUMENTATION = ''' module: na_ontap_autosupport_invoke author:", "nodes = [node_details.get_child_content('node') for node_details in node_info.get_children()] return nodes def", "AutoSupport message to the destination you specify instead of the", "if self.parameters.get('name'): node_names = [self.parameters['name']] else: # simulate REST behavior", "Collection to Issue. choices: ['test', 'performance', 'all'] default: 'all' type:", "= netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '')", "- Not specifying this option invokes AutoSupport on all nodes", "= { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified' } DOCUMENTATION", "AutoSupport Collection to Issue. choices: ['test', 'performance', 'all'] default: 'all'", "node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result =", "netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result", "def send_zapi_message(self, params, node_name): params['node-name'] = node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke',", "[node_details.get_child_content('node') for node_details in node_info.get_children()] return nodes def send_zapi_message(self, params,", "{ 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified' } DOCUMENTATION =", "__future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA =", "'*' api = 'support/autosupport/messages' dummy, error = self.rest_api.post(api, params) if", "extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: - Send an AutoSupport", "pass else: self.send_message() self.module.exit_json(changed=True) def main(): message = NetAppONTAPasupInvoke() message.apply()", "rest uri: http://1.2.3.4/delivery_uri type: test hostname: \"{{ hostname }}\" username:", "self.module.exit_json(changed=True) def main(): message = NetAppONTAPasupInvoke() message.apply() if __name__ ==", "or higher. self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest = True", "type: str aliases: - message version_added: 20.8.0 type: description: -", "to node %s: %s.\" % (node_name, error)) else: if self.parameters.get('name'):", "['test', 'performance', 'all'] default: 'all' type: str uri: description: -", "http://1.2.3.4/delivery_uri type: test hostname: \"{{ hostname }}\" username: \"{{ username", "node_name = '*' api = 'support/autosupport/messages' dummy, error = self.rest_api.post(api,", "''' na_ontap_autosupport_invoke ''' from __future__ import absolute_import, division, print_function __metaclass__", "self.parameters['name'] node_name = params['node.name'] else: node_name = '*' api =", "# simulate REST behavior by sending to all nodes in", "to the destination you specify instead of the configured destination.", "self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if self.use_rest: if self.parameters.get('name'): params['node.name'] =", "for ONTAP 9.6 or higher. self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest():", "class NetAppONTAPasupInvoke(object): ''' send ASUP message ''' def __init__(self): self.use_rest", "NetApp, Inc # GNU General Public License v3.0+ (see COPYING", "self.rest_api.post(api, params) if error is not None: self.module.fail_json(msg=\"Error on sending", "self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] = self.parameters['type'] if", "= netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def", "= type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by':", "netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on sending autosupport message to node", "from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp", "node_name): params['node-name'] = node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message,", "= OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest = True else: if not", "def main(): message = NetAppONTAPasupInvoke() message.apply() if __name__ == '__main__':", "netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send ASUP message ''' def __init__(self):", "import AnsibleModule from ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule", "def get_nodes(self): nodes = list() node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes =", "2020, NetApp, Inc # GNU General Public License v3.0+ (see", "message to. - Not specifying this option invokes AutoSupport on", "ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import", "module: na_ontap_autosupport_invoke author: NetApp Ansible Team (@carchi8py) <<EMAIL>> short_description: NetApp", "send_message(self): params = dict() if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message'] if", "send_zapi_message(self, params, node_name): params['node-name'] = node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params)", "''' from __future__ import absolute_import, division, print_function __metaclass__ = type", "this option invokes AutoSupport on all nodes in the cluster.", "as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and \\ int(result.get_child_content('num-records')) >", "type=dict(required=False, choices=[ 'test', 'performance', 'all'], default='all'), uri=dict(required=False, type='str') )) self.module", "if self.rest_api.is_rest(): self.use_rest = True else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the", "The name of the node to send the message to.", "error)) else: if self.parameters.get('name'): node_names = [self.parameters['name']] else: # simulate", "> 0: node_info = result.get_child_by_name('attributes-list') if node_info is not None:", "General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke", "of AutoSupport Collection to Issue. choices: ['test', 'performance', 'all'] default:", "= self.na_helper.set_parameters(self.module.params) # REST API should be used for ONTAP", "name in node_names: self.send_zapi_message(params, name) def ems_log_event(self): results = netapp_utils.get_cserver(self.server)", "= False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str',", "'all'], default='all'), uri=dict(required=False, type='str') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True", "= self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if", "in node_names: self.send_zapi_message(params, name) def ems_log_event(self): results = netapp_utils.get_cserver(self.server) cserver", "nodes in the cluster node_names = self.get_nodes() for name in", "else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module is required\")", "= netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self): if not", "params['node-name'] = node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False)", "autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance', 'all'], default='all'), uri=dict(required=False,", "behavior by sending to all nodes in the cluster node_names", "if not self.use_rest: self.ems_log_event() if self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True)", "options: name: description: - The name of the node to", "\"{{ hostname }}\" username: \"{{ username }}\" password: \"{{ password", "'support/autosupport/messages' dummy, error = self.rest_api.post(api, params) if error is not", "sending autosupport message to node %s: %s.\" % (node_name, error))", "(c) 2020, NetApp, Inc # GNU General Public License v3.0+", "COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from __future__ import absolute_import,", "if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module is required\") else:", "None: nodes = [node_details.get_child_content('node') for node_details in node_info.get_children()] return nodes", "= ''' module: na_ontap_autosupport_invoke author: NetApp Ansible Team (@carchi8py) <<EMAIL>>", "except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on sending autosupport message to", "params['message'] = self.parameters['autosupport_message'] if self.parameters.get('type'): params['type'] = self.parameters['type'] if self.parameters.get('uri'):", "else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes = list() node_obj", "NetApp-Lib module is required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self):", "20.8.0 type: description: - Type of AutoSupport Collection to Issue.", "def send_message(self): params = dict() if self.parameters.get('autosupport_message'): params['message'] = self.parameters['autosupport_message']", "as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPasupInvoke(object): ''' send ASUP", "the node to send the message to. - Not specifying", "(node_name, error)) else: if self.parameters.get('name'): node_names = [self.parameters['name']] else: #", "NetApp Ansible Team (@carchi8py) <<EMAIL>> short_description: NetApp ONTAP send AutoSupport", "aliases: - message version_added: 20.8.0 type: description: - Type of", "params['node.name'] else: node_name = '*' api = 'support/autosupport/messages' dummy, error", "''' import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import", "import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class", "self.ems_log_event() if self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True) def main(): message", "from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import ansible_collections.netapp.ontap.plugins.module_utils.netapp as netapp_utils HAS_NETAPP_LIB =", "enable_tunneling=False) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=\"Error on sending autosupport message", "'performance', 'all'] default: 'all' type: str uri: description: - send", "from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA", "netapp_utils.get_cserver(self.server) cserver = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=results) return netapp_utils.ems_log_event(\"na_ontap_autosupport_invoke\", cserver) def apply(self):", "node %s: %s.\" % (node_name, to_native(error)), exception=traceback.format_exc()) def send_message(self): params", "AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: - Send", "self.rest_api.is_rest(): self.use_rest = True else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python", "destination. type: str ''' EXAMPLES = ''' - name: Send", "of the AutoSupport message. type: str aliases: - message version_added:", "hostname: \"{{ hostname }}\" username: \"{{ username }}\" password: \"{{", "node_name = params['node.name'] else: node_name = '*' api = 'support/autosupport/messages'", "node_names = self.get_nodes() for name in node_names: self.send_zapi_message(params, name) def", "str autosupport_message: description: - Text sent in the subject line", "node_name send_message = netapp_utils.zapi.NaElement.create_node_with_children('autosupport-invoke', **params) try: self.server.invoke_successfully(send_message, enable_tunneling=False) except netapp_utils.zapi.NaApiError", "description: - Type of AutoSupport Collection to Issue. choices: ['test',", "\"{{ username }}\" password: \"{{ password }}\" ''' RETURN =", "AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params)", "is required\") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module) def get_nodes(self): nodes =", "nodes def send_zapi_message(self, params, node_name): params['node-name'] = node_name send_message =", "NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) # REST API should be used", "in node_info.get_children()] return nodes def send_zapi_message(self, params, node_name): params['node-name'] =", "not None: nodes = [node_details.get_child_content('node') for node_details in node_info.get_children()] return", "sending autosupport message to node %s: %s.\" % (node_name, to_native(error)),", "in the subject line of the AutoSupport message. type: str", "print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status':", "type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance', 'all'], default='all'), uri=dict(required=False, type='str')", "# REST API should be used for ONTAP 9.6 or", "node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try: result = self.server.invoke_successfully(node_obj, True) except", "send the AutoSupport message to the destination you specify instead", "self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) # REST API should", "the cluster node_names = self.get_nodes() for name in node_names: self.send_zapi_message(params,", "the subject line of the AutoSupport message. type: str aliases:", "traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native from", "self.parameters = self.na_helper.set_parameters(self.module.params) # REST API should be used for", "return nodes def send_zapi_message(self, params, node_name): params['node-name'] = node_name send_message", "to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp import OntapRestAPI import", "= self.get_nodes() for name in node_names: self.send_zapi_message(params, name) def ems_log_event(self):", "= self.parameters['type'] if self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if self.use_rest: if", "result.get_child_by_name('attributes-list') if node_info is not None: nodes = [node_details.get_child_content('node') for", "self.use_rest: self.ems_log_event() if self.module.check_mode: pass else: self.send_message() self.module.exit_json(changed=True) def main():", "'all'] default: 'all' type: str uri: description: - send the", "0: node_info = result.get_child_by_name('attributes-list') if node_info is not None: nodes", "from ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from ansible_collections.netapp.ontap.plugins.module_utils.netapp", "name of the node to send the message to. -", "Inc # GNU General Public License v3.0+ (see COPYING or", "AutoSupport on all nodes in the cluster. type: str autosupport_message:", "= netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node', '') desired_attributes.add_child_elem(node_details_info) node_obj.add_child_elem(desired_attributes) try:", "message to the destination you specify instead of the configured", "AnsibleModule from ansible.module_utils._text import to_native from ansible_collections.netapp.ontap.plugins.module_utils.netapp_module import NetAppModule from", "- The name of the node to send the message", "NetAppONTAPasupInvoke(object): ''' send ASUP message ''' def __init__(self): self.use_rest =", "sending to all nodes in the cluster node_names = self.get_nodes()", "v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ''' na_ontap_autosupport_invoke ''' from __future__", "NetApp ONTAP send AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0'", "'certified' } DOCUMENTATION = ''' module: na_ontap_autosupport_invoke author: NetApp Ansible", "type: str ''' EXAMPLES = ''' - name: Send message", "= result.get_child_by_name('attributes-list') if node_info is not None: nodes = [node_details.get_child_content('node')", "type: str uri: description: - send the AutoSupport message to", "node_obj = netapp_utils.zapi.NaElement('system-node-get-iter') desired_attributes = netapp_utils.zapi.NaElement('desired-attributes') node_details_info = netapp_utils.zapi.NaElement('node-details-info') node_details_info.add_new_child('node',", "(@carchi8py) <<EMAIL>> short_description: NetApp ONTAP send AutoSupport message extends_documentation_fragment: -", "the AutoSupport message to the destination you specify instead of", "Issue. choices: ['test', 'performance', 'all'] default: 'all' type: str uri:", "result = self.server.invoke_successfully(node_obj, True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc())", "ONTAP send AutoSupport message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0' description:", "the destination you specify instead of the configured destination. type:", "in the cluster. type: str autosupport_message: description: - Text sent", "by sending to all nodes in the cluster node_names =", "name=dict(required=False, type='str'), autosupport_message=dict(required=False, type='str', aliases=[\"message\"]), type=dict(required=False, choices=[ 'test', 'performance', 'all'],", "autosupport rest uri: http://1.2.3.4/delivery_uri type: test hostname: \"{{ hostname }}\"", "str uri: description: - send the AutoSupport message to the", "self.parameters.get('type'): params['type'] = self.parameters['type'] if self.parameters.get('uri'): params['uri'] = self.parameters['uri'] if", "- send the AutoSupport message to the destination you specify", "not None: self.module.fail_json(msg=\"Error on sending autosupport message to node %s:", "REST behavior by sending to all nodes in the cluster", "import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native", "to all nodes in the cluster node_names = self.get_nodes() for", "node_info.get_children()] return nodes def send_zapi_message(self, params, node_name): params['node-name'] = node_name", "= True else: if not HAS_NETAPP_LIB: self.module.fail_json(msg=\"the python NetApp-Lib module", "message extends_documentation_fragment: - netapp.ontap.netapp.na_ontap version_added: '20.4.0' description: - Send an", "\"{{ password }}\" ''' RETURN = ''' ''' import traceback", "ONTAP 9.6 or higher. self.rest_api = OntapRestAPI(self.module) if self.rest_api.is_rest(): self.use_rest", "Ansible Team (@carchi8py) <<EMAIL>> short_description: NetApp ONTAP send AutoSupport message", "True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg=to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and", "''' def __init__(self): self.use_rest = False self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict(", "for node_details in node_info.get_children()] return nodes def send_zapi_message(self, params, node_name):" ]
[ "def test_simple(self): user = self.create_user() result = serialize(user) assert result[\"id\"]", "serialize from freight.testutils import TestCase class UserSerializerTest(TestCase): def test_simple(self): user", "class UserSerializerTest(TestCase): def test_simple(self): user = self.create_user() result = serialize(user)", "freight.testutils import TestCase class UserSerializerTest(TestCase): def test_simple(self): user = self.create_user()", "result = serialize(user) assert result[\"id\"] == str(user.id) assert result[\"name\"] ==", "UserSerializerTest(TestCase): def test_simple(self): user = self.create_user() result = serialize(user) assert", "user = self.create_user() result = serialize(user) assert result[\"id\"] == str(user.id)", "= self.create_user() result = serialize(user) assert result[\"id\"] == str(user.id) assert", "test_simple(self): user = self.create_user() result = serialize(user) assert result[\"id\"] ==", "import TestCase class UserSerializerTest(TestCase): def test_simple(self): user = self.create_user() result", "from freight.api.serializer import serialize from freight.testutils import TestCase class UserSerializerTest(TestCase):", "self.create_user() result = serialize(user) assert result[\"id\"] == str(user.id) assert result[\"name\"]", "freight.api.serializer import serialize from freight.testutils import TestCase class UserSerializerTest(TestCase): def", "= serialize(user) assert result[\"id\"] == str(user.id) assert result[\"name\"] == user.name", "TestCase class UserSerializerTest(TestCase): def test_simple(self): user = self.create_user() result =", "from freight.testutils import TestCase class UserSerializerTest(TestCase): def test_simple(self): user =", "import serialize from freight.testutils import TestCase class UserSerializerTest(TestCase): def test_simple(self):" ]
[ "'../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y, z, c = pts[:,", "x, y, z, c = pts[:, 0], pts[:, 1], pts[:,", "(100, 100) xb = np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg, ax", "== i) * (cx == k) mean[i, k] = cz[b].mean()", "step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j],", "= np.zeros(shape) for i in range(shape[0]): print('% 3d%%' % i)", "from matplotlib import pyplot as pl from rw import WriteGTiff", "as pl from rw import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts", "= 2, nrows = 2, figsize = (10.24, 10.24), sharex", "j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb = fg.colorbar(im, ax", "= (10.24, 10.24), sharex = True, sharey = True) uc", "for k in range(shape[1]): b = (cy == i) *", "fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y, z, c", "yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb = fg.colorbar(im, ax =", "%i' % uc[j]) b = c == uc[j] cx, cy,", "pts[:, 5] ix = (0.2 * (x - x.min())).astype('int') iy", "'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500, step = 5)", "j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb = fg.colorbar(im, ax", "(10.24, 10.24), sharex = True, sharey = True) uc =", "1], pts[:, 2], pts[:, 5] ix = (0.2 * (x", "= '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y, z, c =", "j in range(len(uc)): print('Class %i' % uc[j]) b = c", "= pts[:, 0], pts[:, 1], pts[:, 2], pts[:, 5] ix", "= (100, 100) xb = np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg,", "fg, ax = pl.subplots(ncols = 2, nrows = 2, figsize", "cmap = pl.cm.magma_r) cb = fg.colorbar(im, ax = ax[1, j])", "5) for j in range(len(uc)): print('Class %i' % uc[j]) b", "(2, 5) for j in range(len(uc)): print('Class %i' % uc[j])", "numpy as np from matplotlib import pyplot as pl from", "pts = np.load(fn) x, y, z, c = pts[:, 0],", "= ax[0, j]) cb.set_label('Mean elevation [m]') im = ax[1, j].pcolormesh(xb,", "i in range(shape[0]): print('% 3d%%' % i) for k in", "rw import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x,", "True, sharey = True) uc = (2, 5) for j", "x.min(), y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy'", "for i in range(shape[0]): print('% 3d%%' % i) for k", "mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0, j].set_title('Class %i' % uc[j])", "b = c == uc[j] cx, cy, cz = ix[b],", "ax = ax[0, j]) cb.set_label('Mean elevation [m]') im = ax[1,", "pl.cm.magma_r) cb = fg.colorbar(im, ax = ax[1, j]) cb.set_label('Elevation STD')", "[m]') im = ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r)", "fg.colorbar(im, ax = ax[1, j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal') ax[1,", "import numpy as np from matplotlib import pyplot as pl", "cb = fg.colorbar(im, ax = ax[1, j]) cb.set_label('Elevation STD') ax[0,", "2, nrows = 2, figsize = (10.24, 10.24), sharex =", "iy[b], z[b] mean = np.zeros(shape) stdr = np.zeros(shape) for i", "import pyplot as pl from rw import WriteGTiff fn =", "sharex = True, sharey = True) uc = (2, 5)", "k in range(shape[1]): b = (cy == i) * (cx", "nrows = 2, figsize = (10.24, 10.24), sharex = True,", "elevation [m]') im = ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap =", "= ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb =", "range(shape[0]): print('% 3d%%' % i) for k in range(shape[1]): b", "print('Class %i' % uc[j]) b = c == uc[j] cx,", "= ax[1, j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal') ax[1, j].set_aspect('equal') pl.savefig('%s.png'", "as np from matplotlib import pyplot as pl from rw", "np.arange(shape[0]+1) fg, ax = pl.subplots(ncols = 2, nrows = 2,", "2], pts[:, 5] ix = (0.2 * (x - x.min())).astype('int')", "cz[b].mean() stdr[i, k] = cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j]", "= pl.cm.magma_r) cb = fg.colorbar(im, ax = ax[1, j]) cb.set_label('Elevation", "3d%%' % i) for k in range(shape[1]): b = (cy", "matplotlib import pyplot as pl from rw import WriteGTiff fn", "== uc[j] cx, cy, cz = ix[b], iy[b], z[b] mean", "y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' %", "pl.subplots(ncols = 2, nrows = 2, figsize = (10.24, 10.24),", "in range(shape[0]): print('% 3d%%' % i) for k in range(shape[1]):", "y.min())).astype('int') shape = (100, 100) xb = np.arange(shape[1]+1) yb =", "= cz[b].mean() stdr[i, k] = cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' %", "% uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy'", "range(shape[1]): b = (cy == i) * (cx == k)", "uc[j]) b = c == uc[j] cx, cy, cz =", "from rw import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn)", "cb.set_label('Mean elevation [m]') im = ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap", "(y - y.min())).astype('int') shape = (100, 100) xb = np.arange(shape[1]+1)", "ax[0, j]) cb.set_label('Mean elevation [m]') im = ax[1, j].pcolormesh(xb, yb,", "= fg.colorbar(im, ax = ax[1, j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal')", "j]) cb.set_label('Mean elevation [m]') im = ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr),", "= pl.cm.viridis_r) cb = fg.colorbar(im, ax = ax[0, j]) cb.set_label('Mean", "= fg.colorbar(im, ax = ax[0, j]) cb.set_label('Mean elevation [m]') im", "5] ix = (0.2 * (x - x.min())).astype('int') iy =", "(cx == k) mean[i, k] = cz[b].mean() stdr[i, k] =", "figsize = (10.24, 10.24), sharex = True, sharey = True)", "mean[i, k] = cz[b].mean() stdr[i, k] = cz[b].std() fname =", "k) mean[i, k] = cz[b].mean() stdr[i, k] = cz[b].std() fname", "cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500,", "c = pts[:, 0], pts[:, 1], pts[:, 2], pts[:, 5]", "= pl.subplots(ncols = 2, nrows = 2, figsize = (10.24,", "WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y, z,", "np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb = fg.colorbar(im, ax = ax[1,", "= True) uc = (2, 5) for j in range(len(uc)):", "np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg, ax = pl.subplots(ncols = 2,", "fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500, step", "sys import numpy as np from matplotlib import pyplot as", "ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb = fg.colorbar(im,", "cy, cz = ix[b], iy[b], z[b] mean = np.zeros(shape) stdr", "ax[1, j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal') ax[1, j].set_aspect('equal') pl.savefig('%s.png' %", "= np.zeros(shape) stdr = np.zeros(shape) for i in range(shape[0]): print('%", "= np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg, ax = pl.subplots(ncols =", "cx, cy, cz = ix[b], iy[b], z[b] mean = np.zeros(shape)", "= True, sharey = True) uc = (2, 5) for", "c == uc[j] cx, cy, cz = ix[b], iy[b], z[b]", "ax[0, j].set_title('Class %i' % uc[j]) im = ax[0, j].pcolormesh(xb, yb,", "True) uc = (2, 5) for j in range(len(uc)): print('Class", "= ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb =", "z[b] mean = np.zeros(shape) stdr = np.zeros(shape) for i in", "10.24), sharex = True, sharey = True) uc = (2,", "sharey = True) uc = (2, 5) for j in", "range(len(uc)): print('Class %i' % uc[j]) b = c == uc[j]", "im = ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb", "pl.cm.viridis_r) cb = fg.colorbar(im, ax = ax[0, j]) cb.set_label('Mean elevation", "= (2, 5) for j in range(len(uc)): print('Class %i' %", "% uc[j]) b = c == uc[j] cx, cy, cz", "mean, x.min(), y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean)", "stdr[i, k] = cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname,", "uc = (2, 5) for j in range(len(uc)): print('Class %i'", "= (0.2 * (x - x.min())).astype('int') iy = (0.2 *", "(0.2 * (y - y.min())).astype('int') shape = (100, 100) xb", "for j in range(len(uc)): print('Class %i' % uc[j]) b =", "in range(shape[1]): b = (cy == i) * (cx ==", "z, c = pts[:, 0], pts[:, 1], pts[:, 2], pts[:,", "np.zeros(shape) for i in range(shape[0]): print('% 3d%%' % i) for", "uc[j]) im = ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r)", "== k) mean[i, k] = cz[b].mean() stdr[i, k] = cz[b].std()", "* (y - y.min())).astype('int') shape = (100, 100) xb =", "i) for k in range(shape[1]): b = (cy == i)", "k] = cz[b].mean() stdr[i, k] = cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif'", "% uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0, j].set_title('Class %i'", "%i' % uc[j]) im = ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap", "- x.min())).astype('int') iy = (0.2 * (y - y.min())).astype('int') shape", "uc[j], stdr) ax[0, j].set_title('Class %i' % uc[j]) im = ax[0,", "im = ax[1, j].pcolormesh(xb, yb, np.ma.masked_invalid(stdr), cmap = pl.cm.magma_r) cb", "5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0,", "uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0, j].set_title('Class %i' %", "pts[:, 2], pts[:, 5] ix = (0.2 * (x -", "np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb = fg.colorbar(im, ax = ax[0,", "print('% 3d%%' % i) for k in range(shape[1]): b =", "yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb = fg.colorbar(im, ax =", "yb = np.arange(shape[0]+1) fg, ax = pl.subplots(ncols = 2, nrows", "% uc[j], stdr) ax[0, j].set_title('Class %i' % uc[j]) im =", "= 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500, step =", "WriteGTiff(fname, mean, x.min(), y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j],", "% i) for k in range(shape[1]): b = (cy ==", "np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0, j].set_title('Class", "y, z, c = pts[:, 0], pts[:, 1], pts[:, 2],", "= 2, figsize = (10.24, 10.24), sharex = True, sharey", "(0.2 * (x - x.min())).astype('int') iy = (0.2 * (y", "stdr) ax[0, j].set_title('Class %i' % uc[j]) im = ax[0, j].pcolormesh(xb,", "= (0.2 * (y - y.min())).astype('int') shape = (100, 100)", "= c == uc[j] cx, cy, cz = ix[b], iy[b],", "cz = ix[b], iy[b], z[b] mean = np.zeros(shape) stdr =", "cb = fg.colorbar(im, ax = ax[0, j]) cb.set_label('Mean elevation [m]')", "fg.colorbar(im, ax = ax[0, j]) cb.set_label('Mean elevation [m]') im =", "iy = (0.2 * (y - y.min())).astype('int') shape = (100,", "- y.min())).astype('int') shape = (100, 100) xb = np.arange(shape[1]+1) yb", "j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal') ax[1, j].set_aspect('equal') pl.savefig('%s.png' % sys.argv[0][:-3])", "ax = pl.subplots(ncols = 2, nrows = 2, figsize =", "x.min())).astype('int') iy = (0.2 * (y - y.min())).astype('int') shape =", "np from matplotlib import pyplot as pl from rw import", "pts[:, 0], pts[:, 1], pts[:, 2], pts[:, 5] ix =", "= np.arange(shape[0]+1) fg, ax = pl.subplots(ncols = 2, nrows =", "* (x - x.min())).astype('int') iy = (0.2 * (y -", "(cy == i) * (cx == k) mean[i, k] =", "pyplot as pl from rw import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy'", "ix[b], iy[b], z[b] mean = np.zeros(shape) stdr = np.zeros(shape) for", "= ix[b], iy[b], z[b] mean = np.zeros(shape) stdr = np.zeros(shape)", "ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap = pl.cm.viridis_r) cb = fg.colorbar(im,", "ax = ax[1, j]) cb.set_label('Elevation STD') ax[0, j].set_aspect('equal') ax[1, j].set_aspect('equal')", "0], pts[:, 1], pts[:, 2], pts[:, 5] ix = (0.2", "2, figsize = (10.24, 10.24), sharex = True, sharey =", "* (cx == k) mean[i, k] = cz[b].mean() stdr[i, k]", "import sys import numpy as np from matplotlib import pyplot", "k] = cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean,", "np.zeros(shape) stdr = np.zeros(shape) for i in range(shape[0]): print('% 3d%%'", "np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr) ax[0, j].set_title('Class %i' % uc[j]) im", "uc[j] WriteGTiff(fname, mean, x.min(), y.min()+500, step = 5) np.save('pozo_5m_dem_mean_cl%i.npy' %", "(x - x.min())).astype('int') iy = (0.2 * (y - y.min())).astype('int')", "np.load(fn) x, y, z, c = pts[:, 0], pts[:, 1],", "= 5) np.save('pozo_5m_dem_mean_cl%i.npy' % uc[j], mean) np.save('pozo_5m_dem_stdr_cl%i.npy' % uc[j], stdr)", "= np.load(fn) x, y, z, c = pts[:, 0], pts[:,", "pts[:, 1], pts[:, 2], pts[:, 5] ix = (0.2 *", "uc[j] cx, cy, cz = ix[b], iy[b], z[b] mean =", "% uc[j]) im = ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean), cmap =", "xb = np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg, ax = pl.subplots(ncols", "ix = (0.2 * (x - x.min())).astype('int') iy = (0.2", "= cz[b].std() fname = 'pozo_5m_dem_mean_cl%i.tif' % uc[j] WriteGTiff(fname, mean, x.min(),", "b = (cy == i) * (cx == k) mean[i,", "stdr = np.zeros(shape) for i in range(shape[0]): print('% 3d%%' %", "i) * (cx == k) mean[i, k] = cz[b].mean() stdr[i,", "= (cy == i) * (cx == k) mean[i, k]", "cmap = pl.cm.viridis_r) cb = fg.colorbar(im, ax = ax[0, j])", "import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts = np.load(fn) x, y,", "pl from rw import WriteGTiff fn = '../pozo-steep-vegetated-pcl.npy' pts =", "mean = np.zeros(shape) stdr = np.zeros(shape) for i in range(shape[0]):", "j].set_title('Class %i' % uc[j]) im = ax[0, j].pcolormesh(xb, yb, np.ma.masked_invalid(mean),", "in range(len(uc)): print('Class %i' % uc[j]) b = c ==", "shape = (100, 100) xb = np.arange(shape[1]+1) yb = np.arange(shape[0]+1)", "100) xb = np.arange(shape[1]+1) yb = np.arange(shape[0]+1) fg, ax =" ]
[ "def __new__(cls, name, bases, namespace): klass = type.__new__(cls, name, bases,", "We are an IUnknown pointer, represented as a c_void_p instance,", "App # CoClass # c_void_p # _SimpleCData # _CData #", "XXX We should insist that a _reg_clsid_ is present. if", "for CoClass (in comtypes/__init__.py) def _wrap_coclass(self): # We are an", "ctypes import POINTER, c_void_p, cast import comtypes ################################################################ # metaclass", "the order of the two base classes! class _coclass_pointer_meta(type(c_void_p), _coclass_meta):", "class App is a subclass of CoClass: # # POINTER(App)", "# CoClass # c_void_p # _SimpleCData # _CData # object", "is created, create a POINTER(...) type # for that class,", "comtypes ################################################################ # metaclass for CoClass (in comtypes/__init__.py) def _wrap_coclass(self):", "POINTER, c_void_p, cast import comtypes ################################################################ # metaclass for CoClass", "a CoClass subclass is created, create a POINTER(...) type #", "return obj raise TypeError(obj) # # The mro() of a", "where class App is a subclass of CoClass: # #", "# POINTER(...) type gets a __ctypes_from_outparam__ method which # will", "POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result def", "a POINTER(...) type # for that class, with bases <coclass>", "return klass # will not work if we change the", "def _coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0], cls)): return obj raise", "subclass is created, create a POINTER(...) type # for that", "PTR return klass # will not work if we change", "of a POINTER(App) type, where class App is a subclass", "= punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result def _coclass_from_param(cls, obj):", "method which # will QueryInterface for the default interface: the", "# _CData # object class _coclass_meta(type): # metaclass for CoClass", "POINTER(App) # App # CoClass # c_void_p # _SimpleCData #", "QueryInterface for the default interface: the first one on #", "(object,): return klass # XXX We should insist that a", "is present. if \"_reg_clsid_\" in namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)]", "list. def __new__(cls, name, bases, namespace): klass = type.__new__(cls, name,", "will QueryInterface for the default interface: the first one on", "type.__new__(cls, name, bases, namespace) if bases == (object,): return klass", "present. if \"_reg_clsid_\" in namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] =", "import _pointer_type_cache _pointer_type_cache[klass] = PTR return klass # will not", "comtypes.com_coclass_registry[str(clsid)] = klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p),", "_pointer_type_cache _pointer_type_cache[klass] = PTR return klass # will not work", "<reponame>phuslu/pyMSAA # comtypes._meta helper module from ctypes import POINTER, c_void_p,", "instance, # but we really want this interface: itf =", "namespace) if bases == (object,): return klass # XXX We", "result def _coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0], cls)): return obj", "really want this interface: itf = self._com_interfaces_[0] punk = cast(self,", "= self._com_interfaces_[0] punk = cast(self, POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"]", "The mro() of a POINTER(App) type, where class App is", "# When a CoClass subclass is created, create a POINTER(...)", "import POINTER, c_void_p, cast import comtypes ################################################################ # metaclass for", "_reg_clsid_ is present. if \"_reg_clsid_\" in namespace: clsid = namespace[\"_reg_clsid_\"]", "mro() of a POINTER(App) type, where class App is a", "name, bases, namespace): klass = type.__new__(cls, name, bases, namespace) if", "_SimpleCData # _CData # object class _coclass_meta(type): # metaclass for", "__ctypes_from_outparam__ method which # will QueryInterface for the default interface:", "# object class _coclass_meta(type): # metaclass for CoClass # #", "_wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from ctypes import _pointer_type_cache _pointer_type_cache[klass] =", "bases == (object,): return klass # XXX We should insist", "as a c_void_p instance, # but we really want this", "if isinstance(obj, (cls._com_interfaces_[0], cls)): return obj raise TypeError(obj) # #", "type, where class App is a subclass of CoClass: #", "== (object,): return klass # XXX We should insist that", "for that class, with bases <coclass> and c_void_p. Also, the", "_com_interfaces_ list. def __new__(cls, name, bases, namespace): klass = type.__new__(cls,", "c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from ctypes import _pointer_type_cache", "helper module from ctypes import POINTER, c_void_p, cast import comtypes", "import comtypes ################################################################ # metaclass for CoClass (in comtypes/__init__.py) def", "obj): if isinstance(obj, (cls._com_interfaces_[0], cls)): return obj raise TypeError(obj) #", "c_void_p. Also, the # POINTER(...) type gets a __ctypes_from_outparam__ method", "is a subclass of CoClass: # # POINTER(App) # App", "the default interface: the first one on # the coclass'", "CoClass (in comtypes/__init__.py) def _wrap_coclass(self): # We are an IUnknown", "a c_void_p instance, # but we really want this interface:", "= type.__new__(cls, name, bases, namespace) if bases == (object,): return", "an IUnknown pointer, represented as a c_void_p instance, # but", "################################################################ # metaclass for CoClass (in comtypes/__init__.py) def _wrap_coclass(self): #", "namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR = _coclass_pointer_meta(\"POINTER(%s)\"", "self._com_interfaces_[0] punk = cast(self, POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] =", "result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result def _coclass_from_param(cls,", "the # POINTER(...) type gets a __ctypes_from_outparam__ method which #", "metaclass for CoClass (in comtypes/__init__.py) def _wrap_coclass(self): # We are", "interface: the first one on # the coclass' _com_interfaces_ list.", "_coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), })", "default interface: the first one on # the coclass' _com_interfaces_", "gets a __ctypes_from_outparam__ method which # will QueryInterface for the", "insist that a _reg_clsid_ is present. if \"_reg_clsid_\" in namespace:", "return result def _coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0], cls)): return", "_CData # object class _coclass_meta(type): # metaclass for CoClass #", "not work if we change the order of the two", "(klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from ctypes import", "__new__(cls, name, bases, namespace): klass = type.__new__(cls, name, bases, namespace)", "# XXX We should insist that a _reg_clsid_ is present.", "of CoClass: # # POINTER(App) # App # CoClass #", "CoClass # # When a CoClass subclass is created, create", "itf = self._com_interfaces_[0] punk = cast(self, POINTER(itf)) result = punk.QueryInterface(itf)", "this interface: itf = self._com_interfaces_[0] punk = cast(self, POINTER(itf)) result", "return klass # XXX We should insist that a _reg_clsid_", "for CoClass # # When a CoClass subclass is created,", "clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" %", "= namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__,", "IUnknown pointer, represented as a c_void_p instance, # but we", "a POINTER(App) type, where class App is a subclass of", "interface: itf = self._com_interfaces_[0] punk = cast(self, POINTER(itf)) result =", "want this interface: itf = self._com_interfaces_[0] punk = cast(self, POINTER(itf))", "but we really want this interface: itf = self._com_interfaces_[0] punk", "type # for that class, with bases <coclass> and c_void_p.", "= cast(self, POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return", "klass = type.__new__(cls, name, bases, namespace) if bases == (object,):", "cast import comtypes ################################################################ # metaclass for CoClass (in comtypes/__init__.py)", "# the coclass' _com_interfaces_ list. def __new__(cls, name, bases, namespace):", "object class _coclass_meta(type): # metaclass for CoClass # # When", "# The mro() of a POINTER(App) type, where class App", "class, with bases <coclass> and c_void_p. Also, the # POINTER(...)", "represented as a c_void_p instance, # but we really want", "c_void_p # _SimpleCData # _CData # object class _coclass_meta(type): #", "# App # CoClass # c_void_p # _SimpleCData # _CData", "POINTER(...) type gets a __ctypes_from_outparam__ method which # will QueryInterface", "classmethod(_coclass_from_param), }) from ctypes import _pointer_type_cache _pointer_type_cache[klass] = PTR return", "cast(self, POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result", "c_void_p instance, # but we really want this interface: itf", "App is a subclass of CoClass: # # POINTER(App) #", "that class, with bases <coclass> and c_void_p. Also, the #", "first one on # the coclass' _com_interfaces_ list. def __new__(cls,", "namespace): klass = type.__new__(cls, name, bases, namespace) if bases ==", "isinstance(obj, (cls._com_interfaces_[0], cls)): return obj raise TypeError(obj) # # The", "metaclass for CoClass # # When a CoClass subclass is", "will not work if we change the order of the", "punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result def _coclass_from_param(cls, obj): if", "change the order of the two base classes! class _coclass_pointer_meta(type(c_void_p),", "create a POINTER(...) type # for that class, with bases", "if \"_reg_clsid_\" in namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass", "POINTER(...) type # for that class, with bases <coclass> and", "we change the order of the two base classes! class", "= str(self._reg_clsid_) return result def _coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0],", "that a _reg_clsid_ is present. if \"_reg_clsid_\" in namespace: clsid", "Also, the # POINTER(...) type gets a __ctypes_from_outparam__ method which", "_coclass_meta(type): # metaclass for CoClass # # When a CoClass", "# # When a CoClass subclass is created, create a", "When a CoClass subclass is created, create a POINTER(...) type", "klass # XXX We should insist that a _reg_clsid_ is", "klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass,", "}) from ctypes import _pointer_type_cache _pointer_type_cache[klass] = PTR return klass", "# c_void_p # _SimpleCData # _CData # object class _coclass_meta(type):", "# # The mro() of a POINTER(App) type, where class", "def _wrap_coclass(self): # We are an IUnknown pointer, represented as", "namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass,", "{\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from ctypes import _pointer_type_cache _pointer_type_cache[klass]", "if bases == (object,): return klass # XXX We should", "order of the two base classes! class _coclass_pointer_meta(type(c_void_p), _coclass_meta): pass", "with bases <coclass> and c_void_p. Also, the # POINTER(...) type", "# will not work if we change the order of", "= PTR return klass # will not work if we", "raise TypeError(obj) # # The mro() of a POINTER(App) type,", "# comtypes._meta helper module from ctypes import POINTER, c_void_p, cast", "c_void_p, cast import comtypes ################################################################ # metaclass for CoClass (in", "\"from_param\": classmethod(_coclass_from_param), }) from ctypes import _pointer_type_cache _pointer_type_cache[klass] = PTR", "work if we change the order of the two base", "# # POINTER(App) # App # CoClass # c_void_p #", "the coclass' _com_interfaces_ list. def __new__(cls, name, bases, namespace): klass", "comtypes._meta helper module from ctypes import POINTER, c_void_p, cast import", "# metaclass for CoClass # # When a CoClass subclass", "CoClass subclass is created, create a POINTER(...) type # for", "for the default interface: the first one on # the", "CoClass: # # POINTER(App) # App # CoClass # c_void_p", "_wrap_coclass(self): # We are an IUnknown pointer, represented as a", "from ctypes import _pointer_type_cache _pointer_type_cache[klass] = PTR return klass #", "bases <coclass> and c_void_p. Also, the # POINTER(...) type gets", "POINTER(App) type, where class App is a subclass of CoClass:", "one on # the coclass' _com_interfaces_ list. def __new__(cls, name,", "subclass of CoClass: # # POINTER(App) # App # CoClass", "are an IUnknown pointer, represented as a c_void_p instance, #", "We should insist that a _reg_clsid_ is present. if \"_reg_clsid_\"", "bases, namespace): klass = type.__new__(cls, name, bases, namespace) if bases", "a subclass of CoClass: # # POINTER(App) # App #", "from ctypes import POINTER, c_void_p, cast import comtypes ################################################################ #", "# but we really want this interface: itf = self._com_interfaces_[0]", "the first one on # the coclass' _com_interfaces_ list. def", "should insist that a _reg_clsid_ is present. if \"_reg_clsid_\" in", "if we change the order of the two base classes!", "# We are an IUnknown pointer, represented as a c_void_p", "(cls._com_interfaces_[0], cls)): return obj raise TypeError(obj) # # The mro()", "# POINTER(App) # App # CoClass # c_void_p # _SimpleCData", "created, create a POINTER(...) type # for that class, with", "% klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from", "PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\":", "result.__dict__[\"__clsid\"] = str(self._reg_clsid_) return result def _coclass_from_param(cls, obj): if isinstance(obj,", "class _coclass_meta(type): # metaclass for CoClass # # When a", "(in comtypes/__init__.py) def _wrap_coclass(self): # We are an IUnknown pointer,", "punk = cast(self, POINTER(itf)) result = punk.QueryInterface(itf) result.__dict__[\"__clsid\"] = str(self._reg_clsid_)", "_coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0], cls)): return obj raise TypeError(obj)", "pointer, represented as a c_void_p instance, # but we really", "CoClass # c_void_p # _SimpleCData # _CData # object class", "<coclass> and c_void_p. Also, the # POINTER(...) type gets a", "# will QueryInterface for the default interface: the first one", "coclass' _com_interfaces_ list. def __new__(cls, name, bases, namespace): klass =", "# metaclass for CoClass (in comtypes/__init__.py) def _wrap_coclass(self): # We", "comtypes/__init__.py) def _wrap_coclass(self): # We are an IUnknown pointer, represented", "obj raise TypeError(obj) # # The mro() of a POINTER(App)", "# for that class, with bases <coclass> and c_void_p. Also,", "= klass PTR = _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\":", "a __ctypes_from_outparam__ method which # will QueryInterface for the default", "in namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR =", "type gets a __ctypes_from_outparam__ method which # will QueryInterface for", "_pointer_type_cache[klass] = PTR return klass # will not work if", "bases, namespace) if bases == (object,): return klass # XXX", "klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param), }) from ctypes", "name, bases, namespace) if bases == (object,): return klass #", "on # the coclass' _com_interfaces_ list. def __new__(cls, name, bases,", "a _reg_clsid_ is present. if \"_reg_clsid_\" in namespace: clsid =", "= _coclass_pointer_meta(\"POINTER(%s)\" % klass.__name__, (klass, c_void_p), {\"__ctypes_from_outparam__\": _wrap_coclass, \"from_param\": classmethod(_coclass_from_param),", "we really want this interface: itf = self._com_interfaces_[0] punk =", "str(self._reg_clsid_) return result def _coclass_from_param(cls, obj): if isinstance(obj, (cls._com_interfaces_[0], cls)):", "\"_reg_clsid_\" in namespace: clsid = namespace[\"_reg_clsid_\"] comtypes.com_coclass_registry[str(clsid)] = klass PTR", "cls)): return obj raise TypeError(obj) # # The mro() of", "module from ctypes import POINTER, c_void_p, cast import comtypes ################################################################", "TypeError(obj) # # The mro() of a POINTER(App) type, where", "# _SimpleCData # _CData # object class _coclass_meta(type): # metaclass", "and c_void_p. Also, the # POINTER(...) type gets a __ctypes_from_outparam__", "which # will QueryInterface for the default interface: the first", "klass # will not work if we change the order", "ctypes import _pointer_type_cache _pointer_type_cache[klass] = PTR return klass # will" ]
[ "callbacks if not in continuous mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get())", "self.opPanel.lockUnlockDisplay() if __name__ == '__main__': def foo(val): print val d", "return d={} for k, w in self.labCfg.items(): if k ==", "x1, y1 ] pts2 = [ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth,", "0 or 1. 1 disables, 0 enables. Setting values with", "without even the implied warranty of ## MERCHANTABILITY or FITNESS", "lockValue self.lockType = lockType self.lockContinuous = lockContinuous self.lockOneTurn = lockOneTurn", "got %s\"%( type(0), type(0.0), type(min) ) if self.max and min", "this new <value> \"\"\" def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None},", "self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) # the 'lock'", "def set(self, val, update=1, force=0): # if force is set", "if self.showLabel == 1: self.printLabel() if self.value < self.min: self.set(self.min)", "in the hope that it will be useful, ## but", "self.max: val = self.max # recompute vector and angle corresponding", "<0.0: self.angle = self.angle - 360.0 a = self.angle*self.pyOver180 self.vector", "be added to this new <value> \"\"\" def __init__(self, master=None,", "Label options self.labelFont = ( ensureFontCase('helvetica'), 14, 'bold') # label", "lockShowLabelCB(self, mode): if mode != 0: mode = 1 self.lockShowLabel", "call callbacks at # each value change, else gets called", "self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth) self.arrowPolborder2 =", "key=='plus': if key == 'period': key = '.' elif key", "defines widget size self.offsetValue = 0. # used to set", "self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self):", "def mouseWheel(self, event): #print \"mouseWheel\", event, event.num if os.name ==", "self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas", "1 # turn on to display label on self.continuous =", "widget self.showLabel = 1 # turn on to display label", "General Public ## License as published by the Free Software", "key = '+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event)", "!= 0: mode = 1 self.lockIncrement = mode if hasattr(self.opPanel,", "# no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if", "> self.max: min = self.max self.min = self.type(min) if self.showLabel", "= 4 else: lEventNum = 5 else: lEventNum = event.num", "turn self.value = 0.0 # current value of widget self.oldValue", "self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name == 'nt': #sys.platform == 'win32':", "with default values self.precision = 2 # decimal places self.min", "else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if size is not None:", "to 2, setting the value to 6 will actually result", "def lockBIncrementCB(self, mode): # increment checkbutton if mode != 0:", "ma = 1.0 elif ma < -1.0: ma = -1.0", "360 units by default. A dial can also operate in", "get(self): return self.type(self.value) def printLabel(self): if self.canvas is None: return", "<EMAIL> # <EMAIL> # # Copyright: <NAME>, <NAME> and TSRI", "rotation, sign of z component of vector prod. oldv =", "not None: self.setSize(size) aS = self.size/40 self.arrowLength = max(3, 3*aS)", "self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas is None: return #", "is None or callable(cb) or type(cb) is types.ListType,\\ \"Illegal callback:", "== 'nt': #sys.platform == 'win32': if event.delta > 0: lEventNum", "text = labCfg.get('text', None) if text is None or text=='':", "store old values self.maxOld = 0. self.incrementOld = increment self.size", "lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel = lockShowLabel", "and size can be passed only to the constructor. a", "!= 0: mode = 1 self.lockType = mode if hasattr(self.opPanel,", "= OptionsPanel(master = self, title=\"Dial Options\") ## if self.callback: ##", "optional keyword force=True, i.e. dial.set(<value>, force=True)), which will set the", "the widget in self.usedArcColor = '#aaaaaa' # filled arc color", "oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi = oneTurn", "if dval <0.0: self.angle = self.angle - 360.0 a =", "< 1: val = 1 self.precision = val if self.type", "will actually result in 7 (3,5,7,9,.....) To still be able", "datatype. Expected %s or %s, got %s\"%( type('a'), type(type), type(Type)", "= math.acos(ma) # find the sign of the rotation, sign", "mode = 1 self.lockContinuous = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "val, update=1, force=0): # if force is set to 1,", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): # increment checkbutton", "self.setLabel(value) elif key=='type': self.setType(value) elif key=='min': self.setMin(value) elif key=='max': self.setMax(value)", "as an argument. An optional label can be displayed at", "##################################################################### def configure(self, **kw): for key,value in kw.items(): # the", "None self.continuous = cont if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget']", "is called every time the widget value is set/modified\"\"\" assert", "if normz>0: ang = -1. * ang # compute the", "= canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='', font = self.labelFont) self.drawArrow()", "= self.min else: self.min = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0)", "function. Callback is called every time the widget value is", "== 2: # show widget labels only when mouse moves", "got %s\"%( type('a'), type(type), type(Type) ) if type(Type) == type(\"\"):", "size=None): if size is not None: self.setSize(size) aS = self.size/40", "attributes with default values self.precision = 2 # decimal places", "- 360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.drawArrow()", "if val > 10: val = 10 if val <", "lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw):", "show always widget labels self.showLabel=1 self.printLabel() if val == 2:", "== int: w.setvalue('int') elif self.type == 'float': w.setvalue('float') if self.opPanel:", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): # min checkbutton if mode", "text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event): dx = event.x-self.xm dy", "key == 'period': key = '.' elif key == 'minus':", "if self.showLabel == 0: label = 'never' elif self.showLabel ==", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if mode != 0: mode", "The widget tried to adjust automatically the size of the", "remember where the mouse went down self.lastx = event.x self.lasty", "it and/or ## modify it under the terms of the", "in widget keyboard entry label key = event.keysym if key.isdigit()", "lock<X> vars are used in self.lock() self.lockMax = lockMax #", "if self.min is not None and val < self.min: val", "set(), the actual value will 'snap' to the next increment.", "self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas =", "self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if val == 1: #", "default. A dial can also operate in discrete mode (if", "arrow in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if mode != 0: mode", "components of the options panel. Usage: <instance>.lock(<component>=<value>) components see configure().", "= self.size/40 self.arrowLength = max(3, 3*aS) # arrow head length", "update=1, force=0): # if force is set to 1, we", "= lockMin # lock<X> vars are used in self.lock() self.lockMax", "GNU Lesser General Public ## License along with this library;", "of the GNU Lesser General Public ## License along with", "able to set the value, disregarding the current active increment,", "1.0 elif ma < -1.0: ma = -1.0 # compute", "= dval + offset if self.min is not None and", "set in the options panel # snap to closest increment", "val == 1: # show always widget labels self.showLabel=1 self.printLabel()", "for k, w in self.labCfg.items(): if k == 'side': continue", "0: mode = 1 self.lockType = mode if hasattr(self.opPanel, 'optionsForm'):", "the optional keyword force=True, i.e. dial.set(<value>, force=True)), which will set", "= int(val) if val > 10: val = 10 if", "the Dial widget. The size of the dial has to", "\"Illegal type for oneTurn. Expected %s or %s, got %s\"%(", "<value>. The increment will now be added to this new", "be either None or callable, or list. Got %s\"%cb if", "def mouseMove(self, event): dx = event.x-self.xm dy = self.ym-event.y n", "values that are allowed. By defaults these are set to", "force=True)), which will set the value to <value>. The increment", "if mode != 0: mode = 1 self.lockPrecision = mode", "# shadow lines self.arrowHeadWidth = 2*self.arrowWidth # width of arrow", "under the terms of the GNU Lesser General Public ##", "not None and val < self.min: val = self.min elif", "self.lockMin = lockMin # lock<X> vars are used in self.lock()", "\"%d\" self.int_value = self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel,", "self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val): assert type(val) in", "text='') def setValue(self, val): if type(val) == types.StringType: val =", "self.lockMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode):", "of widget self.showLabel = 1 # turn on to display", "None) if text is None or text=='': return d={} for", "math import types import sys import os from mglutil.util.callback import", "used to disable the various gui components of the options", "\"\"\"Show label can be 0, 1 or 2 0: no", "object to manage callback # functions. They get called with", "self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg = labCfg text =", "1 self.lockShowLabel = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self,", "min > self.max: min = self.max self.min = self.type(min) if", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if mode", "the angle between new hand position and previous # hand", "if mode != 0: mode = 1 self.lockBMin = mode", "func in cb: assert callable(func), \"Illegal callback must be callable.", "if self.canvas and self.showLabel == 1: self.printLabel() def setContinuous(self, cont):", "of z component of vector prod. oldv = self.vector normz", "else: col1 = 'black' col2 = '#DDDDDD' apply( canvas.coords, (self.arrowPolId,)", "event): #print \"mouseWheel\", event, event.num if os.name == 'nt': #sys.platform", "# width of arrow # shadow lines self.arrowHeadWidth = 2*self.arrowWidth", "= event.keysym if key.isdigit() or key=='period' or key=='minus' or key=='plus':", "v[1]*self.vector[1] # assure no rounding errors if ma > 1.0:", "angle between new hand position and previous # hand position", "callback: must be either None or callable, or list. Got", "in a window maybe import traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self,", "self.ym - self.vector[1]*self.rad # point at arrow head base xb", "k == 'side': continue else: d[k] = w if not", "type descriptor. Expected 'int' or 'float', got '%s'\"%Type self.type =", "self.showLabel == 0: label = 'never' elif self.showLabel == 1:", "-1. * ang # compute the new value val =", "self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\",", "mouseDown(self, event): # remember where the mouse went down self.lastx", "w in self.labCfg.items(): if k == 'side': continue else: d[k]", "for func in cb: assert callable(func), \"Illegal callback must be", "Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks = CallbackManager() # object to manage", "full turn self.value = 0.0 # current value of widget", "= labCfg text = labCfg.get('text', None) if text is None", "entry field if mode != 0: mode = 1 self.lockMin", "0. # used to store old values self.maxOld = 0.", "is None: return # end point x1 = self.xm +", "self.offsetValue=self.value self.oldValue = self.value #update arrow in display self.angle =", "= (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle = self.angle - 360.0", "0, 1 or 2\" return self.showLabel = val self.toggleWidgetLabel(val) if", "val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel", "= self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def", "widget labels self.showLabel=1 self.printLabel() if val == 2: # show", "arrow in display self.drawArrow() newVal = self.get() if self.continuous or", "Lesser General Public ## License as published by the Free", "'left' if not self.lab: self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\",", "if os.name == 'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else:", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if mode", "2, self.ym, size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' )", "force: if update and self.oldValue != newVal or force: self.oldValue", "the options panel # snap to closest increment if self.increment", "= [math.sin(a), math.cos(a)] self.value = dval self.offsetValue = dval else:", "0: mode = 1 self.lockMax = mode if hasattr(self.opPanel, 'optionsForm'):", "self.type(min) if self.showLabel == 1: self.printLabel() if self.value < self.min:", "even the implied warranty of ## MERCHANTABILITY or FITNESS FOR", "fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 =", "1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg =", "else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size): \"\"\"Set widget size. Size", "== 1: self.printLabel() if self.value < self.min: self.set(self.min) if hasattr(self.opPanel,", "val != 0 and val != 1 and val !=", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if mode != 0:", "manage callback # functions. They get called with the #", "of the Dial widget. The size of the dial has", "self.setMax(value) elif key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value)", "1 to call callbacks at # each value change, else", "elif key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif", "yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas = self.canvas if", "> self.max: val = self.max self.value = self.type(val) self.offsetValue=self.value self.oldValue", "'__main__': def foo(val): print val d = Dial(size=50) d.configure(showLabel=1) d.callbacks.AddCallback(foo)", "'configure' methods: ##################################################################### def configure(self, **kw): for key,value in kw.items():", "if self.value <0.0: self.angle = self.angle - 360.0 a =", "== 'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel)", "self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value)", "head base xb = self.xm + self.vector[0]*self.radNoArrow yb = self.xm", "key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) # the 'lock' entries callbacks", "1 full turn self.value = 0.0 # current value of", "else gets called # on button release event self.angle =", "lockOneTurn self.setArrow() # configure with user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous)", "size > 0, \"Illegal size: must be > 0, got", "mode != 0: mode = 1 self.lockType = mode if", "meaning that there is no min and no max. One", "\"mouseWheel\", event, event.num if os.name == 'nt': #sys.platform == 'win32':", "# user specified callback self.opPanel = None # option panel", "0.0: col1 = '#DDDDDD' col2 = 'black' else: col1 =", "used to set increment correctly self.lab = None # label", "hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0", "math.pi/360. self.lockMin = lockMin # lock<X> vars are used in", "== 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self,", "moved around a circle. The range corresponding to one full", "self.lockValue = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode):", "self.increment is set to x). In this mode the values", "on button release event self.angle = 0. # angle corresponding", "Public ## License along with this library; if not, write", "functions. They get called with the # current value as", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min", "# initialize various attributes with default values self.precision = 2", "disable the various gui components of the options panel. Usage:", "def lockIncrementCB(self, mode): # increment entry field if mode !=", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr): if incr", "= 1 self.lockPrecision = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "in [types.IntType, types.FloatType],\\ \"Illegal type for value: expected %s or", "'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0: label =", "val > self.max: val = self.max self.value = self.type(val) self.offsetValue=self.value", "(dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle = self.angle - 360.0 a", "= 1 self.lockOneTurn = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if", "This library is distributed in the hope that it will", ") r = size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white')", "2: show label only when value changes\"\"\" assert val in", "if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show label can be", "self.lockOneTurn = lockOneTurn self.setArrow() # configure with user-defined values self.setSize(size)", "\"Illegal type for value: expected %s or %s, got %s\"%(", "fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId", "size: must be > 0, got %s\"%size self.size = size", "width = self.arrowBorderwidth ) r = size/20 off = self.arrowBorderwidth", "Expected %s or %s, got %s\"%( type('a'), type(type), type(Type) )", "self.lockBMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode):", "= self.xm - self.vector[1]*self.radNoArrow # vector orthogonal to arrow n", "self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w =", "type for oneTurn. Expected %s or %s, got %s\"%( type(0),", "\"Illegal type for minimum. Expected type %s or %s, got", "library is free software; you can redistribute it and/or ##", "self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal", "Dial widget. The size of the dial has to be", "mode): if mode != 0: mode = 1 self.lockShowLabel =", "self.max else: self.max = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled',", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): # increment entry", "self.lockBIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode):", "self.showLabel == 1: self.printLabel() if self.value < self.min: self.set(self.min) if", "should have received a copy of the GNU Lesser General", "= self.vector normz = oldv[0]*v[1] - oldv[1]*v[0] if normz>0: ang", "= 'black' col2 = '#DDDDDD' apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2)", "can redistribute it and/or ## modify it under the terms", "= CallbackManager() # object to manage callback # functions. They", "widget has a configure() method: type, min, max, increment, precision,", "the sign of the rotation, sign of z component of", "min is not None: assert type(min) in [types.IntType, types.FloatType],\\ \"Illegal", "## Lesser General Public License for more details. ## ##", "= lockOneTurn self.setArrow() # configure with user-defined values self.setSize(size) self.setCallback(callback)", "and previous # hand position ma = v[0]*self.vector[0] + v[1]*self.vector[1]", "self.size/40 self.arrowLength = max(3, 3*aS) # arrow head length self.arrowWidth", "%s\"%cb if cb is None: return elif type(cb) is types.ListType:", "< self.min: val = self.min elif self.max is not None", "turn can be specified as well as the min and", "'period': key = '.' elif key == 'minus': key =", "type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0, precision=2, showLabel=1, value=0.0, continuous=1,", "size of the dial has to be specified at instanciation.", "elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif", "canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master = self,", "= self.xm + self.vector[0]*self.rad y1 = self.ym - self.vector[1]*self.rad #", "to store old values self.maxOld = 0. self.incrementOld = increment", "self.vector normz = oldv[0]*v[1] - oldv[1]*v[0] if normz>0: ang =", "\"Illegal type for precision. Expected type %s or %s, got", "self.drawArrow() newVal = self.get() if self.continuous or force: if update", "'bold') # label font self.labelColor = 'yellow' # label color", "type(0), type(0.0), type(incr) ) self.increment = self.type(incr) self.offsetValue = self.value", "passed only to the constructor. a lock() method is used", "assert callable(func), \"Illegal callback must be callable. Got %s\"%func self.callbacks.AddCallback(func)", "type(Type) ) if type(Type) == type(\"\"): # type str assert", "min and max values that are allowed. By defaults these", "event.num if os.name == 'nt': #sys.platform == 'win32': if event.delta", "value increment self.minOld = 0. # used to store old", "dval = self.max # recompute vector and angle corresponding to", "precision, showLabel, value, continuous, oneTurn can be set this way.", "In this mode the values will be restrained to be", "widget self.oneTurn = 360. # value increment for 1 full", "2016 ## ################################################################################ ######################################################################### # # Date: Mai 2001 Authors:", "elif key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) #", "w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() # and update", "canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth ) r = size/20", "write to the Free Software ## Foundation, Inc., 51 Franklin", "self.size = size def setCallback(self, cb): \"\"\"Set widget callback. Must", "type, min, max, increment, precision, showLabel, value, continuous, oneTurn can", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if size", "= newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else: if self.showLabel==2: self.printLabel()", "elif key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif", "elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif", "when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self,", "KeyboardEntry): \"\"\"This class implements a Dial widget. The widget has", "self.increment. The Widget has a Callback manager. Callback functions get", "self.type(val) self.offsetValue=self.value self.oldValue = self.value #update arrow in display self.angle", "to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle =", "'+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self,", "if n == 0.0: v = [0.0, 0.0] else: v", "if mode != 0: mode = 1 self.lockOneTurn = mode", "dval > self.max: dval = self.max # recompute vector and", "= Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm", "if min is not None: assert type(min) in [types.IntType, types.FloatType],\\", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if mode !=", "keyword force=True, i.e. dial.set(<value>, force=True)), which will set the value", "base def mouseDown(self, event): # remember where the mouse went", "em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if", "4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self): return self.type(self.value) def printLabel(self):", "y1 ] pts2 = [ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth,", "label color self.canvas = None # the canvas to create", "%s or %s, got %s\"%( type('a'), type(type), type(Type) ) if", "self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg)", "= self.get() if self.continuous or force: if update and self.oldValue", "example the case if the dial # is set to", "'win32': if event.delta > 0: lEventNum = 4 else: lEventNum", "[types.IntType, types.FloatType],\\ \"Illegal type for value: expected %s or %s,", "of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See", "minimum. Expected type %s or %s, got %s\"%( type(0), type(0.0),", "mode != 0: mode = 1 self.lockBMax = mode if", "# defines widget size self.offsetValue = 0. # used to", "values will be restrained to be multiples of self.increment. The", "self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value)", "update and self.oldValue != newVal or force: self.oldValue = newVal", "= self.min elif self.max is not None and val >", "= increment # value increment self.minOld = 0. # used", "in discrete mode (if self.increment is set to x). In", "import traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event): # handle key", "if event.delta > 0: lEventNum = 4 else: lEventNum =", "1 self.piOver1turn = math.pi/360. self.lockMin = lockMin # lock<X> vars", "3, and the increment is set to 2, setting the", "type(0), type(0.0), type(min) ) if self.max and min > self.max:", "to arrow n = [-self.vector[1], -self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth,", "for increment. Expected type %s or %s, got %s\"%( type(0),", "None: return elif type(cb) is types.ListType: for func in cb:", "self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): # increment entry field if mode", "# Tkinter Label options self.labelFont = ( ensureFontCase('helvetica'), 14, 'bold')", "up in a window maybe import traceback traceback.print_stack() traceback.print_exc() def", "is set in the options panel # snap to closest", "now be added to this new <value> \"\"\" def __init__(self,", "lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks", "in [types.IntType, types.FloatType],\\ \"Illegal type for increment. Expected type %s", "can be moved around a circle. The range corresponding to", "head base def mouseDown(self, event): # remember where the mouse", "val): if type(val) == types.StringType: val = float(val) assert type(val)", "= 1 self.lockBIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel", "disables, 0 enables. Setting values with increment enabled: if using", "no min and no max. One turn corresponds to 360", "if self.showLabel==2: self.printLabel() else: if self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel()", "Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA", "[None, 0, 1],\\ \"Illegal value for continuous: expected None, 0", "change, else gets called # on button release event self.angle", "cont if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1", "Expected %s or %s, got %s\"%( type(0), type(0.0), type(oneTurn) )", "== 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self): return self.type(self.value) def", "if self.vector[0] > 0.0: col1 = '#DDDDDD' col2 = 'black'", "os.name == 'nt': #sys.platform == 'win32': if event.delta > 0:", "# constants used in various places self.threeSixtyOver1turn = 1 self.piOver1turn", "OptionsPanel from KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class", "in the options panel # snap to closest increment if", "def lockMinCB(self, mode): #min entry field if mode != 0:", "'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment = self.type(0) if", "create the widget in self.usedArcColor = '#aaaaaa' # filled arc", "a circle. The range corresponding to one full turn can", "\"Illegal size: must be > 0, got %s\"%size self.size =", "instanciation. Other parameters can be set after the widget has", "release event self.angle = 0. # angle corresponding to value", "types.IntType),\\ \"Illegal size: expected type %s, got %s\"%(type(1), type(size) )", "self.max self.min = self.type(min) if self.showLabel == 1: self.printLabel() if", "not in continuous mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel", "canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2,", "for precision. Expected type %s or %s, got %s\"%( type(0),", "used in self.lock() self.lockMax = lockMax # to lock/unlock entries", "the value to 6 will actually result in 7 (3,5,7,9,.....)", "apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2 )", "import sys import os from mglutil.util.callback import CallbackManager from mglutil.util.misc", "self.callback = cb def toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else:", "= [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1", "only to the constructor. a lock() method is used to", "\"Illegal type for increment. Expected type %s or %s, got", "value self.increment = increment # value increment self.minOld = 0.", "correctly self.lab = None # label self.callback = None #", "values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment)", "This library is free software; you can redistribute it and/or", "col1 = 'black' col2 = '#DDDDDD' apply( canvas.coords, (self.arrowPolId,) +", "== 2: label = 'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def", "%s or %s, got %s\"%( type(0), type(0.0), type(max) ) if", "configure(). value is 0 or 1. 1 disables, 0 enables.", "or force: if update and self.oldValue != newVal or force:", "#min entry field if mode != 0: mode = 1", "new value val = self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx =", "functions get called at every value change if self.contiguous is", "value self.max = None # maximum value self.increment = increment", "no label 1: label is always shown 2: show label", "= None self.continuous = cont if hasattr(self.opPanel, 'optionsForm'): w =", "# option panel widget self.oneTurn = 360. # value increment", "key=='minus' or key=='plus': if key == 'period': key = '.'", "to 360 units by default. A dial can also operate", "cont != 1: cont = None self.continuous = cont if", "software; you can redistribute it and/or ## modify it under", "value of widget self.showLabel = 1 # turn on to", "= math.pi/180.0 # constants used in various places self.threeSixtyOver1turn =", "self.lockShowLabel = lockShowLabel self.lockValue = lockValue self.lockType = lockType self.lockContinuous", "= ( ensureFontCase('helvetica'), 14, 'bold') # label font self.labelColor =", "be passed only to the constructor. a lock() method is", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if mode !=", "2\" return self.showLabel = val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w", "not None: assert type(incr) in [types.IntType, types.FloatType],\\ \"Illegal type for", "value will 'snap' to the next increment. i.e., if the", "received a copy of the GNU Lesser General Public ##", "# half the arrow body width self.arrowBorderwidth = max(1, self.arrowWidth/2)", "fill='black', justify='center', text='', font = self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym,", "= 360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi = oneTurn / (2*math.pi)", "<NAME>, <NAME> # # <EMAIL> # <EMAIL> # # Copyright:", "is set to x). In this mode the values will", "extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm, 2, self.ym, size+2)", "An optional label can be displayed at the center of", "lockTypeCB(self, mode): if mode != 0: mode = 1 self.lockType", "current active increment, the set method understands the optional keyword", "0, 1 or 2 0: no label 1: label is", "width of arrow head base def mouseDown(self, event): # remember", "not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if", "'yellow' # label color self.canvas = None # the canvas", "# hand position ma = v[0]*self.vector[0] + v[1]*self.vector[1] # assure", "max < self.min: max = self.min self.max = self.type(max) if", "Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr. <NAME>", "self.callback = None # user specified callback self.opPanel = None", "self.printLabel() if self.value > self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max)", "max is not None: assert type(max) in [types.IntType, types.FloatType],\\ \"Illegal", "of the options panel. Usage: <instance>.lock(<component>=<value>) components see configure(). value", "if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else:", "def toggleWidgetLabel(self, val): if val == 0: # no widget", "self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = dval self.offsetValue =", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min else:", "self.minOld = self.min else: self.min = None if hasattr(self.opPanel, 'optionsForm'):", "eval(Type) else: self.type = Type if self.type == int: self.labelFormat", "self.type == float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\"", "manager. Callback functions get called at every value change if", "lockPrecision self.lockShowLabel = lockShowLabel self.lockValue = lockValue self.lockType = lockType", "= self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if n == 0.0: v", "self.showLabel = 1 # turn on to display label on", "must be of type int and greater than 0\"\"\" assert", "w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int: w.setvalue('int') elif self.type", "or force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else:", "a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = dval", "yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas = self.canvas if self.vector[0] >", "== 'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() # and update the", "if os.name == 'nt': #sys.platform == 'win32': if event.delta >", "self.lastx = event.x self.lasty = event.y def mouseWheel(self, event): #print", "max(1, self.arrowWidth/2) # width of arrow # shadow lines self.arrowHeadWidth", "useful, ## but WITHOUT ANY WARRANTY; without even the implied", "if self.type == int: self.labelFormat = \"%d\" self.int_value = self.value", "widget keyboard entry label key = event.keysym if key.isdigit() or", "event self.angle = 0. # angle corresponding to value self.labCfg", "hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0: label", "types.TypeType],\\ \"Illegal type for datatype. Expected %s or %s, got", "canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name == 'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\",", "must be either None or callable, or list. Got %s\"%cb", "= float(val) assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for", "def createCanvas(self, master): size = self.size self.frame = Tkinter.Frame(self, borderwidth=3,", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max): if max", "You should have received a copy of the GNU Lesser", "newVal = self.get() if self.continuous or force: if update and", "def lockPrecisionCB(self, mode): if mode != 0: mode = 1", "1, we call this method regardless of the # widget", "Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm = self.ym = size/2+2 self.rad =", "and val > self.max: val = self.max self.value = self.type(val)", "has a configure() method: type, min, max, increment, precision, showLabel,", "fg='gray40') def setMax(self, max): if max is not None: assert", "widget labels only when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId,", "def lockOneTurnCB(self, mode): if mode != 0: mode = 1", "= lockMax # to lock/unlock entries in optionpanel self.lockIncrement =", "self.printLabel() if self.value < self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min)", "ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x self.lasty = event.y def mouseWheel(self,", "None # label self.callback = None # user specified callback", "self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr): if incr is not None:", ") # setValue does NOT call a callback! if self.min", "7 (3,5,7,9,.....) To still be able to set the value,", "self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) #####################################################################", "of the License, or (at your option) any later version.", ") self.oneTurn = oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn = math.pi/oneTurn", "float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\" if hasattr(self.opPanel,", "else: self.max = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40')", "= None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self,", "360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.drawArrow() if", "def get(self): return self.type(self.value) def printLabel(self): if self.canvas is None:", "value val = self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x", "to create the widget in self.usedArcColor = '#aaaaaa' # filled", "math.cos(a)] self.drawArrow() if self.showLabel == 1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value)", "labels only when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='')", "elif self.showLabel == 2: label = 'move' w.setvalue(label) if self.opPanel:", "= \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type", "== 2: # no widget labels on mouse release self.canvas.itemconfigure(self.labelId2,", "val != 1 and val != 2: print \"Illegal value.", "but the value is set in the options panel #", "self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else: if self.showLabel==2: self.printLabel() if self.showLabel==1:", "self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value)", "######################################################################### import Tkinter import math import types import sys import", "corresponds to 360 units by default. A dial can also", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): # max checkbutton if mode", "<NAME> and TSRI # ######################################################################### import Tkinter import math import", "self.arrowBorderwidth = max(1, self.arrowWidth/2) # width of arrow # shadow", "and max < self.min: max = self.min self.max = self.type(max)", "OptionsPanel(master = self, title=\"Dial Options\") ## if self.callback: ## self.callbacks.AddCallback(self.callback)", "pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val):", "one full turn can be specified as well as the", "mode): # increment entry field if mode != 0: mode", "'float', got '%s'\"%Type self.type = eval(Type) else: self.type = Type", "None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max):", "not None: assert type(max) in [types.IntType, types.FloatType],\\ \"Illegal type for", "the License, or (at your option) any later version. ##", "and not force: offset = self.offsetValue%self.increment dval = round(val/self.increment) *", "val in [0,1,2],\\ \"Illegal value for showLabel. Expected 0, 1", "setType(self, Type): assert type(Type) in [types.StringType, types.TypeType],\\ \"Illegal type for", "# Copyright: <NAME>, <NAME> and TSRI # ######################################################################### import Tkinter", "import CallbackManager from mglutil.util.misc import ensureFontCase from optionsPanel import OptionsPanel", "x1 = self.xm + self.vector[0]*self.rad y1 = self.ym - self.vector[1]*self.rad", "def setFromEntry(self, valueString): try: self.set(self.type(valueString)) except ValueError: # fixme we", "to 1, else they get called when the mouse button", "created. The widget tried to adjust automatically the size of", "self.value > self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal',", "self.value <0.0: self.angle = self.angle - 360.0 a = self.angle*self.pyOver180", "\"\"\"This class implements a Dial widget. The widget has a", "1: self.printLabel() if self.value < self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'):", "mode != 0: mode = 1 self.lockOneTurn = mode if", "value changes\"\"\" assert val in [0,1,2],\\ \"Illegal value for showLabel.", "dval <0.0: self.angle = self.angle - 360.0 a = self.angle*self.pyOver180", "gui components of the options panel. Usage: <instance>.lock(<component>=<value>) components see", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val):", "not, write to the Free Software ## Foundation, Inc., 51", "if size is not None: self.setSize(size) aS = self.size/40 self.arrowLength", "or callable, or list. Got %s\"%cb if cb is None:", "discrete mode (if self.increment is set to x). In this", "various gui components of the options panel. Usage: <instance>.lock(<component>=<value>) components", "hope that it will be useful, ## but WITHOUT ANY", "= '#aaaaaa' # filled arc color of used portion self.unusedArcColor", "a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = val", "self.pyOver180 = math.pi/180.0 # constants used in various places self.threeSixtyOver1turn", "self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg = labCfg", "1 self.precision = val if self.type == float: self.labelFormat =", "value is set/modified\"\"\" assert cb is None or callable(cb) or", "vector prod. oldv = self.vector normz = oldv[0]*v[1] - oldv[1]*v[0]", "self.min elif self.max is not None and val > self.max:", "still be able to set the value, disregarding the current", "KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size): \"\"\"Set widget size. Size must", "(val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle = self.angle - 360.0 a", "xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2 = [", "corresponding to one full turn can be specified as well", "50 # defines widget size self.offsetValue = 0. # used", "self.xm + self.vector[0]*self.rad y1 = self.ym + self.vector[1]*self.rad canvas =", "entry field if mode != 0: mode = 1 self.lockIncrement", "self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD')", "# label font self.labelColor = 'yellow' # label color self.canvas", "mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2: #", "self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size):", "self.lockOneTurn = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ ==", "called at every value change if self.contiguous is set to", "self.ym, fill=self.labelColor, justify='center', text='', font = self.labelFont) self.drawArrow() self.opPanel =", "self.vector[0] > 0.0: col1 = '#DDDDDD' col2 = 'black' else:", "lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks =", "setIncrement(self, incr): if incr is not None: assert type(incr) in", "= val self.offsetValue = val #update arrow in display self.drawArrow()", "%s\"%( type(0), type(0.0), type(val) ) val = int(val) if val", "elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif", "KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements a", "recompute vector and angle corresponding to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn", "to continuous=0, but the value is set in the options", "canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2,", "self.canvas.itemconfigure(self.labelId, text='') if val == 1: # show always widget", "if val <0.0: self.angle = self.angle - 360.0 a =", "self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if val == 1: # show", "max entry field if mode != 0: mode = 1", "= 1 self.lockMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "oldv[0]*v[1] - oldv[1]*v[0] if normz>0: ang = -1. * ang", "if k == 'side': continue else: d[k] = w if", "it under the terms of the GNU Lesser General Public", "- self.vector[1]*self.radNoArrow # vector orthogonal to arrow n = [-self.vector[1],", "to 1 to call callbacks at # each value change,", "to set the value, disregarding the current active increment, the", "self.precision = val if self.type == float: self.labelFormat = \"%.\"+str(self.precision)+\"f\"", "None # minimum value self.max = None # maximum value", "in [0,1,2],\\ \"Illegal value for showLabel. Expected 0, 1 or", "self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm = self.ym = size/2+2", "## You should have received a copy of the GNU", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): #", "but WITHOUT ANY WARRANTY; without even the implied warranty of", "an argument. An optional label can be displayed at the", "arrow body width self.arrowBorderwidth = max(1, self.arrowWidth/2) # width of", "setArrow(self, size=None): if size is not None: self.setSize(size) aS =", "specified at instanciation. Other parameters can be set after the", "type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for precision. Expected type", "be useful, ## but WITHOUT ANY WARRANTY; without even the", "= self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70',", "* self.increment if val < dval: dval = dval +", "is free software; you can redistribute it and/or ## modify", "self.value self.incrementOld = self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal',", "%s or %s, got %s\"%( type(0), type(0.0), type(oneTurn) ) self.oneTurn", "relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm = self.ym =", "fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2,", "else: self.lab.configure(text) ##################################################################### # the 'configure' methods: ##################################################################### def configure(self,", "if not in continuous mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if", "fill=col2 ) canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def createCanvas(self, master): size", "y1 = self.ym + self.vector[1]*self.rad canvas = self.canvas self.circleId =", "cb is None: return elif type(cb) is types.ListType: for func", "label can be 0, 1 or 2 0: no label", "size. Size must be of type int and greater than", "- self.increment else: dval = dval + offset if self.min", "fill='gray75' ) self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth)", "is used to disable the various gui components of the", "**kw): for key,value in kw.items(): # the 'set' parameter callbacks", "+ self.vector[0]*self.radNoArrow yb = self.xm - self.vector[1]*self.radNoArrow # vector orthogonal", "self.lasty = event.y def mouseWheel(self, event): #print \"mouseWheel\", event, event.num", "value for continuous: expected None, 0 or 1, got %s\"%cont", "= \"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\" if hasattr(self.opPanel, 'optionsForm'): w", "Callback functions get called at every value change if self.contiguous", "will be useful, ## but WITHOUT ANY WARRANTY; without even", "type(incr) in [types.IntType, types.FloatType],\\ \"Illegal type for increment. Expected type", "self.offsetValue = val #update arrow in display self.drawArrow() newVal =", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if mode != 0:", "= self.type(incr) self.offsetValue = self.value self.incrementOld = self.increment if hasattr(self.opPanel,", "# current value of widget self.oldValue = 0.0 # old", "canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75'", "mode != 0: mode = 1 self.lockPrecision = mode if", "= size/2+2 self.rad = size/2 self.radNoArrow = self.rad-self.arrowLength self.vector =", "ensureFontCase('helvetica'), 14, 'bold') # label font self.labelColor = 'yellow' #", "display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle = self.angle", "= self.max else: self.max = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0)", "None # the canvas to create the widget in self.usedArcColor", "if self.canvas is None: return # end point x1 =", "self.xm = self.ym = size/2+2 self.rad = size/2 self.radNoArrow =", "if self.showLabel == 1: self.printLabel() if self.value > self.max: self.set(self.max)", "= 1 self.lockIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "is 0 or 1. 1 disables, 0 enables. Setting values", "self.vector = [math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel == 1: self.printLabel()", "rounding errors if ma > 1.0: ma = 1.0 elif", "self.lab.configure(text) ##################################################################### # the 'configure' methods: ##################################################################### def configure(self, **kw):", "force: offset = self.offsetValue%self.increment dval = round(val/self.increment) * self.increment if", "corresponding to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle", "= self.max self.value = self.type(val) self.offsetValue=self.value self.oldValue = self.value #update", "of the rotation, sign of z component of vector prod.", "of the # widget configuration. This is for example the", "w if not 'side' in self.labCfg.keys(): self.labCfg['side'] = 'left' if", "that can be moved around a circle. The range corresponding", "got %s\"%val if val != 0 and val != 1", "to value self.labCfg = labCfg # Tkinter Label options self.labelFont", "ang = -1. * ang # compute the new value", "self.min and max < self.min: max = self.min self.max =", "# lock<X> vars are used in self.lock() self.lockMax = lockMax", "== int: self.labelFormat = \"%d\" self.int_value = self.value else: self.labelFormat", "or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ##", "[types.IntType, types.FloatType],\\ \"Illegal type for oneTurn. Expected %s or %s,", "self.oneTurnOver2pi = oneTurn / (2*math.pi) if self.opPanel: self.opPanel.updateDisplay() ##################################################################### #", "# no widget labels on mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId,", "library; if not, write to the Free Software ## Foundation,", "max, increment, precision, showLabel, value, continuous, oneTurn can be set", "self.lockMax = lockMax # to lock/unlock entries in optionpanel self.lockIncrement", "self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master)", "not None and val < self.min: val = self.min if", "[dx/n, dy/n] # find the cosine of the angle between", "self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\",", "lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self,", "self.type == int: w.setvalue('int') elif self.type == 'float': w.setvalue('float') if", "elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def", "# end point x1 = self.xm + self.vector[0]*self.rad y1 =", "# functions. They get called with the # current value", "USA ## ## (C) Copyrights Dr. <NAME> and TSRI 2016", "1 \"\"\" assert cont in [None, 0, 1],\\ \"Illegal value", "(3,5,7,9,.....) To still be able to set the value, disregarding", "and val != 2: print \"Illegal value. Must be 0,", "set to 1 to call callbacks at # each value", "well as the min and max values that are allowed.", "parameters can be set after the widget has been created.", "text='') if val == 1: # show always widget labels", "must be > 0, got %s\"%size self.size = size def", "setMin(self, min): if min is not None: assert type(min) in", ") if type(Type) == type(\"\"): # type str assert Type", "toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel, 'optionsForm'):", "key == 'minus': key = '-' elif key == 'plus':", "dval: dval = dval + offset - self.increment else: dval", "elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif", "col2 = 'black' else: col1 = 'black' col2 = '#DDDDDD'", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): # max", "and dval > self.max: dval = self.max # recompute vector", "in kw.items(): # the 'set' parameter callbacks if key=='labCfg': self.setLabel(value)", "None and val < self.min: val = self.min if self.max", "'lock' entries callbacks elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif", "self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max else: self.max =", "implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR", "offset - self.increment else: dval = dval + offset if", "of vector prod. oldv = self.vector normz = oldv[0]*v[1] -", "if max is not None: assert type(max) in [types.IntType, types.FloatType],\\", "self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name == 'nt': #sys.platform", "fg='gray0') self.maxOld = self.max else: self.max = None if hasattr(self.opPanel,", "self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if n == 0.0: v =", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): # max checkbutton if", "width self.arrowBorderwidth = max(1, self.arrowWidth/2) # width of arrow #", "full turn can be specified as well as the min", "= self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0: label = 'never' elif", "**kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks = CallbackManager() # object to", "'black' else: col1 = 'black' col2 = '#DDDDDD' apply( canvas.coords,", "w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert type(oneTurn) in", "arc color of used portion self.unusedArcColor = '#cccccc' # filled", "= None # option panel widget self.oneTurn = 360. #", "compute angle increment compared to current vector ang = math.acos(ma)", "self.type(max) if self.showLabel == 1: self.printLabel() if self.value > self.max:", "To still be able to set the value, disregarding the", "By defaults these are set to None meaning that there", "is distributed in the hope that it will be useful,", "= dval + offset - self.increment else: dval = dval", "if mode != 0: mode = 1 self.lockType = mode", "got %s\"%cont if cont != 1: cont = None self.continuous", "= val #update arrow in display self.drawArrow() newVal = self.get()", "self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown)", "import math import types import sys import os from mglutil.util.callback", "= self.value #update arrow in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if", "pop this up in a window maybe import traceback traceback.print_stack()", "key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement':", "mode): if mode != 0: mode = 1 self.lockValue =", "can be 0, 1 or 2 0: no label 1:", "always shown 2: show label only when value changes\"\"\" assert", "'never' elif self.showLabel == 1: label = 'always' elif self.showLabel", "################################################################################ ## ## This library is free software; you can", "+ offset - self.increment else: dval = dval + offset", "self.lockBMax = lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel", "descriptor. Expected 'int' or 'float', got '%s'\"%Type self.type = eval(Type)", "this up in a window maybe import traceback traceback.print_stack() traceback.print_exc()", "size/2+2 self.rad = size/2 self.radNoArrow = self.rad-self.arrowLength self.vector = [0,", "if __name__ == '__main__': def foo(val): print val d =", "key=='type': self.setType(value) elif key=='min': self.setMin(value) elif key=='max': self.setMax(value) elif key=='increment':", "prod. oldv = self.vector normz = oldv[0]*v[1] - oldv[1]*v[0] if", "= event.num if lEventNum == 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def", "or %s, got %s\"%( type(0), type(0.0), type(min) ) if self.max", "is for example the case if the dial # is", "the implied warranty of ## MERCHANTABILITY or FITNESS FOR A", "if val < dval: dval = dval + offset -", "+ offset if self.min is not None and dval <", "Date: Mai 2001 Authors: <NAME>, <NAME> # # <EMAIL> #", "size/2 self.radNoArrow = self.rad-self.arrowLength self.vector = [0, 1] x1 =", "widget tried to adjust automatically the size of the arrow", "optionsPanel import OptionsPanel from KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry):", "mode, i.e. no step-wise increment if self.min is not None", "key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value) elif key=='min': self.setMin(value) elif key=='max':", "and val != 1 and val != 2: print \"Illegal", "canvas.coords, (self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId,", "self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value)", "vector and angle corresponding to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if", "if mode != 0: mode = 1 self.lockIncrement = mode", "allowed. By defaults these are set to None meaning that", "or key=='period' or key=='minus' or key=='plus': if key == 'period':", "else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel =", "any later version. ## ## This library is distributed in", "self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value)", "def lockContinuousCB(self, mode): if mode != 0: mode = 1", "Tkinter.Pack.config(self) self.callbacks = CallbackManager() # object to manage callback #", "3*aS) # arrow head length self.arrowWidth = max(2, aS) #", "elif self.max is not None and val > self.max: val", "widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if val ==", "and max values that are allowed. By defaults these are", "using the method set(), the actual value will 'snap' to", "ValueError: # fixme we would like to pop this up", "not None and dval > self.max: dval = self.max #", "case if the dial # is set to continuous=0, but", "this library; if not, write to the Free Software ##", "'side' in self.labCfg.keys(): self.labCfg['side'] = 'left' if not self.lab: self.lab", "of arrow # shadow lines self.arrowHeadWidth = 2*self.arrowWidth # width", "oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0,", "1 self.lockMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self,", "filled arc color of used portion self.unusedArcColor = '#cccccc' #", "is not None and val < self.min: val = self.min", "self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if mode != 0: mode =", "= lockValue self.lockType = lockType self.lockContinuous = lockContinuous self.lockOneTurn =", "show widget labels only when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='')", "w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show", "justify='center', text='', font = self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor,", "cont): \"\"\" cont can be None, 0 or 1 \"\"\"", "= event.x self.lasty = event.y def mouseUp(self, event): # call", "import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements a Dial", "to current vector ang = math.acos(ma) # find the sign", "None or text=='': return d={} for k, w in self.labCfg.items():", "## ## This library is free software; you can redistribute", "mode): # max entry field if mode != 0: mode", "key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif key=='showLabel':", "if mode != 0: mode = 1 self.lockBIncrement = mode", "increment self.size = 50 # defines widget size self.offsetValue =", "None: return # end point x1 = self.xm + self.vector[0]*self.rad", "= math.pi/360. self.lockMin = lockMin # lock<X> vars are used", "setValue does NOT call a callback! if self.min is not", "canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='', font = self.labelFont) self.labelId =", "val < 1: val = 1 self.precision = val if", "to manage callback # functions. They get called with the", "self.oldValue = self.value #update arrow in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn", "the various gui components of the options panel. Usage: <instance>.lock(<component>=<value>)", "to the Free Software ## Foundation, Inc., 51 Franklin Street,", "type int and greater than 0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal", "mode = 1 self.lockMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "defaults these are set to None meaning that there is", "x1 = self.xm + self.vector[0]*self.rad y1 = self.ym + self.vector[1]*self.rad", "actually result in 7 (3,5,7,9,.....) To still be able to", "self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle = self.angle -", "0. self.incrementOld = increment self.size = 50 # defines widget", "added to this new <value> \"\"\" def __init__(self, master=None, type='float',", "self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): # max entry field if mode", "val = 1 self.precision = val if self.type == float:", "label if self.canvas and self.showLabel == 1: self.printLabel() def setContinuous(self,", "label = 'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn):", "mode): if mode != 0: mode = 1 self.lockOneTurn =", "y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas =", "if val == 0: # no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2,", "if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay()", "types.ListType,\\ \"Illegal callback: must be either None or callable, or", "event): # remember where the mouse went down self.lastx =", "if cont != 1: cont = None self.continuous = cont", "('int','float'),\\ \"Illegal type descriptor. Expected 'int' or 'float', got '%s'\"%Type", ") self.increment = self.type(incr) self.offsetValue = self.value self.incrementOld = self.increment", "# the 'lock' entries callbacks elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin':", "# max checkbutton if mode != 0: mode = 1", "color of used portion self.unusedArcColor = '#cccccc' # filled arc", "The increment will now be added to this new <value>", "self.value = 0.0 # current value of widget self.oldValue =", "assure no rounding errors if ma > 1.0: ma =", "title=\"Dial Options\") # pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel)", "self.min = self.type(min) if self.showLabel == 1: self.printLabel() if self.value", "# configure with user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision)", "set the value to <value>. The increment will now be", "are used in self.lock() self.lockMax = lockMax # to lock/unlock", "= canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor)", "type(1.0), type(val) ) # setValue does NOT call a callback!", "= cont if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if cont:", "'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min else: self.min", "type str assert Type in ('int','float'),\\ \"Illegal type descriptor. Expected", "!= 0: mode = 1 self.lockBIncrement = mode if hasattr(self.opPanel,", "width=size+2, height=size+2) self.xm = self.ym = size/2+2 self.rad = size/2", "1 self.lockBIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self,", "= self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() # and update the", "set to 3, and the increment is set to 2,", "def setMax(self, max): if max is not None: assert type(max)", "normz>0: ang = -1. * ang # compute the new", "self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='', font = self.labelFont)", "enabled: if using the method set(), the actual value will", "if mode != 0: mode = 1 self.lockMin = mode", "self.labelFont = ( ensureFontCase('helvetica'), 14, 'bold') # label font self.labelColor", "called when the mouse button is released. They always get", "constructor. a lock() method is used to disable the various", "got '%s'\"%Type self.type = eval(Type) else: self.type = Type if", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max", "self.set(self.type(valueString)) except ValueError: # fixme we would like to pop", "lock() method is used to disable the various gui components", "## if self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try: self.set(self.type(valueString))", "self.ym+2, fill='black', justify='center', text='', font = self.labelFont) self.labelId = canvas.create_text(self.xm,", "self.showLabel = val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget']", "elif self.showLabel == 1: label = 'always' elif self.showLabel ==", "# on button release event self.angle = 0. # angle", "## License as published by the Free Software Foundation; either", "is set to 1, else they get called when the", "col2 = '#DDDDDD' apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) ) apply(", "event.y def mouseWheel(self, event): #print \"mouseWheel\", event, event.num if os.name", "key = event.keysym if key.isdigit() or key=='period' or key=='minus' or", "self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") #", "event.x self.lasty = event.y def mouseUp(self, event): # call callbacks", "angle corresponding to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0:", "'text':None}, min=None, max=None, increment=.0, precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50,", "lEventNum = 4 else: lEventNum = 5 else: lEventNum =", "self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert type(oneTurn) in [types.IntType, types.FloatType],\\", "values self.precision = 2 # decimal places self.min = None", "try: self.set(self.type(valueString)) except ValueError: # fixme we would like to", "self.canvas is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self,", "Copyrights Dr. <NAME> and TSRI 2016 ## ################################################################################ ######################################################################### #", "def lockTypeCB(self, mode): if mode != 0: mode = 1", "self.xm + self.vector[0]*self.rad y1 = self.ym - self.vector[1]*self.rad # point", "mode != 0: mode = 1 self.lockIncrement = mode if", "self.increment is not None and self.increment != 0. and not", "range corresponding to one full turn can be specified as", "size of the dial. The widget has a configure() method:", "self.arrowLength = max(3, 3*aS) # arrow head length self.arrowWidth =", "if self.showLabel == 2: # no widget labels on mouse", "self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max else: self.max = None", "self.vector[1]*self.radNoArrow # vector orthogonal to arrow n = [-self.vector[1], -self.vector[0]]", "# find the sign of the rotation, sign of z", "color self.canvas = None # the canvas to create the", "type(max) in [types.IntType, types.FloatType],\\ \"Illegal type for maximum. Expected type", "labCfg.get('text', None) if text is None or text=='': return d={}", "self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if mode != 0: mode =", "= canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line(", "(self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply( canvas.coords,", "oldv = self.vector normz = oldv[0]*v[1] - oldv[1]*v[0] if normz>0:", "%s\"%( type(0), type(0.0), type(max) ) if self.min and max <", "type(min) ) if self.max and min > self.max: min =", "def setContinuous(self, cont): \"\"\" cont can be None, 0 or", "%s\"%cont if cont != 1: cont = None self.continuous =", "CallbackManager() # object to manage callback # functions. They get", "Mai 2001 Authors: <NAME>, <NAME> # # <EMAIL> # <EMAIL>", "step-wise increment if self.min is not None and val <", "NOT call a callback! if self.min is not None and", "self.max: val = self.max self.value = self.type(val) self.offsetValue=self.value self.oldValue =", "elif key == 'plus': key = '+' self.typedValue += key", "mglutil.util.misc import ensureFontCase from optionsPanel import OptionsPanel from KeyboardEntry import", "2 0: no label 1: label is always shown 2:", "ang # compute the new value val = self.value +", "0 or 1, got %s\"%cont if cont != 1: cont", "can be passed only to the constructor. a lock() method", "2*self.arrowWidth # width of arrow head base def mouseDown(self, event):", "self.setArrow() # configure with user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type)", "self.lockIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode):", "type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for value: expected %s", "size of the arrow according to the size of the", "where the mouse went down self.lastx = event.x self.lasty =", "key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn':", "of the arrow according to the size of the dial.", "widget has been created. The widget tried to adjust automatically", "callable function. Callback is called every time the widget value", "self.toggleOptPanel) if os.name == 'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel)", "previous # hand position ma = v[0]*self.vector[0] + v[1]*self.vector[1] #", "0.0: v = [0.0, 0.0] else: v = [dx/n, dy/n]", "self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle = self.angle -", "self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym)", "CallbackManager from mglutil.util.misc import ensureFontCase from optionsPanel import OptionsPanel from", "else: self.callbacks.AddCallback(cb) self.callback = cb def toggleOptPanel(self, event=None): if self.opPanel.flag:", "in self.labCfg.items(): if k == 'side': continue else: d[k] =", "self.offsetValue = dval else: # 'regular' mode, i.e. no step-wise", "aS) # half the arrow body width self.arrowBorderwidth = max(1,", "The widget has a pointer that can be moved around", "has to be specified at instanciation. Other parameters can be", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min entry field if", "fill='black', width = self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width", "= self.min self.max = self.type(max) if self.showLabel == 1: self.printLabel()", "mode = 1 self.lockValue = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "got %s\"%( type(1), type(1.0), type(val) ) # setValue does NOT", "can be set after the widget has been created. The", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): # increment checkbutton if", "this mode the values will be restrained to be multiples", "self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas = self.canvas if self.vector[0] > 0.0:", "elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif", "value of widget self.oldValue = 0.0 # old value of", "self.labelColor = 'yellow' # label color self.canvas = None #", "\"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\" if hasattr(self.opPanel, 'optionsForm'): w =", "type %s or %s, got %s\"%( type(0), type(0.0), type(val) )", "to pop this up in a window maybe import traceback", "if self.min is not None and dval < self.min: dval", "(self.arrowPolId,) + tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1) )", "else: self.increment = self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled',", "yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2 = [ x1, y1, xb-n[0]*self.arrowHeadWidth,", "= 0. # used to store old values self.maxOld =", "self.min is not None and dval < self.min: dval =", "TSRI # ######################################################################### import Tkinter import math import types import", "copy of the GNU Lesser General Public ## License along", "<NAME> # # <EMAIL> # <EMAIL> # # Copyright: <NAME>,", "'side': continue else: d[k] = w if not 'side' in", "Expected type %s or %s, got %s\"%( type(0), type(0.0), type(min)", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ == '__main__': def", "new hand position and previous # hand position ma =", "the GNU Lesser General Public ## License along with this", "> 1.0: ma = 1.0 elif ma < -1.0: ma", "(at your option) any later version. ## ## This library", "self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas is None:", "mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val):", "int: self.labelFormat = \"%d\" self.int_value = self.value else: self.labelFormat =", "round(val/self.increment) * self.increment if val < dval: dval = dval", "various places self.threeSixtyOver1turn = 1 self.piOver1turn = math.pi/360. self.lockMin =", "canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def createCanvas(self,", "assert type(max) in [types.IntType, types.FloatType],\\ \"Illegal type for maximum. Expected", "configure(self, **kw): for key,value in kw.items(): # the 'set' parameter", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if mode !=", "options self.labelFont = ( ensureFontCase('helvetica'), 14, 'bold') # label font", "'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,),", "aS = self.size/40 self.arrowLength = max(3, 3*aS) # arrow head", "version. ## ## This library is distributed in the hope", "!= 0: mode = 1 self.lockContinuous = mode if hasattr(self.opPanel,", "self.min self.max = self.type(max) if self.showLabel == 1: self.printLabel() if", "< self.min: dval = self.min elif self.max is not None", "not None and val > self.max: val = self.max self.value", "position ma = v[0]*self.vector[0] + v[1]*self.vector[1] # assure no rounding", "get called at every value change if self.contiguous is set", "increment is set to 2, setting the value to 6", "+ self.vector[0]*self.rad y1 = self.ym + self.vector[1]*self.rad canvas = self.canvas", "set to None meaning that there is no min and", "0: mode = 1 self.lockBMin = mode if hasattr(self.opPanel, 'optionsForm'):", "self.vector[1]*self.rad canvas = self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId", "def setIncrement(self, incr): if incr is not None: assert type(incr)", "size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0,", "ma = -1.0 # compute angle increment compared to current", "PURPOSE. See the GNU ## Lesser General Public License for", "are allowed. By defaults these are set to None meaning", "Usage: <instance>.lock(<component>=<value>) components see configure(). value is 0 or 1.", "for value: expected %s or %s, got %s\"%( type(1), type(1.0),", "callback must be callable. Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback", "License as published by the Free Software Foundation; either ##", "%s\"%( type(0), type(0.0), type(oneTurn) ) self.oneTurn = oneTurn self.threeSixtyOver1turn =", "self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x self.lasty = event.y", "numbers only in widget keyboard entry label key = event.keysym", "self.set(self.value-self.oneTurn) def get(self): return self.type(self.value) def printLabel(self): if self.canvas is", "closest increment if self.increment is not None and self.increment !=", "canvas = self.canvas if self.vector[0] > 0.0: col1 = '#DDDDDD'", "self.type(incr) self.offsetValue = self.value self.incrementOld = self.increment if hasattr(self.opPanel, 'optionsForm'):", "## modify it under the terms of the GNU Lesser", "self.lockIncrement = lockIncrement self.lockBMin = lockBMin self.lockBMax = lockBMax self.lockBIncrement", "each value change, else gets called # on button release", "text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val): if type(val) == types.StringType:", "to display label on self.continuous = 1 # set to", "self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg = labCfg text = labCfg.get('text',", "size+2, self.ym) canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0,", "lockMax # to lock/unlock entries in optionpanel self.lockIncrement = lockIncrement", "val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle = self.angle", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if", "called # on button release event self.angle = 0. #", "mouseMove(self, event): dx = event.x-self.xm dy = self.ym-event.y n =", "not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2: # no widget", "key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type): assert type(Type) in [types.StringType, types.TypeType],\\", "option) any later version. ## ## This library is distributed", "the next increment. i.e., if the value is set to", "self.value = val self.offsetValue = val #update arrow in display", "mode = 1 self.lockIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "height=size+2) self.xm = self.ym = size/2+2 self.rad = size/2 self.radNoArrow", "== 'plus': key = '+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else:", "key,value in kw.items(): # the 'set' parameter callbacks if key=='labCfg':", "units by default. A dial can also operate in discrete", "mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event): dx", "moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val): if", "type for increment. Expected type %s or %s, got %s\"%(", "self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback = cb def toggleOptPanel(self, event=None): if", "val = 10 if val < 1: val = 1", "= lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel = lockShowLabel self.lockValue =", "self.canvas and self.showLabel == 1: self.printLabel() def setContinuous(self, cont): \"\"\"", "between new hand position and previous # hand position ma", "The widget has a configure() method: type, min, max, increment,", "field if mode != 0: mode = 1 self.lockMax =", "else they get called when the mouse button is released.", "self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi = oneTurn / (2*math.pi) if self.opPanel:", "lockBIncrementCB(self, mode): # increment checkbutton if mode != 0: mode", "#sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel)", "+ tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure(", "kw.items(): # the 'set' parameter callbacks if key=='labCfg': self.setLabel(value) elif", "val > 10: val = 10 if val < 1:", "self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event): dx = event.x-self.xm dy =", "type %s or %s, got %s\"%( type(0), type(0.0), type(max) )", "assert type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal type for oneTurn. Expected", "type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal type for oneTurn. Expected %s", "is no min and no max. One turn corresponds to", "= Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm = self.ym = size/2+2 self.rad", "self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel == 1:", "!= 0: mode = 1 self.lockMax = mode if hasattr(self.opPanel,", "increment self.minOld = 0. # used to store old values", "2.1 of the License, or (at your option) any later", "of the dial has to be specified at instanciation. Other", "self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try: self.set(self.type(valueString)) except ValueError: # fixme", "< -1.0: ma = -1.0 # compute angle increment compared", "to be specified at instanciation. Other parameters can be set", "self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld", "set increment correctly self.lab = None # label self.callback =", "val self.offsetValue = val #update arrow in display self.drawArrow() newVal", "or text=='': return d={} for k, w in self.labCfg.items(): if", "'.' elif key == 'minus': key = '-' elif key", "self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = val self.offsetValue =", "= self.ym = size/2+2 self.rad = size/2 self.radNoArrow = self.rad-self.arrowLength", "mode = 1 self.lockBIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "self.type == 'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() # and update", "options panel. Usage: <instance>.lock(<component>=<value>) components see configure(). value is 0", "if key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value) elif key=='min': self.setMin(value) elif", "xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas = self.canvas if self.vector[0]", "## but WITHOUT ANY WARRANTY; without even the implied warranty", "# current value as an argument # initialize various attributes", "can also operate in discrete mode (if self.increment is set", "time the widget value is set/modified\"\"\" assert cb is None", "= self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay()", "%s\"%(type(1), type(size) ) assert size > 0, \"Illegal size: must", "canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm, 2,", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if mode", "dy/n] # find the cosine of the angle between new", "keyboard entry label key = event.keysym if key.isdigit() or key=='period'", "def printLabel(self): if self.canvas is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId,", "- 360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value", "self.continuous = cont if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if", "expected %s or %s, got %s\"%( type(1), type(1.0), type(val) )", "dy = self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if n == 0.0:", "= canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='', font = self.labelFont) self.labelId", "val = float(val) assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type", "360. # value increment for 1 full turn self.value =", "= self.max self.min = self.type(min) if self.showLabel == 1: self.printLabel()", "self.min: dval = self.min elif self.max is not None and", "# vector orthogonal to arrow n = [-self.vector[1], -self.vector[0]] pts1", "mode = 1 self.lockMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "mode != 0: mode = 1 self.lockValue = mode if", "self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type):", "key = '-' elif key == 'plus': key = '+'", "if text is None or text=='': return d={} for k,", "option panel widget self.oneTurn = 360. # value increment for", "no widget labels on mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='')", "dval = dval + offset - self.increment else: dval =", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ == '__main__': def foo(val): print", "assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for precision. Expected", "self.canvas and self.showLabel == 1: self.printLabel() def setMin(self, min): if", "Public License for more details. ## ## You should have", "= OptionsPanel(master = self, title=\"Dial Options\") # pack em up", "'nt': #sys.platform == 'win32': if event.delta > 0: lEventNum =", "text='') self.canvas.itemconfigure(self.labelId, text='') if val == 1: # show always", "showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0,", "self.lockType = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode):", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): # max entry field", "if mode != 0: mode = 1 self.lockContinuous = mode", "half the arrow body width self.arrowBorderwidth = max(1, self.arrowWidth/2) #", "if type(Type) == type(\"\"): # type str assert Type in", "= None # minimum value self.max = None # maximum", "callbacks at # each value change, else gets called #", "self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type): assert type(Type) in", "self.labCfg = labCfg text = labCfg.get('text', None) if text is", "orthogonal to arrow n = [-self.vector[1], -self.vector[0]] pts1 = [", "dial has to be specified at instanciation. Other parameters can", "self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event): dx = event.x-self.xm", "self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2)", "configuration. This is for example the case if the dial", "def setLabel(self, labCfg): self.labCfg = labCfg text = labCfg.get('text', None)", "%s, got %s\"%(type(1), type(size) ) assert size > 0, \"Illegal", "elif key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) # the 'lock' entries", "arc color of unused portion self.pyOver180 = math.pi/180.0 # constants", "circle. The range corresponding to one full turn can be", "self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if val == 0: # no", "Type): assert type(Type) in [types.StringType, types.TypeType],\\ \"Illegal type for datatype.", "mode = 1 self.lockShowLabel = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "set/modified\"\"\" assert cb is None or callable(cb) or type(cb) is", "> 10: val = 10 if val < 1: val", "They always get called with the current value as an", "way. master, labCfg and size can be passed only to", "no step-wise increment if self.min is not None and val", "canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0,", "Free Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor,", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): # increment", "they get called when the mouse button is released. They", "def toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel,", "be None, 0 or 1 \"\"\" assert cont in [None,", "the hope that it will be useful, ## but WITHOUT", "'minus': key = '-' elif key == 'plus': key =", "got %s\"%( type(0), type(0.0), type(val) ) val = int(val) if", "vector ang = math.acos(ma) # find the sign of the", "self.ym, size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1", "w.setvalue('int') elif self.type == 'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() #", "0: mode = 1 self.lockBMax = mode if hasattr(self.opPanel, 'optionsForm'):", "type(max) ) if self.min and max < self.min: max =", "has been created. The widget tried to adjust automatically the", "print \"Illegal value. Must be 0, 1 or 2\" return", "or %s, got %s\"%( type(1), type(1.0), type(val) ) # setValue", "dval = dval + offset if self.min is not None", "val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle = self.angle", "0.0-self.angle) def createCanvas(self, master): size = self.size self.frame = Tkinter.Frame(self,", "type(size) ) assert size > 0, \"Illegal size: must be", "== float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\" if", "increment will now be added to this new <value> \"\"\"", "= self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size,", "= self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x self.lasty =", "it will be useful, ## but WITHOUT ANY WARRANTY; without", "an argument # initialize various attributes with default values self.precision", "self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if size is not None: self.setSize(size)", "= [-self.vector[1], -self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth,", "[math.sin(a), math.cos(a)] self.value = dval self.offsetValue = dval else: #", "self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max): if max is not None:", "x). In this mode the values will be restrained to", "'#aaaaaa' # filled arc color of used portion self.unusedArcColor =", "with user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min)", "1: self.printLabel() def setContinuous(self, cont): \"\"\" cont can be None,", "label = 'always' elif self.showLabel == 2: label = 'move'", "dial # is set to continuous=0, but the value is", "Options\") # pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def", "= lockPrecision self.lockShowLabel = lockShowLabel self.lockValue = lockValue self.lockType =", "%s\"%val if val != 0 and val != 1 and", "if the dial # is set to continuous=0, but the", "# <EMAIL> # <EMAIL> # # Copyright: <NAME>, <NAME> and", "warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.", "point at arrow head base xb = self.xm + self.vector[0]*self.radNoArrow", "== 'win32': if event.delta > 0: lEventNum = 4 else:", "with the # current value as an argument # initialize", "[math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel == 1: self.printLabel() if self.opPanel:", "multiples of self.increment. The Widget has a Callback manager. Callback", "lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks = CallbackManager() #", "# snap to closest increment if self.increment is not None", "self.max: dval = self.max # recompute vector and angle corresponding", "continue else: d[k] = w if not 'side' in self.labCfg.keys():", "assert Type in ('int','float'),\\ \"Illegal type descriptor. Expected 'int' or", "self.lockBMin = lockBMin self.lockBMax = lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision", "at instanciation. Other parameters can be set after the widget", "be 0, 1 or 2\" return self.showLabel = val self.toggleWidgetLabel(val)", "0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal size: expected type %s, got", "= size/2 self.radNoArrow = self.rad-self.arrowLength self.vector = [0, 1] x1", "self.lockPrecision = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode):", "## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA", "Expected type %s or %s, got %s\"%( type(0), type(0.0), type(incr)", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min entry field", "is types.ListType,\\ \"Illegal callback: must be either None or callable,", "self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment", "title=\"Dial Options\") ## if self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString):", "# type str assert Type in ('int','float'),\\ \"Illegal type descriptor.", "precision. Expected type %s or %s, got %s\"%( type(0), type(0.0),", "field if mode != 0: mode = 1 self.lockIncrement =", "increment, precision, showLabel, value, continuous, oneTurn can be set this", "= 'yellow' # label color self.canvas = None # the", "== 1: self.printLabel() def setContinuous(self, cont): \"\"\" cont can be", "be multiples of self.increment. The Widget has a Callback manager.", "'int' or 'float', got '%s'\"%Type self.type = eval(Type) else: self.type", "the 'lock' entries callbacks elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value)", "display self.drawArrow() newVal = self.get() if self.continuous or force: if", "= \"%d\" self.int_value = self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if", "self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value)", "= self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int: w.setvalue('int') elif self.type ==", "self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name ==", "(canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") ##", "widget. The size of the dial has to be specified", "mode): # increment checkbutton if mode != 0: mode =", "change if self.contiguous is set to 1, else they get", "will be restrained to be multiples of self.increment. The Widget", "handleKeyStroke(self, event): # handle key strokes for numbers only in", "and self.oldValue != newVal or force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal)", "w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() # and update the printed label", "v = [dx/n, dy/n] # find the cosine of the", "traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event): # handle key strokes", "= self.min if self.max is not None and val >", "increment if self.increment is not None and self.increment != 0.", "math.pi/180.0 # constants used in various places self.threeSixtyOver1turn = 1", "val < dval: dval = dval + offset - self.increment", "mode): #min entry field if mode != 0: mode =", "0: mode = 1 self.lockMin = mode if hasattr(self.opPanel, 'optionsForm'):", "self.value = dval self.offsetValue = dval else: # 'regular' mode,", "if not self.lab: self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel)", "showLabel. Expected 0, 1 or 2, got %s\"%val if val", "= 'never' elif self.showLabel == 1: label = 'always' elif", "1 self.lockMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self,", "self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min else: self.min = None", "1 # set to 1 to call callbacks at #", "[ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ]", "printed label if self.canvas and self.showLabel == 1: self.printLabel() def", "Must be 0, 1 or 2\" return self.showLabel = val", "self.lockValue = lockValue self.lockType = lockType self.lockContinuous = lockContinuous self.lockOneTurn", "set(self, val, update=1, force=0): # if force is set to", "understands the optional keyword force=True, i.e. dial.set(<value>, force=True)), which will", "= self.type(val) self.offsetValue=self.value self.oldValue = self.value #update arrow in display", "pointer that can be moved around a circle. The range", "key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision':", "which will set the value to <value>. The increment will", "%s, got %s\"%( type('a'), type(type), type(Type) ) if type(Type) ==", "widget in self.usedArcColor = '#aaaaaa' # filled arc color of", "assert isinstance(size, types.IntType),\\ \"Illegal size: expected type %s, got %s\"%(type(1),", "KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements a Dial widget.", "== type(\"\"): # type str assert Type in ('int','float'),\\ \"Illegal", "\"Illegal type descriptor. Expected 'int' or 'float', got '%s'\"%Type self.type", "10: val = 10 if val < 1: val =", "class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements a Dial widget. The", "self.type = Type if self.type == int: self.labelFormat = \"%d\"", "the printed label if self.canvas and self.showLabel == 1: self.printLabel()", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): # max checkbutton", "in self.lock() self.lockMax = lockMax # to lock/unlock entries in", "> 0, got %s\"%size self.size = size def setCallback(self, cb):", "labCfg): self.labCfg = labCfg text = labCfg.get('text', None) if text", "of the angle between new hand position and previous #", "default values self.precision = 2 # decimal places self.min =", "oneTurn can be set this way. master, labCfg and size", "# object to manage callback # functions. They get called", "oneTurn. Expected %s or %s, got %s\"%( type(0), type(0.0), type(oneTurn)", "= self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master = self, title=\"Dial Options\")", "self.set(val) self.lastx = event.x self.lasty = event.y def mouseWheel(self, event):", "'plus': key = '+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self,", "not self.lab: self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else:", "1 self.lockPrecision = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self,", "maybe import traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event): # handle", "canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1)", "[ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ]", "(if self.increment is set to x). In this mode the", "+ ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x self.lasty = event.y def", "in 7 (3,5,7,9,.....) To still be able to set the", "components see configure(). value is 0 or 1. 1 disables,", "k, w in self.labCfg.items(): if k == 'side': continue else:", "02110-1301 USA ## ## (C) Copyrights Dr. <NAME> and TSRI", "is set to 2, setting the value to 6 will", "precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0,", "1 self.lockIncrement = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self,", "[0,1,2],\\ \"Illegal value for showLabel. Expected 0, 1 or 2,", "%s\"%( type(0), type(0.0), type(min) ) if self.max and min >", "xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas = self.canvas", "<NAME>, <NAME> and TSRI # ######################################################################### import Tkinter import math", "canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name", "* ang # compute the new value val = self.value", "= 1 self.piOver1turn = math.pi/360. self.lockMin = lockMin # lock<X>", "continuous: expected None, 0 or 1, got %s\"%cont if cont", "= size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black',", "for more details. ## ## You should have received a", "called with the current value as an argument. An optional", "if cb is None: return elif type(cb) is types.ListType: for", "self.contiguous is set to 1, else they get called when", "version 2.1 of the License, or (at your option) any", "canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def createCanvas(self, master): size = self.size", "Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### # the", "self.oldValue = 0.0 # old value of widget self.showLabel =", "changes\"\"\" assert val in [0,1,2],\\ \"Illegal value for showLabel. Expected", "the widget value is set/modified\"\"\" assert cb is None or", "'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() # and update the printed", "lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self)", "0. and not force: offset = self.offsetValue%self.increment dval = round(val/self.increment)", "self.printLabel() if self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if", "labCfg text = labCfg.get('text', None) if text is None or", "5 else: lEventNum = event.num if lEventNum == 4: self.set(self.value+self.oneTurn)", "the mouse button is released. They always get called with", "in various places self.threeSixtyOver1turn = 1 self.piOver1turn = math.pi/360. self.lockMin", "val < self.min: val = self.min if self.max is not", "be > 0, got %s\"%size self.size = size def setCallback(self,", "got %s\"%( type(0), type(0.0), type(incr) ) self.increment = self.type(incr) self.offsetValue", "# # Date: Mai 2001 Authors: <NAME>, <NAME> # #", "= 'black' else: col1 = 'black' col2 = '#DDDDDD' apply(", "GNU ## Lesser General Public License for more details. ##", "= canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0,", "type(1), type(1.0), type(val) ) # setValue does NOT call a", "panel # snap to closest increment if self.increment is not", "is types.ListType: for func in cb: assert callable(func), \"Illegal callback", "val): \"\"\"Show label can be 0, 1 or 2 0:", "float(val) assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for value:", "in self.usedArcColor = '#aaaaaa' # filled arc color of used", "2: label = 'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self,", "key strokes for numbers only in widget keyboard entry label", "1 self.lockBMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self,", "self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2: # no widget labels on", "type(\"\"): # type str assert Type in ('int','float'),\\ \"Illegal type", "type(val) ) val = int(val) if val > 10: val", "sign of z component of vector prod. oldv = self.vector", "types.FloatType],\\ \"Illegal type for increment. Expected type %s or %s,", "= self.size self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame,", "on to display label on self.continuous = 1 # set", "in [types.StringType, types.TypeType],\\ \"Illegal type for datatype. Expected %s or", "old values self.maxOld = 0. self.incrementOld = increment self.size =", "0: # no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='')", "the # current value as an argument # initialize various", "end point x1 = self.xm + self.vector[0]*self.rad y1 = self.ym", "and/or ## modify it under the terms of the GNU", "and val < self.min: val = self.min elif self.max is", "start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm, 2, self.ym,", "to the constructor. a lock() method is used to disable", "got %s\"%( type(0), type(0.0), type(max) ) if self.min and max", "str assert Type in ('int','float'),\\ \"Illegal type descriptor. Expected 'int'", "None and val > self.max: val = self.max # recompute", "elif self.max is not None and dval > self.max: dval", "list. Got %s\"%cb if cb is None: return elif type(cb)", "self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val): if type(val) ==", "redistribute it and/or ## modify it under the terms of", "val = self.max self.value = self.type(val) self.offsetValue=self.value self.oldValue = self.value", "Dial widget. The widget has a pointer that can be", "One turn corresponds to 360 units by default. A dial", "text='', font = self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master = self,", "6 will actually result in 7 (3,5,7,9,.....) To still be", "'regular' mode, i.e. no step-wise increment if self.min is not", "def drawArrow(self): if self.canvas is None: return # end point", "if self.canvas and self.showLabel == 1: self.printLabel() def setMin(self, min):", "font = self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master = self, title=\"Dial", "self.get() if self.continuous or force: if update and self.oldValue !=", "see configure(). value is 0 or 1. 1 disables, 0", "ma = v[0]*self.vector[0] + v[1]*self.vector[1] # assure no rounding errors", "label = 'never' elif self.showLabel == 1: label = 'always'", "if key == 'period': key = '.' elif key ==", "!= 0: mode = 1 self.lockPrecision = mode if hasattr(self.opPanel,", "'lock' methods: ##################################################################### def lockTypeCB(self, mode): if mode != 0:", "tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1,", "def setOneTurn(self, oneTurn): assert type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal type", "lEventNum == 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self): return self.type(self.value)", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment = self.type(0)", "1: self.printLabel() def setMin(self, min): if min is not None:", "constants used in various places self.threeSixtyOver1turn = 1 self.piOver1turn =", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if", "== 1: self.printLabel() if self.value > self.max: self.set(self.max) if hasattr(self.opPanel,", "%s\"%( type('a'), type(type), type(Type) ) if type(Type) == type(\"\"): #", "size self.offsetValue = 0. # used to set increment correctly", "self.value = self.type(val) self.offsetValue=self.value self.oldValue = self.value #update arrow in", "= self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel)", "types import sys import os from mglutil.util.callback import CallbackManager from", "min and no max. One turn corresponds to 360 units", "handle key strokes for numbers only in widget keyboard entry", "= -1.0 # compute angle increment compared to current vector", "2, got %s\"%val if val != 0 and val !=", ") canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def createCanvas(self, master): size =", "return self.showLabel = val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w =", "= 'left' if not self.lab: self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side'])", "= self.angle - 360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a),", "0, \"Illegal size: must be > 0, got %s\"%size self.size", "specified callback self.opPanel = None # option panel widget self.oneTurn", "Size must be of type int and greater than 0\"\"\"", "and self.showLabel == 1: self.printLabel() def setMin(self, min): if min", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): #", "def mouseUp(self, event): # call callbacks if not in continuous", "= v[0]*self.vector[0] + v[1]*self.vector[1] # assure no rounding errors if", "ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY", "if mode != 0: mode = 1 self.lockValue = mode", "self.type == int: self.labelFormat = \"%d\" self.int_value = self.value else:", "[-self.vector[1], -self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth,", "or 1, got %s\"%cont if cont != 1: cont =", "self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val): assert type(val) in [types.IntType, types.FloatType],\\", "window maybe import traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event): #", "off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r,", "= canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm,", "and angle corresponding to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val", "self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") # pack em", "mouse button is released. They always get called with the", "current value as an argument. An optional label can be", "self.piOver1turn = math.pi/360. self.lockMin = lockMin # lock<X> vars are", "normz = oldv[0]*v[1] - oldv[1]*v[0] if normz>0: ang = -1.", "self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value)", "set to 2, setting the value to 6 will actually", "None, 0 or 1, got %s\"%cont if cont != 1:", "= lockType self.lockContinuous = lockContinuous self.lockOneTurn = lockOneTurn self.setArrow() #", "# increment checkbutton if mode != 0: mode = 1", "self.ym, size+2, self.ym) canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId = canvas.create_polygon(", "type %s or %s, got %s\"%( type(0), type(0.0), type(incr) )", "arrow n = [-self.vector[1], -self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth,", "= lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel =", "Other parameters can be set after the widget has been", "= 1 self.lockBMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "mode != 0: mode = 1 self.lockBIncrement = mode if", "lines self.arrowHeadWidth = 2*self.arrowWidth # width of arrow head base", "self.printLabel() else: if self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel() if self.opPanel:", "be specified as well as the min and max values", "toggleWidgetLabel(self, val): if val == 0: # no widget labels", "## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try: self.set(self.type(valueString)) except ValueError: #", "1.0: ma = 1.0 elif ma < -1.0: ma =", "None # option panel widget self.oneTurn = 360. # value", "display label on self.continuous = 1 # set to 1", "fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='', font", "can be displayed at the center of the Dial widget.", "event) def setSize(self, size): \"\"\"Set widget size. Size must be", "2: print \"Illegal value. Must be 0, 1 or 2\"", "self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if", "or 2, got %s\"%val if val != 0 and val", "= '#DDDDDD' col2 = 'black' else: col1 = 'black' col2", "lEventNum = 5 else: lEventNum = event.num if lEventNum ==", "for continuous: expected None, 0 or 1, got %s\"%cont if", "increment enabled: if using the method set(), the actual value", "for 1 full turn self.value = 0.0 # current value", "text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val, update=1, force=0): # if", "self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90.,", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): # increment entry field", "has a Callback manager. Callback functions get called at every", "FOR A PARTICULAR PURPOSE. See the GNU ## Lesser General", "self.labCfg.items(): if k == 'side': continue else: d[k] = w", "isinstance(size, types.IntType),\\ \"Illegal size: expected type %s, got %s\"%(type(1), type(size)", "event, event.num if os.name == 'nt': #sys.platform == 'win32': if", "incr): if incr is not None: assert type(incr) in [types.IntType,", "these are set to None meaning that there is no", "self.unusedArcColor = '#cccccc' # filled arc color of unused portion", "self.maxOld = 0. self.incrementOld = increment self.size = 50 #", "checkbutton if mode != 0: mode = 1 self.lockBMax =", "mode != 0: mode = 1 self.lockContinuous = mode if", "event.delta > 0: lEventNum = 4 else: lEventNum = 5", "self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() # and update the printed", "checkbutton if mode != 0: mode = 1 self.lockBMin =", "\"Illegal type for maximum. Expected type %s or %s, got", "also operate in discrete mode (if self.increment is set to", "text=='': return d={} for k, w in self.labCfg.items(): if k", "types.FloatType],\\ \"Illegal type for minimum. Expected type %s or %s,", "not force: offset = self.offsetValue%self.increment dval = round(val/self.increment) * self.increment", "0: mode = 1 self.lockShowLabel = mode if hasattr(self.opPanel, 'optionsForm'):", "is None: return elif type(cb) is types.ListType: for func in", "self.min else: self.min = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled',", "!= 2: print \"Illegal value. Must be 0, 1 or", "self.angle = self.angle - 360.0 a = self.angle*self.pyOver180 self.vector =", ") val = int(val) if val > 10: val =", "OptionsPanel(master = self, title=\"Dial Options\") # pack em up self.canvas.pack(side=Tkinter.TOP)", "2: # show widget labels only when mouse moves self.showLabel=2", "class implements a Dial widget. The widget has a pointer", "used to store old values self.maxOld = 0. self.incrementOld =", "mode != 0: mode = 1 self.lockBMin = mode if", "is set to 1, we call this method regardless of", "self.labCfg['side'] = 'left' if not self.lab: self.lab = Tkinter.Label(self, d)", "type(min) in [types.IntType, types.FloatType],\\ \"Illegal type for minimum. Expected type", "lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0,", "from KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements", "be restrained to be multiples of self.increment. The Widget has", "= 1 # set to 1 to call callbacks at", "get called with the current value as an argument. An", "self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove)", "self.max # recompute vector and angle corresponding to val self.angle", "= self.ym + self.vector[1]*self.rad canvas = self.canvas self.circleId = canvas.create_oval(2,2,size,size,", "force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else: if", "# decimal places self.min = None # minimum value self.max", "the constructor. a lock() method is used to disable the", "PARTICULAR PURPOSE. See the GNU ## Lesser General Public License", "entries in optionpanel self.lockIncrement = lockIncrement self.lockBMin = lockBMin self.lockBMax", "elif key=='oneTurn': self.setOneTurn(value) # the 'lock' entries callbacks elif key=='lockType':", "elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type): assert", "filled arc color of unused portion self.pyOver180 = math.pi/180.0 #", "2, setting the value to 6 will actually result in", "or %s, got %s\"%( type(0), type(0.0), type(oneTurn) ) self.oneTurn =", "else: v = [dx/n, dy/n] # find the cosine of", "various attributes with default values self.precision = 2 # decimal", "text='', font = self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center',", ") self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth) self.arrowPolborder2", "set this way. master, labCfg and size can be passed", "%s or %s, got %s\"%( type(1), type(1.0), type(val) ) #", "self, title=\"Dial Options\") ## if self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self,", "label if self.canvas and self.showLabel == 1: self.printLabel() def setMin(self,", "= [math.sin(a), math.cos(a)] self.value = val self.offsetValue = val #update", "methods: ##################################################################### def configure(self, **kw): for key,value in kw.items(): #", "self.opPanel = None # option panel widget self.oneTurn = 360.", "import os from mglutil.util.callback import CallbackManager from mglutil.util.misc import ensureFontCase", "type(0), type(0.0), type(max) ) if self.min and max < self.min:", "!= 0: mode = 1 self.lockValue = mode if hasattr(self.opPanel,", "turn corresponds to 360 units by default. A dial can", "key = '.' elif key == 'minus': key = '-'", "createCanvas(self, master): size = self.size self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken')", "self.showLabel == 2: label = 'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay()", "labCfg and size can be passed only to the constructor.", "= event.y def mouseWheel(self, event): #print \"mouseWheel\", event, event.num if", "1: # show always widget labels self.showLabel=1 self.printLabel() if val", "elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif", "than 0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal size: expected type %s,", "mode = 1 self.lockType = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "valueString): try: self.set(self.type(valueString)) except ValueError: # fixme we would like", "self.arrowHeadWidth = 2*self.arrowWidth # width of arrow head base def", "or 'float', got '%s'\"%Type self.type = eval(Type) else: self.type =", "label 1: label is always shown 2: show label only", "configure() method: type, min, max, increment, precision, showLabel, value, continuous,", "self.showLabel=1 self.printLabel() if val == 2: # show widget labels", "#print \"mouseWheel\", event, event.num if os.name == 'nt': #sys.platform ==", "self.lockPrecision = lockPrecision self.lockShowLabel = lockShowLabel self.lockValue = lockValue self.lockType", "= 0.0 # current value of widget self.oldValue = 0.0", "in [None, 0, 1],\\ \"Illegal value for continuous: expected None,", "if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas is None: return", "type(incr) ) self.increment = self.type(incr) self.offsetValue = self.value self.incrementOld =", "# maximum value self.increment = increment # value increment self.minOld", "the 'configure' methods: ##################################################################### def configure(self, **kw): for key,value in", "self.printLabel() def setMin(self, min): if min is not None: assert", "elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif", "the size of the dial. The widget has a configure()", "cb): \"\"\"Set widget callback. Must be callable function. Callback is", "arrow according to the size of the dial. The widget", "ang = math.acos(ma) # find the sign of the rotation,", "yb = self.xm - self.vector[1]*self.radNoArrow # vector orthogonal to arrow", "label on self.continuous = 1 # set to 1 to", "self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if val ==", "used portion self.unusedArcColor = '#cccccc' # filled arc color of", "!= 0. and not force: offset = self.offsetValue%self.increment dval =", "self.opPanel.updateDisplay() # and update the printed label if self.canvas and", "self.xm - self.vector[1]*self.radNoArrow # vector orthogonal to arrow n =", "self.max: min = self.max self.min = self.type(min) if self.showLabel ==", "## License along with this library; if not, write to", "the value, disregarding the current active increment, the set method", "the options panel. Usage: <instance>.lock(<component>=<value>) components see configure(). value is", "angle increment compared to current vector ang = math.acos(ma) #", "argument # initialize various attributes with default values self.precision =", "Expected 'int' or 'float', got '%s'\"%Type self.type = eval(Type) else:", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): # increment checkbutton if mode", "min, max, increment, precision, showLabel, value, continuous, oneTurn can be", "the case if the dial # is set to continuous=0,", "self.min is not None and val < self.min: val =", "size: expected type %s, got %s\"%(type(1), type(size) ) assert size", "vector and angle corresponding to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if", "self.vector[0]*self.radNoArrow yb = self.xm - self.vector[1]*self.radNoArrow # vector orthogonal to", "self.drawArrow() if self.showLabel == 1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def", "self.maxOld = self.max else: self.max = None if hasattr(self.opPanel, 'optionsForm'):", "## ################################################################################ ######################################################################### # # Date: Mai 2001 Authors: <NAME>,", "to x). In this mode the values will be restrained", "automatically the size of the arrow according to the size", "disregarding the current active increment, the set method understands the", "self.max = None # maximum value self.increment = increment #", "have received a copy of the GNU Lesser General Public", "options panel # snap to closest increment if self.increment is", "setLabel(self, labCfg): self.labCfg = labCfg text = labCfg.get('text', None) if", "set to 1, we call this method regardless of the", "arrow head length self.arrowWidth = max(2, aS) # half the", "Lesser General Public ## License along with this library; if", "of arrow head base def mouseDown(self, event): # remember where", "and the increment is set to 2, setting the value", "unused portion self.pyOver180 = math.pi/180.0 # constants used in various", "every value change if self.contiguous is set to 1, else", "drawArrow(self): if self.canvas is None: return # end point x1", "self.printLabel() def setContinuous(self, cont): \"\"\" cont can be None, 0", "event.y def mouseUp(self, event): # call callbacks if not in", "== 'side': continue else: d[k] = w if not 'side'", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ == '__main__':", "max. One turn corresponds to 360 units by default. A", "0, got %s\"%size self.size = size def setCallback(self, cb): \"\"\"Set", "if key.isdigit() or key=='period' or key=='minus' or key=='plus': if key", "after the widget has been created. The widget tried to", "label self.callback = None # user specified callback self.opPanel =", "A dial can also operate in discrete mode (if self.increment", "the dial # is set to continuous=0, but the value", "def setPrecision(self, val): assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type", "lockShowLabel self.lockValue = lockValue self.lockType = lockType self.lockContinuous = lockContinuous", "the current value as an argument. An optional label can", "key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size): \"\"\"Set widget", "self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self): return self.type(self.value) def printLabel(self): if", "min checkbutton if mode != 0: mode = 1 self.lockBMin", "corresponding to value self.labCfg = labCfg # Tkinter Label options", "traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event): # handle key strokes for", "= event.x-self.xm dy = self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if n", "value change, else gets called # on button release event", "compute the new value val = self.value + ang*self.oneTurnOver2pi self.set(val)", "dval = self.min elif self.max is not None and dval", "the value is set to 3, and the increment is", "+ tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,)", "self.radNoArrow = self.rad-self.arrowLength self.vector = [0, 1] x1 = self.xm", "mouse went down self.lastx = event.x self.lasty = event.y def", "import ensureFontCase from optionsPanel import OptionsPanel from KeyboardEntry import KeyboardEntry", "type(Type) in [types.StringType, types.TypeType],\\ \"Illegal type for datatype. Expected %s", "self.labelFormat = \"%d\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val)", "# increment entry field if mode != 0: mode =", "mode): # max checkbutton if mode != 0: mode =", "sys import os from mglutil.util.callback import CallbackManager from mglutil.util.misc import", "self.threeSixtyOver1turn = 1 self.piOver1turn = math.pi/360. self.lockMin = lockMin #", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if mode != 0: mode", "key=='period' or key=='minus' or key=='plus': if key == 'period': key", "%s, got %s\"%( type(0), type(0.0), type(oneTurn) ) self.oneTurn = oneTurn", "< self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0')", "canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name == 'nt': #sys.platform ==", ") if self.max and min > self.max: min = self.max", "self.setFromEntry) self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") ## if", "10 if val < 1: val = 1 self.precision =", "types.ListType: for func in cb: assert callable(func), \"Illegal callback must", "or %s, got %s\"%( type('a'), type(type), type(Type) ) if type(Type)", "WARRANTY; without even the implied warranty of ## MERCHANTABILITY or", "increment correctly self.lab = None # label self.callback = None", "self.max = self.type(max) if self.showLabel == 1: self.printLabel() if self.value", "modify it under the terms of the GNU Lesser General", "label is always shown 2: show label only when value", "self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### # the 'configure' methods: ##################################################################### def", "to <value>. The increment will now be added to this", "like to pop this up in a window maybe import", "yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2 = [ x1,", "if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0:", "lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0,", "assert cb is None or callable(cb) or type(cb) is types.ListType,\\", "expected None, 0 or 1, got %s\"%cont if cont !=", "# turn on to display label on self.continuous = 1", "master, labCfg and size can be passed only to the", "the center of the Dial widget. The size of the", "self.showLabel==2: self.printLabel() else: if self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel() if", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if mode !=", "self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if size is not", "be specified at instanciation. Other parameters can be set after", "base xb = self.xm + self.vector[0]*self.radNoArrow yb = self.xm -", "\"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type ==", "method: type, min, max, increment, precision, showLabel, value, continuous, oneTurn", "values with increment enabled: if using the method set(), the", "self.angle - 360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)]", "regardless of the # widget configuration. This is for example", "a window maybe import traceback traceback.print_stack() traceback.print_exc() def handleKeyStroke(self, event):", "Got %s\"%cb if cb is None: return elif type(cb) is", "= (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle = self.angle - 360.0", "\"Illegal type for datatype. Expected %s or %s, got %s\"%(", "for minimum. Expected type %s or %s, got %s\"%( type(0),", "canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='',", "= math.pi/oneTurn self.oneTurnOver2pi = oneTurn / (2*math.pi) if self.opPanel: self.opPanel.updateDisplay()", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockShowLabelCB(self, mode): if mode != 0:", "type(0.0), type(oneTurn) ) self.oneTurn = oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn", "to the next increment. i.e., if the value is set", "dx = event.x-self.xm dy = self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if", "if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg = labCfg text", ") canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def", "parameter callbacks if key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value) elif key=='min':", "cont can be None, 0 or 1 \"\"\" assert cont", "self.lockShowLabel = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode):", "-1.0: ma = -1.0 # compute angle increment compared to", "%s, got %s\"%( type(0), type(0.0), type(min) ) if self.max and", "the mouse went down self.lastx = event.x self.lasty = event.y", "1 self.lockBMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self,", "be moved around a circle. The range corresponding to one", "mode = 1 self.lockBMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback = cb def toggleOptPanel(self,", "MA 02110-1301 USA ## ## (C) Copyrights Dr. <NAME> and", "the set method understands the optional keyword force=True, i.e. dial.set(<value>,", "the GNU Lesser General Public ## License as published by", "License along with this library; if not, write to the", "= self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = val self.offsetValue", "self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val): if type(val) == types.StringType: val", "Callback is called every time the widget value is set/modified\"\"\"", "terms of the GNU Lesser General Public ## License as", "dial can also operate in discrete mode (if self.increment is", "= None # label self.callback = None # user specified", "as published by the Free Software Foundation; either ## version", "self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### # the 'configure' methods: #####################################################################", "xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2 = [ x1, y1,", "if val == 2: # show widget labels only when", "to lock/unlock entries in optionpanel self.lockIncrement = lockIncrement self.lockBMin =", "setValue(self, val): if type(val) == types.StringType: val = float(val) assert", "self.showLabel == 1: self.printLabel() def setMin(self, min): if min is", "callable, or list. Got %s\"%cb if cb is None: return", "= labCfg.get('text', None) if text is None or text=='': return", "value is 0 or 1. 1 disables, 0 enables. Setting", "as the min and max values that are allowed. By", "in [types.IntType, types.FloatType],\\ \"Illegal type for precision. Expected type %s", "lockPrecisionCB(self, mode): if mode != 0: mode = 1 self.lockPrecision", "is not None: assert type(incr) in [types.IntType, types.FloatType],\\ \"Illegal type", "setting the value to 6 will actually result in 7", "= 10 if val < 1: val = 1 self.precision", "> 0.0: col1 = '#DDDDDD' col2 = 'black' else: col1", "of type int and greater than 0\"\"\" assert isinstance(size, types.IntType),\\", "elif key == 'minus': key = '-' elif key ==", "or type(cb) is types.ListType,\\ \"Illegal callback: must be either None", "master): size = self.size self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas", "self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment = self.type(0) if hasattr(self.opPanel,", "360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi = oneTurn / (2*math.pi) if", "v = [0.0, 0.0] else: v = [dx/n, dy/n] #", "min): if min is not None: assert type(min) in [types.IntType,", "None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr):", "no rounding errors if ma > 1.0: ma = 1.0", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment =", "# assure no rounding errors if ma > 1.0: ma", "[types.IntType, types.FloatType],\\ \"Illegal type for precision. Expected type %s or", "a Callback manager. Callback functions get called at every value", "there is no min and no max. One turn corresponds", "increment=.0, precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0,", "the widget has been created. The widget tried to adjust", "argument. An optional label can be displayed at the center", "self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if mode != 0: mode =", "v[0]*self.vector[0] + v[1]*self.vector[1] # assure no rounding errors if ma", "self.lockContinuous = lockContinuous self.lockOneTurn = lockOneTurn self.setArrow() # configure with", "the actual value will 'snap' to the next increment. i.e.,", "value=0.0, continuous=1, oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0,", "of used portion self.unusedArcColor = '#cccccc' # filled arc color", "elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type): assert type(Type) in [types.StringType,", "update the printed label if self.canvas and self.showLabel == 1:", "force is set to 1, we call this method regardless", "None: assert type(min) in [types.IntType, types.FloatType],\\ \"Illegal type for minimum.", "canvas.create_line(2, self.ym, size+2, self.ym) canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId =", "the arrow according to the size of the dial. The", "lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master)", "canvas to create the widget in self.usedArcColor = '#aaaaaa' #", "that it will be useful, ## but WITHOUT ANY WARRANTY;", "if type(val) == types.StringType: val = float(val) assert type(val) in", "%s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback = cb def toggleOptPanel(self, event=None):", "published by the Free Software Foundation; either ## version 2.1", "the Free Software ## Foundation, Inc., 51 Franklin Street, Fifth", "is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val,", "recompute vector and angle corresponding to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn", "if lEventNum == 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self): return", "be callable. Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback = cb", "x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth ] canvas", "= '+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def", "self.showLabel == 1: self.printLabel() if self.value > self.max: self.set(self.max) if", "oneTurn / (2*math.pi) if self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the 'lock'", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): #", "decimal places self.min = None # minimum value self.max =", "val != 2: print \"Illegal value. Must be 0, 1", "to set increment correctly self.lab = None # label self.callback", "self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min entry field if mode !=", "import types import sys import os from mglutil.util.callback import CallbackManager", "elif self.type == 'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() # and", "get called with the # current value as an argument", "apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,) +", "> self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0')", "self.showLabel == 1: self.printLabel() def setContinuous(self, cont): \"\"\" cont can", "types.FloatType],\\ \"Illegal type for oneTurn. Expected %s or %s, got", "set to x). In this mode the values will be", "0 or 1 \"\"\" assert cont in [None, 0, 1],\\", "%s or %s, got %s\"%( type(0), type(0.0), type(min) ) if", "assert cont in [None, 0, 1],\\ \"Illegal value for continuous:", "# # <EMAIL> # <EMAIL> # # Copyright: <NAME>, <NAME>", "event.keysym if key.isdigit() or key=='period' or key=='minus' or key=='plus': if", "of the GNU Lesser General Public ## License as published", "be set this way. master, labCfg and size can be", "down self.lastx = event.x self.lasty = event.y def mouseUp(self, event):", "= 1.0 elif ma < -1.0: ma = -1.0 #", "widget size self.offsetValue = 0. # used to set increment", "mode (if self.increment is set to x). In this mode", "self.canvas = None # the canvas to create the widget", "only when value changes\"\"\" assert val in [0,1,2],\\ \"Illegal value", "the value to <value>. The increment will now be added", "None or callable(cb) or type(cb) is types.ListType,\\ \"Illegal callback: must", "a configure() method: type, min, max, increment, precision, showLabel, value,", "self.lockBIncrement = lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel = lockShowLabel self.lockValue", "Copyright: <NAME>, <NAME> and TSRI # ######################################################################### import Tkinter import", "are set to None meaning that there is no min", "= (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle = self.angle - 360.0", "= None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self,", "value is set in the options panel # snap to", "i.e. dial.set(<value>, force=True)), which will set the value to <value>.", "self.lockBMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode):", "None: assert type(incr) in [types.IntType, types.FloatType],\\ \"Illegal type for increment.", "# value increment self.minOld = 0. # used to store", "types.StringType: val = float(val) assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal", "the min and max values that are allowed. By defaults", "lockMin # lock<X> vars are used in self.lock() self.lockMax =", "call a callback! if self.min is not None and val", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): # max", "value: expected %s or %s, got %s\"%( type(1), type(1.0), type(val)", "!= 0: mode = 1 self.lockBMax = mode if hasattr(self.opPanel,", "entries callbacks elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin':", "######################################################################### # # Date: Mai 2001 Authors: <NAME>, <NAME> #", "the rotation, sign of z component of vector prod. oldv", ") apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2", "master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0, precision=2, showLabel=1, value=0.0,", "!= 0 and val != 1 and val != 2:", "self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show label can be 0,", "n = math.sqrt(dx*dx+dy*dy) if n == 0.0: v = [0.0,", "old value of widget self.showLabel = 1 # turn on", "= self, title=\"Dial Options\") # pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1,", "self.increment else: dval = dval + offset if self.min is", "not None: assert type(min) in [types.IntType, types.FloatType],\\ \"Illegal type for", "lockBMinCB(self, mode): # min checkbutton if mode != 0: mode", "#update arrow in display self.drawArrow() newVal = self.get() if self.continuous", "setSize(self, size): \"\"\"Set widget size. Size must be of type", "setShowLabel(self, val): \"\"\"Show label can be 0, 1 or 2", "self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\",", "self.lockMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode):", "as well as the min and max values that are", "self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2 =", "= 5 else: lEventNum = event.num if lEventNum == 4:", "or %s, got %s\"%( type(0), type(0.0), type(val) ) val =", "else: if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self,", "lockValueCB(self, mode): if mode != 0: mode = 1 self.lockValue", "release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event): dx =", "the method set(), the actual value will 'snap' to the", "max values that are allowed. By defaults these are set", "lockBMaxCB(self, mode): # max checkbutton if mode != 0: mode", "## This library is distributed in the hope that it", "is always shown 2: show label only when value changes\"\"\"", "increment if self.min is not None and val < self.min:", "to adjust automatically the size of the arrow according to", "self.lasty = event.y def mouseUp(self, event): # call callbacks if", "== 1: label = 'always' elif self.showLabel == 2: label", "you can redistribute it and/or ## modify it under the", "if self.value < self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1)", "self.size self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2,", "def setType(self, Type): assert type(Type) in [types.StringType, types.TypeType],\\ \"Illegal type", "arrow # shadow lines self.arrowHeadWidth = 2*self.arrowWidth # width of", "# the 'lock' methods: ##################################################################### def lockTypeCB(self, mode): if mode", "type %s, got %s\"%(type(1), type(size) ) assert size > 0,", "import Tkinter import math import types import sys import os", "Expected type %s or %s, got %s\"%( type(0), type(0.0), type(val)", "value as an argument # initialize various attributes with default", "portion self.pyOver180 = math.pi/180.0 # constants used in various places", "= cb def toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if", "the arrow body width self.arrowBorderwidth = max(1, self.arrowWidth/2) # width", "# is set to continuous=0, but the value is set", "self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas is None: return # end", "user specified callback self.opPanel = None # option panel widget", "shown 2: show label only when value changes\"\"\" assert val", "None and dval < self.min: dval = self.min elif self.max", "setContinuous(self, cont): \"\"\" cont can be None, 0 or 1", "math.cos(a)] self.value = dval self.offsetValue = dval else: # 'regular'", "= self.ym - self.vector[1]*self.rad # point at arrow head base", "= 1 self.lockContinuous = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size): \"\"\"Set widget size.", "self.max is not None and val > self.max: val =", "if self.canvas is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def", "canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry)", "self.vector[0]*self.rad y1 = self.ym + self.vector[1]*self.rad canvas = self.canvas self.circleId", "'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max): if max is", "self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self,", "can be None, 0 or 1 \"\"\" assert cont in", "## version 2.1 of the License, or (at your option)", "tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,) +", "max = self.min self.max = self.type(max) if self.showLabel == 1:", "= 0. # used to set increment correctly self.lab =", "displayed at the center of the Dial widget. The size", "else: self.labelFormat = \"%d\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget']", "[types.IntType, types.FloatType],\\ \"Illegal type for maximum. Expected type %s or", "# show widget labels only when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2,", "label key = event.keysym if key.isdigit() or key=='period' or key=='minus'", "= event.y def mouseUp(self, event): # call callbacks if not", "not 'side' in self.labCfg.keys(): self.labCfg['side'] = 'left' if not self.lab:", "labCfg # Tkinter Label options self.labelFont = ( ensureFontCase('helvetica'), 14,", "'snap' to the next increment. i.e., if the value is", "every time the widget value is set/modified\"\"\" assert cb is", "that are allowed. By defaults these are set to None", "= canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth ) r =", "def lockValueCB(self, mode): if mode != 0: mode = 1", "a Dial widget. The widget has a pointer that can", "self.lockContinuous = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode):", "or list. Got %s\"%cb if cb is None: return elif", "( ensureFontCase('helvetica'), 14, 'bold') # label font self.labelColor = 'yellow'", "self.incrementOld = increment self.size = 50 # defines widget size", "val = self.min if self.max is not None and val", "!= 1 and val != 2: print \"Illegal value. Must", "to this new <value> \"\"\" def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left',", "2001 Authors: <NAME>, <NAME> # # <EMAIL> # <EMAIL> #", "around a circle. The range corresponding to one full turn", "None and dval > self.max: dval = self.max # recompute", "self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min", "A PARTICULAR PURPOSE. See the GNU ## Lesser General Public", "#sys.platform == 'win32': if event.delta > 0: lEventNum = 4", "<EMAIL> # # Copyright: <NAME>, <NAME> and TSRI # #########################################################################", "= max(1, self.arrowWidth/2) # width of arrow # shadow lines", "in display self.drawArrow() newVal = self.get() if self.continuous or force:", "and val < self.min: val = self.min if self.max is", "lockContinuousCB(self, mode): if mode != 0: mode = 1 self.lockContinuous", "self.vector = [0, 1] x1 = self.xm + self.vector[0]*self.rad y1", "def setShowLabel(self, val): \"\"\"Show label can be 0, 1 or", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): # min checkbutton", "type(Type) == type(\"\"): # type str assert Type in ('int','float'),\\", "\"\"\" assert cont in [None, 0, 1],\\ \"Illegal value for", "values self.maxOld = 0. self.incrementOld = increment self.size = 50", "key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self, Type): assert type(Type)", "increment. i.e., if the value is set to 3, and", "# compute the new value val = self.value + ang*self.oneTurnOver2pi", "self.min: max = self.min self.max = self.type(max) if self.showLabel ==", "%s or %s, got %s\"%( type(0), type(0.0), type(val) ) val", "self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0)", "self.vector = [math.sin(a), math.cos(a)] self.value = dval self.offsetValue = dval", "self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value)", "mode != 0: mode = 1 self.lockMax = mode if", "type(val) ) # setValue does NOT call a callback! if", "widget size. Size must be of type int and greater", "master) Tkinter.Pack.config(self) self.callbacks = CallbackManager() # object to manage callback", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max else:", "%s\"%( type(1), type(1.0), type(val) ) # setValue does NOT call", "%s, got %s\"%( type(0), type(0.0), type(incr) ) self.increment = self.type(incr)", "General Public ## License along with this library; if not,", "Type if self.type == int: self.labelFormat = \"%d\" self.int_value =", "more details. ## ## You should have received a copy", "button release event self.angle = 0. # angle corresponding to", "lockType=0, lockContinuous=0, lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks = CallbackManager()", "increment # value increment self.minOld = 0. # used to", "the terms of the GNU Lesser General Public ## License", "# handle key strokes for numbers only in widget keyboard", "self.oldValue != newVal or force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if", "text='') def mouseMove(self, event): dx = event.x-self.xm dy = self.ym-event.y", "snap to closest increment if self.increment is not None and", "-1.0 # compute angle increment compared to current vector ang", "value for showLabel. Expected 0, 1 or 2, got %s\"%val", "= 1 self.lockBMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "value to 6 will actually result in 7 (3,5,7,9,.....) To", "= 2 # decimal places self.min = None # minimum", "fill='white', width = self.arrowBorderwidth ) r = size/20 off =", "r = size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off,", "def handleKeyStroke(self, event): # handle key strokes for numbers only", "strokes for numbers only in widget keyboard entry label key", "None # user specified callback self.opPanel = None # option", "mode): if mode != 0: mode = 1 self.lockContinuous =", "setMax(self, max): if max is not None: assert type(max) in", "if force is set to 1, we call this method", "> 0: lEventNum = 4 else: lEventNum = 5 else:", "= self.value self.incrementOld = self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1)", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max): if", "# if force is set to 1, we call this", "val #update arrow in display self.drawArrow() newVal = self.get() if", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr): if", "# used to store old values self.maxOld = 0. self.incrementOld", "# arrow head length self.arrowWidth = max(2, aS) # half", "distributed in the hope that it will be useful, ##", "1, got %s\"%cont if cont != 1: cont = None", "widget. The widget has a pointer that can be moved", "= dval self.offsetValue = dval else: # 'regular' mode, i.e.", "self.value < self.min: self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal',", "elif ma < -1.0: ma = -1.0 # compute angle", "in ('int','float'),\\ \"Illegal type descriptor. Expected 'int' or 'float', got", "labels self.showLabel=1 self.printLabel() if val == 2: # show widget", "set to continuous=0, but the value is set in the", "got %s\"%size self.size = size def setCallback(self, cb): \"\"\"Set widget", "when value changes\"\"\" assert val in [0,1,2],\\ \"Illegal value for", "from optionsPanel import OptionsPanel from KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame,", "!= newVal or force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2:", "if self.max and min > self.max: min = self.max self.min", "in self.labCfg.keys(): self.labCfg['side'] = 'left' if not self.lab: self.lab =", "the dial. The widget has a configure() method: type, min,", "[math.sin(a), math.cos(a)] self.value = val self.offsetValue = val #update arrow", "\"Illegal value. Must be 0, 1 or 2\" return self.showLabel", "= event.x self.lasty = event.y def mouseWheel(self, event): #print \"mouseWheel\",", "# max entry field if mode != 0: mode =", "self.arrowPolborder1, fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure(", "size def setCallback(self, cb): \"\"\"Set widget callback. Must be callable", "method understands the optional keyword force=True, i.e. dial.set(<value>, force=True)), which", "# set to 1 to call callbacks at # each", "val = self.max # recompute vector and angle corresponding to", "Expected 0, 1 or 2, got %s\"%val if val !=", "type(cb) is types.ListType: for func in cb: assert callable(func), \"Illegal", "col1 = '#DDDDDD' col2 = 'black' else: col1 = 'black'", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): # min checkbutton if", "= [ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth, self.ym-n[1]*self.arrowWidth", "== 1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg): self.labCfg", "set the value, disregarding the current active increment, the set", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if mode", "key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) # the", "def lockShowLabelCB(self, mode): if mode != 0: mode = 1", "hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() #", "self.opPanel.updateDisplay() ##################################################################### # the 'lock' methods: ##################################################################### def lockTypeCB(self, mode):", "else: self.set(self.value-self.oneTurn) def get(self): return self.type(self.value) def printLabel(self): if self.canvas", "width of arrow # shadow lines self.arrowHeadWidth = 2*self.arrowWidth #", "14, 'bold') # label font self.labelColor = 'yellow' # label", "labels on mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self,", "or 2 0: no label 1: label is always shown", "self.showLabel == 1: label = 'always' elif self.showLabel == 2:", "self.increment = self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40')", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): # increment", "] canvas = self.canvas if self.vector[0] > 0.0: col1 =", "the values will be restrained to be multiples of self.increment.", "The Widget has a Callback manager. Callback functions get called", "0.0 # old value of widget self.showLabel = 1 #", "self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### # the 'configure' methods:", "self.increment = self.type(incr) self.offsetValue = self.value self.incrementOld = self.increment if", "checkbutton if mode != 0: mode = 1 self.lockBIncrement =", "value to <value>. The increment will now be added to", "increment entry field if mode != 0: mode = 1", "+ tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent =", "got %s\"%( type(0), type(0.0), type(oneTurn) ) self.oneTurn = oneTurn self.threeSixtyOver1turn", "dval = round(val/self.increment) * self.increment if val < dval: dval", "ma < -1.0: ma = -1.0 # compute angle increment", "to val self.angle = (val%self.oneTurn)*self.threeSixtyOver1turn if val <0.0: self.angle =", "self.setType(value) elif key=='min': self.setMin(value) elif key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value)", "increment. Expected type %s or %s, got %s\"%( type(0), type(0.0),", "portion self.unusedArcColor = '#cccccc' # filled arc color of unused", "'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ == '__main__': def foo(val): print val", "showLabel, value, continuous, oneTurn can be set this way. master,", "widget self.oldValue = 0.0 # old value of widget self.showLabel", "type(0.0), type(min) ) if self.max and min > self.max: min", "callback # functions. They get called with the # current", "self.printLabel() if val == 2: # show widget labels only", "min = self.max self.min = self.type(min) if self.showLabel == 1:", "type(oneTurn) ) self.oneTurn = oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn =", "0,0,0,0,0,0,0,0, fill='black', width = self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white',", "result in 7 (3,5,7,9,.....) To still be able to set", "val = self.min elif self.max is not None and val", "= val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if", "d[k] = w if not 'side' in self.labCfg.keys(): self.labCfg['side'] =", "= eval(Type) else: self.type = Type if self.type == int:", "= self.type(min) if self.showLabel == 1: self.printLabel() if self.value <", "= self.type(max) if self.showLabel == 1: self.printLabel() if self.value >", "will 'snap' to the next increment. i.e., if the value", "used in various places self.threeSixtyOver1turn = 1 self.piOver1turn = math.pi/360.", "None or callable, or list. Got %s\"%cb if cb is", "outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2,", "self.size = 50 # defines widget size self.offsetValue = 0.", "types.FloatType],\\ \"Illegal type for precision. Expected type %s or %s,", "0: mode = 1 self.lockIncrement = mode if hasattr(self.opPanel, 'optionsForm'):", "with increment enabled: if using the method set(), the actual", "value is set to 3, and the increment is set", "self.offsetValue = self.value self.incrementOld = self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment)", "License, or (at your option) any later version. ## ##", "self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2: # no widget labels", "key=='min': self.setMin(value) elif key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value) elif key=='precision':", "at every value change if self.contiguous is set to 1,", "type(type), type(Type) ) if type(Type) == type(\"\"): # type str", "to 1, we call this method regardless of the #", "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val): assert", "\"%d\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel:", "= 0. # angle corresponding to value self.labCfg = labCfg", "= self.offsetValue%self.increment dval = round(val/self.increment) * self.increment if val <", "= size def setCallback(self, cb): \"\"\"Set widget callback. Must be", "event.x-self.xm dy = self.ym-event.y n = math.sqrt(dx*dx+dy*dy) if n ==", "self.vector = [math.sin(a), math.cos(a)] self.value = val self.offsetValue = val", "self.ym) canvas.create_line(self.xm, 2, self.ym, size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,", "None and val > self.max: val = self.max self.value =", "is set to 3, and the increment is set to", "None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val, update=1,", "offset = self.offsetValue%self.increment dval = round(val/self.increment) * self.increment if val", "self.continuous or force: if update and self.oldValue != newVal or", "key == 'plus': key = '+' self.typedValue += key self.typedValueTK.configure(text=self.typedValue)", "mode != 0: mode = 1 self.lockShowLabel = mode if", "type for precision. Expected type %s or %s, got %s\"%(", "\"Illegal callback: must be either None or callable, or list.", "implements a Dial widget. The widget has a pointer that", "None and val < self.min: val = self.min elif self.max", "assert size > 0, \"Illegal size: must be > 0,", "at the center of the Dial widget. The size of", "can be set this way. master, labCfg and size can", "a callback! if self.min is not None and val <", "and dval < self.min: dval = self.min elif self.max is", "self.value #update arrow in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value", "None, 0 or 1 \"\"\" assert cont in [None, 0,", "## ## This library is distributed in the hope that", "return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val, update=1, force=0):", "- self.vector[1]*self.rad # point at arrow head base xb =", "self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else: if self.showLabel==2:", "# 'regular' mode, i.e. no step-wise increment if self.min is", "if self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the 'lock' methods: ##################################################################### def", "1],\\ \"Illegal value for continuous: expected None, 0 or 1,", "<NAME> and TSRI 2016 ## ################################################################################ ######################################################################### # # Date:", "a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel", "lockMaxCB(self, mode): # max entry field if mode != 0:", "callbacks if key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value) elif key=='min': self.setMin(value)", "self.lab = None # label self.callback = None # user", "adjust automatically the size of the arrow according to the", "Fifth Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights", "+ v[1]*self.vector[1] # assure no rounding errors if ma >", "None: assert type(max) in [types.IntType, types.FloatType],\\ \"Illegal type for maximum.", "method set(), the actual value will 'snap' to the next", "for oneTurn. Expected %s or %s, got %s\"%( type(0), type(0.0),", "text is None or text=='': return d={} for k, w", "# point at arrow head base xb = self.xm +", "%s, got %s\"%( type(0), type(0.0), type(val) ) val = int(val)", "borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm = self.ym", "self.incrementOld = self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0')", "\"\"\" def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0,", "self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try: self.set(self.type(valueString)) except ValueError:", "self, title=\"Dial Options\") # pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x')", "is not None and self.increment != 0. and not force:", "no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if val", "this method regardless of the # widget configuration. This is", "= 2*self.arrowWidth # width of arrow head base def mouseDown(self,", "-self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth,", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if mode != 0:", "canvas.coords, (self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply(", "(self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle = self.angle - 360.0 a", "== 0.0: v = [0.0, 0.0] else: v = [dx/n,", "tried to adjust automatically the size of the arrow according", "cb: assert callable(func), \"Illegal callback must be callable. Got %s\"%func", "continuous, oneTurn can be set this way. master, labCfg and", "shadow lines self.arrowHeadWidth = 2*self.arrowWidth # width of arrow head", "self.xm + self.vector[0]*self.radNoArrow yb = self.xm - self.vector[1]*self.radNoArrow # vector", "\"\"\"Set widget size. Size must be of type int and", "self.lockType = lockType self.lockContinuous = lockContinuous self.lockOneTurn = lockOneTurn self.setArrow()", "1 self.lockValue = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self,", "self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel)", "for maximum. Expected type %s or %s, got %s\"%( type(0),", "self.angle = 0. # angle corresponding to value self.labCfg =", "type(val) == types.StringType: val = float(val) assert type(val) in [types.IntType,", "val > self.max: val = self.max # recompute vector and", "offset if self.min is not None and dval < self.min:", "# call callbacks if not in continuous mode if not", "be set after the widget has been created. The widget", "assert type(Type) in [types.StringType, types.TypeType],\\ \"Illegal type for datatype. Expected", "width = self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width =", "!= 0: mode = 1 self.lockBMin = mode if hasattr(self.opPanel,", "if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert type(oneTurn) in [types.IntType,", "= 50 # defines widget size self.offsetValue = 0. #", "this way. master, labCfg and size can be passed only", "self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the 'lock' methods: ##################################################################### def lockTypeCB(self,", "## ## (C) Copyrights Dr. <NAME> and TSRI 2016 ##", "position and previous # hand position ma = v[0]*self.vector[0] +", "Software ## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,", "The size of the dial has to be specified at", "= -1. * ang # compute the new value val", "== 0: # no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId,", "elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif", "'%s'\"%Type self.type = eval(Type) else: self.type = Type if self.type", "= 'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert", "and TSRI # ######################################################################### import Tkinter import math import types", "label can be displayed at the center of the Dial", "cb def toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not", "if self.max is not None and val > self.max: val", "or (at your option) any later version. ## ## This", "from mglutil.util.misc import ensureFontCase from optionsPanel import OptionsPanel from KeyboardEntry", "##################################################################### def lockTypeCB(self, mode): if mode != 0: mode =", "body width self.arrowBorderwidth = max(1, self.arrowWidth/2) # width of arrow", "in [types.IntType, types.FloatType],\\ \"Illegal type for maximum. Expected type %s", "entry field if mode != 0: mode = 1 self.lockMax", "self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master =", "details. ## ## You should have received a copy of", "# old value of widget self.showLabel = 1 # turn", "oldv[1]*v[0] if normz>0: ang = -1. * ang # compute", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if mode", "Tkinter import math import types import sys import os from", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if", "or 2\" return self.showLabel = val self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'):", "# <EMAIL> # # Copyright: <NAME>, <NAME> and TSRI #", "!= 1: cont = None self.continuous = cont if hasattr(self.opPanel,", "continuous=0, but the value is set in the options panel", "self.arrowWidth = max(2, aS) # half the arrow body width", "self.max is not None and dval > self.max: dval =", "fg='gray40') def setPrecision(self, val): assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal", "if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None):", "restrained to be multiples of self.increment. The Widget has a", "self.vector[1]*self.rad # point at arrow head base xb = self.xm", "= [math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel == 1: self.printLabel() if", "self.offsetValue = 0. # used to set increment correctly self.lab", "if self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try: self.set(self.type(valueString)) except", "self.min: val = self.min elif self.max is not None and", "# remember where the mouse went down self.lastx = event.x", "the GNU ## Lesser General Public License for more details.", "fg='gray0') self.minOld = self.min else: self.min = None if hasattr(self.opPanel,", "event): # call callbacks if not in continuous mode if", "def setSize(self, size): \"\"\"Set widget size. Size must be of", "0: mode = 1 self.lockOneTurn = mode if hasattr(self.opPanel, 'optionsForm'):", "0, 1],\\ \"Illegal value for continuous: expected None, 0 or", "along with this library; if not, write to the Free", "WITHOUT ANY WARRANTY; without even the implied warranty of ##", "at # each value change, else gets called # on", "if self.value > self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1)", "'move' w.setvalue(label) if self.opPanel: self.opPanel.updateDisplay() def setOneTurn(self, oneTurn): assert type(oneTurn)", "lockBIncrement self.lockPrecision = lockPrecision self.lockShowLabel = lockShowLabel self.lockValue = lockValue", "# Date: Mai 2001 Authors: <NAME>, <NAME> # # <EMAIL>", "self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi = oneTurn /", "None: self.setSize(size) aS = self.size/40 self.arrowLength = max(3, 3*aS) #", "if self.type == float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat =", "math.pi/oneTurn self.oneTurnOver2pi = oneTurn / (2*math.pi) if self.opPanel: self.opPanel.updateDisplay() #####################################################################", "callable(cb) or type(cb) is types.ListType,\\ \"Illegal callback: must be either", "enables. Setting values with increment enabled: if using the method", "# the canvas to create the widget in self.usedArcColor =", "field if mode != 0: mode = 1 self.lockMin =", "is not None: assert type(max) in [types.IntType, types.FloatType],\\ \"Illegal type", "of unused portion self.pyOver180 = math.pi/180.0 # constants used in", "##################################################################### # the 'lock' methods: ##################################################################### def lockTypeCB(self, mode): if", "event.x self.lasty = event.y def mouseWheel(self, event): #print \"mouseWheel\", event,", "val): if val == 0: # no widget labels self.showLabel=0", "1: self.printLabel() if self.value > self.max: self.set(self.max) if hasattr(self.opPanel, 'optionsForm'):", "widget labels on mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def", "to closest increment if self.increment is not None and self.increment", "self.rad-self.arrowLength self.vector = [0, 1] x1 = self.xm + self.vector[0]*self.rad", "the canvas to create the widget in self.usedArcColor = '#aaaaaa'", "value, disregarding the current active increment, the set method understands", "greater than 0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal size: expected type", "self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") ## if self.callback:", "width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0, fill=self.usedArcColor) canvas.create_line(2, self.ym,", "later version. ## ## This library is distributed in the", "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU", "compared to current vector ang = math.acos(ma) # find the", "!= 0: mode = 1 self.lockOneTurn = mode if hasattr(self.opPanel,", "if self.opPanel: self.opPanel.updateDisplay() # and update the printed label if", "initialize various attributes with default values self.precision = 2 #", "val = int(val) if val > 10: val = 10", "+ self.vector[1]*self.rad canvas = self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor)", "dval < self.min: dval = self.min elif self.max is not", ") canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2)", "corresponding to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle", "The range corresponding to one full turn can be specified", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if", "# used to set increment correctly self.lab = None #", "in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0: self.angle =", "self.min elif self.max is not None and dval > self.max:", "General Public License for more details. ## ## You should", "self.set(self.min) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld =", "def lockBMaxCB(self, mode): # max checkbutton if mode != 0:", "0. # used to set increment correctly self.lab = None", "fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2,", "been created. The widget tried to adjust automatically the size", "find the sign of the rotation, sign of z component", "= Type if self.type == int: self.labelFormat = \"%d\" self.int_value", "and update the printed label if self.canvas and self.showLabel ==", "self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if", "= 1 self.lockMax = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__ == '__main__': def foo(val):", "find the cosine of the angle between new hand position", "\"\"\" cont can be None, 0 or 1 \"\"\" assert", "%s\"%size self.size = size def setCallback(self, cb): \"\"\"Set widget callback.", "1: cont = None self.continuous = cont if hasattr(self.opPanel, 'optionsForm'):", "setFromEntry(self, valueString): try: self.set(self.type(valueString)) except ValueError: # fixme we would", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): # max entry", "method regardless of the # widget configuration. This is for", "def setValue(self, val): if type(val) == types.StringType: val = float(val)", "else: dval = dval + offset if self.min is not", "up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if val", "or 1. 1 disables, 0 enables. Setting values with increment", "active increment, the set method understands the optional keyword force=True,", "in continuous mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel ==", "# min checkbutton if mode != 0: mode = 1", "or 1 \"\"\" assert cont in [None, 0, 1],\\ \"Illegal", "self.oneTurn = 360. # value increment for 1 full turn", "size = self.size self.frame = Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas =", "= labCfg # Tkinter Label options self.labelFont = ( ensureFontCase('helvetica'),", "next increment. i.e., if the value is set to 3,", "self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent = 0.0-self.angle) def createCanvas(self, master):", "Free Software Foundation; either ## version 2.1 of the License,", "value change if self.contiguous is set to 1, else they", "= self.max # recompute vector and angle corresponding to val", "## This library is free software; you can redistribute it", "##################################################################### # the 'configure' methods: ##################################################################### def configure(self, **kw): for", "else: if self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal)", "key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel':", "font self.labelColor = 'yellow' # label color self.canvas = None", "on self.continuous = 1 # set to 1 to call", "for key,value in kw.items(): # the 'set' parameter callbacks if", "math.cos(a)] self.value = val self.offsetValue = val #update arrow in", "else: self.min = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40')", "at arrow head base xb = self.xm + self.vector[0]*self.radNoArrow yb", "Widget has a Callback manager. Callback functions get called at", "self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value)", "%s, got %s\"%( type(0), type(0.0), type(max) ) if self.min and", "mode != 0: mode = 1 self.lockMin = mode if", "font = self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='',", "places self.threeSixtyOver1turn = 1 self.piOver1turn = math.pi/360. self.lockMin = lockMin", "self.min = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def", "set after the widget has been created. The widget tried", "user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn) self.setMin(min) self.setMax(max)", "################################################################################ ######################################################################### # # Date: Mai 2001 Authors: <NAME>, <NAME>", "\"\"\"Set widget callback. Must be callable function. Callback is called", "widget has a pointer that can be moved around a", "is not None and dval > self.max: dval = self.max", "== 0: label = 'never' elif self.showLabel == 1: label", "key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif key=='continuous':", "self.setMin(min) self.setMax(max) self.setIncrement(increment) self.setShowLabel(showLabel) self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas", "type for maximum. Expected type %s or %s, got %s\"%(", "label font self.labelColor = 'yellow' # label color self.canvas =", "self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0: self.angle = self.angle -", "the increment is set to 2, setting the value to", "if self.contiguous is set to 1, else they get called", "# and update the printed label if self.canvas and self.showLabel", "Setting values with increment enabled: if using the method set(),", "increment compared to current vector ang = math.acos(ma) # find", "pts2 = [ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth, self.xm-n[0]*self.arrowWidth,", "if incr is not None: assert type(incr) in [types.IntType, types.FloatType],\\", "if using the method set(), the actual value will 'snap'", "1. 1 disables, 0 enables. Setting values with increment enabled:", "Callback manager. Callback functions get called at every value change", "# angle corresponding to value self.labCfg = labCfg # Tkinter", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): #", "has a pointer that can be moved around a circle.", "either ## version 2.1 of the License, or (at your", "w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay() # and update the printed label", "turn on to display label on self.continuous = 1 #", "value. Must be 0, 1 or 2\" return self.showLabel =", "#update arrow in display self.angle = (self.value%self.oneTurn)*self.threeSixtyOver1turn if self.value <0.0:", "type(0), type(0.0), type(oneTurn) ) self.oneTurn = oneTurn self.threeSixtyOver1turn = 360./oneTurn", "if mode != 0: mode = 1 self.lockMax = mode", "2 # decimal places self.min = None # minimum value", "== 'minus': key = '-' elif key == 'plus': key", "= self.increment if hasattr(self.opPanel, 'optionsForm'): self.opPanel.incrInput.set(self.labelFormat%self.increment) self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else:", "self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId = canvas.create_arc(2,2,size,size, start=90., extent=0,", "callback! if self.min is not None and val < self.min:", "self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value)", "not None and self.increment != 0. and not force: offset", "the 'lock' methods: ##################################################################### def lockTypeCB(self, mode): if mode !=", "a copy of the GNU Lesser General Public ## License", "setCallback(self, cb): \"\"\"Set widget callback. Must be callable function. Callback", "if ma > 1.0: ma = 1.0 elif ma <", "self.increment if val < dval: dval = dval + offset", "# pack em up self.canvas.pack(side=Tkinter.TOP) self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self,", "of the dial. The widget has a configure() method: type,", "self.canvas is None: return # end point x1 = self.xm", "self.max self.value = self.type(val) self.offsetValue=self.value self.oldValue = self.value #update arrow", "%s or %s, got %s\"%( type(0), type(0.0), type(incr) ) self.increment", "os.name == 'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\",", "'black' col2 = '#DDDDDD' apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) )", "val == 0: # no widget labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='')", "current value as an argument # initialize various attributes with", "i.e., if the value is set to 3, and the", "self.opPanel.toggleIncr.set(1) self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment = self.type(0) if hasattr(self.opPanel, 'optionsForm'):", "self.lockOneTurnCB(value) def setType(self, Type): assert type(Type) in [types.StringType, types.TypeType],\\ \"Illegal", "self.setOneTurn(value) # the 'lock' entries callbacks elif key=='lockType': self.lockTypeCB(value) elif", "with this library; if not, write to the Free Software", "= lockIncrement self.lockBMin = lockBMin self.lockBMax = lockBMax self.lockBIncrement =", "and greater than 0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal size: expected", "continuous mode if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2:", "minimum value self.max = None # maximum value self.increment =", "# label self.callback = None # user specified callback self.opPanel", "is None or text=='': return d={} for k, w in", "'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int: w.setvalue('int') elif", "1: label is always shown 2: show label only when", "self.canvas if self.vector[0] > 0.0: col1 = '#DDDDDD' col2 =", "Public ## License as published by the Free Software Foundation;", "self.frame.pack(expand=1, fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if val == 0:", "# the 'configure' methods: ##################################################################### def configure(self, **kw): for key,value", "if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self,", "= Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### #", "%s\"%( type(0), type(0.0), type(incr) ) self.increment = self.type(incr) self.offsetValue =", "self.max = None if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def", "# to lock/unlock entries in optionpanel self.lockIncrement = lockIncrement self.lockBMin", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockIncrementCB(self, mode): # increment entry field if", "no max. One turn corresponds to 360 units by default.", "a lock() method is used to disable the various gui", "# widget configuration. This is for example the case if", "canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2", "fill=self.labelColor, justify='center', text='', font = self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master", "self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def", "we call this method regardless of the # widget configuration.", "the 'set' parameter callbacks if key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value)", "in [types.IntType, types.FloatType],\\ \"Illegal type for oneTurn. Expected %s or", "or callable(cb) or type(cb) is types.ListType,\\ \"Illegal callback: must be", "else: # 'regular' mode, i.e. no step-wise increment if self.min", "self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show label can be 0, 1", "1 self.lockOneTurn = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() if __name__", "w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show label can", "self.setContinuous(value) elif key=='oneTurn': self.setOneTurn(value) # the 'lock' entries callbacks elif", "## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", "0: mode = 1 self.lockContinuous = mode if hasattr(self.opPanel, 'optionsForm'):", "== types.StringType: val = float(val) assert type(val) in [types.IntType, types.FloatType],\\", "size): \"\"\"Set widget size. Size must be of type int", "only in widget keyboard entry label key = event.keysym if", "'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if", "to one full turn can be specified as well as", "== 1: self.printLabel() def setMin(self, min): if min is not", "self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth ) r", "assert type(incr) in [types.IntType, types.FloatType],\\ \"Illegal type for increment. Expected", "!= 0: mode = 1 self.lockShowLabel = mode if hasattr(self.opPanel,", "callable(func), \"Illegal callback must be callable. Got %s\"%func self.callbacks.AddCallback(func) else:", "not None and dval < self.min: dval = self.min elif", "by the Free Software Foundation; either ## version 2.1 of", "## ## You should have received a copy of the", "lockOneTurnCB(self, mode): if mode != 0: mode = 1 self.lockOneTurn", "ma > 1.0: ma = 1.0 elif ma < -1.0:", "panel widget self.oneTurn = 360. # value increment for 1", "'nt': #sys.platform == 'win32': canvas.bind(\"<MouseWheel>\", self.mouseWheel) else: canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\",", "'-' elif key == 'plus': key = '+' self.typedValue +=", "cosine of the angle between new hand position and previous", "return self.type(self.value) def printLabel(self): if self.canvas is None: return self.canvas.itemconfigure(self.labelId2,", "self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0: label = 'never' elif self.showLabel", "self.rad = size/2 self.radNoArrow = self.rad-self.arrowLength self.vector = [0, 1]", "callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0,", "= round(val/self.increment) * self.increment if val < dval: dval =", "> self.max: val = self.max # recompute vector and angle", "xb = self.xm + self.vector[0]*self.radNoArrow yb = self.xm - self.vector[1]*self.radNoArrow", ") assert size > 0, \"Illegal size: must be >", "See the GNU ## Lesser General Public License for more", "or key=='minus' or key=='plus': if key == 'period': key =", "fg='gray0') else: self.increment = self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0)", "max): if max is not None: assert type(max) in [types.IntType,", "in [types.IntType, types.FloatType],\\ \"Illegal type for minimum. Expected type %s", "else: lEventNum = 5 else: lEventNum = event.num if lEventNum", "key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif key=='lockOneTurn': self.lockOneTurnCB(value) def setType(self,", "callable. Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback = cb def", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMaxCB(self, mode): # max entry field if", "self.labCfg = labCfg # Tkinter Label options self.labelFont = (", "self.setMin(value) elif key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value) elif key=='precision': self.setPrecision(value)", "self.ym + self.vector[1]*self.rad canvas = self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1,", "size can be passed only to the constructor. a lock()", "self.ym-n[1]*self.arrowWidth ] canvas = self.canvas if self.vector[0] > 0.0: col1", "= oldv[0]*v[1] - oldv[1]*v[0] if normz>0: ang = -1. *", "= 1 self.lockType = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "free software; you can redistribute it and/or ## modify it", "set method understands the optional keyword force=True, i.e. dial.set(<value>, force=True)),", "widget configuration. This is for example the case if the", "self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): # min checkbutton if mode !=", "operate in discrete mode (if self.increment is set to x).", "self.min = None # minimum value self.max = None #", "None meaning that there is no min and no max.", "labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0, precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360.,", "head length self.arrowWidth = max(2, aS) # half the arrow", "type('a'), type(type), type(Type) ) if type(Type) == type(\"\"): # type", "# recompute vector and angle corresponding to val self.angle =", "arrow head base def mouseDown(self, event): # remember where the", "would like to pop this up in a window maybe", "1 disables, 0 enables. Setting values with increment enabled: if", "apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1 )", "# # Copyright: <NAME>, <NAME> and TSRI # ######################################################################### import", "elif key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif", "key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax':", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBMinCB(self, mode): # min", "the # widget configuration. This is for example the case", "value increment for 1 full turn self.value = 0.0 #", "except ValueError: # fixme we would like to pop this", "z component of vector prod. oldv = self.vector normz =", "if update and self.oldValue != newVal or force: self.oldValue =", "self.min: val = self.min if self.max is not None and", "type(0.0), type(max) ) if self.min and max < self.min: max", "val): assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for precision.", "if val < 1: val = 1 self.precision = val", "= lockBMin self.lockBMax = lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision =", "1: label = 'always' elif self.showLabel == 2: label =", "Street, Fifth Floor, Boston, MA 02110-1301 USA ## ## (C)", "'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max else: self.max", "self.opPanel.lockUnlockDisplay() def lockBMaxCB(self, mode): # max checkbutton if mode !=", "is set to continuous=0, but the value is set in", "'optionsForm'): self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr): if incr is", "# minimum value self.max = None # maximum value self.increment", "the new value val = self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx", "= self.rad-self.arrowLength self.vector = [0, 1] x1 = self.xm +", "def lockMaxCB(self, mode): # max entry field if mode !=", "0: mode = 1 self.lockBIncrement = mode if hasattr(self.opPanel, 'optionsForm'):", "1: val = 1 self.precision = val if self.type ==", "method is used to disable the various gui components of", "extent = 0.0-self.angle) def createCanvas(self, master): size = self.size self.frame", "when the mouse button is released. They always get called", "on mouse release self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def mouseMove(self, event):", "elif key=='min': self.setMin(value) elif key=='max': self.setMax(value) elif key=='increment': self.setIncrement(value) elif", "to the size of the dial. The widget has a", "!= 0: mode = 1 self.lockMin = mode if hasattr(self.opPanel,", "< self.min: val = self.min if self.max is not None", "0, 1 or 2, got %s\"%val if val != 0", "val < self.min: val = self.min elif self.max is not", "for numbers only in widget keyboard entry label key =", "# filled arc color of used portion self.unusedArcColor = '#cccccc'", "Lesser General Public License for more details. ## ## You", "optional label can be displayed at the center of the", "1, else they get called when the mouse button is", "= self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth", "self.ym = size/2+2 self.rad = size/2 self.radNoArrow = self.rad-self.arrowLength self.vector", "mode): if mode != 0: mode = 1 self.lockPrecision =", "will now be added to this new <value> \"\"\" def", "/ (2*math.pi) if self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the 'lock' methods:", "dval + offset if self.min is not None and dval", "self.lastx = event.x self.lasty = event.y def mouseUp(self, event): #", "cont = None self.continuous = cont if hasattr(self.opPanel, 'optionsForm'): w", "> 0, \"Illegal size: must be > 0, got %s\"%size", "widget value is set/modified\"\"\" assert cb is None or callable(cb)", "= self.canvas if self.vector[0] > 0.0: col1 = '#DDDDDD' col2", "is not None: self.setSize(size) aS = self.size/40 self.arrowLength = max(3,", "= [dx/n, dy/n] # find the cosine of the angle", "self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld = self.max else: self.max = None if", "GNU Lesser General Public ## License as published by the", "must be callable. Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb) self.callback =", "increment, the set method understands the optional keyword force=True, i.e.", "self.opPanel: self.opPanel.updateDisplay() # and update the printed label if self.canvas", "dval else: # 'regular' mode, i.e. no step-wise increment if", "button is released. They always get called with the current", "as an argument # initialize various attributes with default values", "released. They always get called with the current value as", "types.FloatType],\\ \"Illegal type for maximum. Expected type %s or %s,", "with the current value as an argument. An optional label", "value self.labCfg = labCfg # Tkinter Label options self.labelFont =", "= None # the canvas to create the widget in", "newVal or force: self.oldValue = newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel()", "360.0 a = self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value =", "vector orthogonal to arrow n = [-self.vector[1], -self.vector[0]] pts1 =", "be callable function. Callback is called every time the widget", "self.usedArcColor = '#aaaaaa' # filled arc color of used portion", "and val > self.max: val = self.max # recompute vector", "the Free Software Foundation; either ## version 2.1 of the", "self.callbacks = CallbackManager() # object to manage callback # functions.", "val == 2: # show widget labels only when mouse", "= w if not 'side' in self.labCfg.keys(): self.labCfg['side'] = 'left'", "self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='', font = self.labelFont)", "specified as well as the min and max values that", "according to the size of the dial. The widget has", "elif type(cb) is types.ListType: for func in cb: assert callable(func),", "increment checkbutton if mode != 0: mode = 1 self.lockBIncrement", "max(2, aS) # half the arrow body width self.arrowBorderwidth =", "0: label = 'never' elif self.showLabel == 1: label =", "got %s\"%(type(1), type(size) ) assert size > 0, \"Illegal size:", "canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black',", "Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This class implements a Dial widget. The widget", "we would like to pop this up in a window", "0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth ) r = size/20 off", "mode): if mode != 0: mode = 1 self.lockType =", "Options\") ## if self.callback: ## self.callbacks.AddCallback(self.callback) def setFromEntry(self, valueString): try:", "dial. The widget has a configure() method: type, min, max,", "= max(2, aS) # half the arrow body width self.arrowBorderwidth", "0 enables. Setting values with increment enabled: if using the", "KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master = self, title=\"Dial Options\")", "self.increment != 0. and not force: offset = self.offsetValue%self.increment dval", "0: mode = 1 self.lockValue = mode if hasattr(self.opPanel, 'optionsForm'):", "'optionsForm'): self.opPanel.toggleIncr.set(0) self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val): assert type(val)", "(2*math.pi) if self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the 'lock' methods: #####################################################################", "## (C) Copyrights Dr. <NAME> and TSRI 2016 ## ################################################################################", "< self.min: max = self.min self.max = self.type(max) if self.showLabel", "i.e. no step-wise increment if self.min is not None and", "fixme we would like to pop this up in a", "[types.StringType, types.TypeType],\\ \"Illegal type for datatype. Expected %s or %s,", "0. # angle corresponding to value self.labCfg = labCfg #", "color of unused portion self.pyOver180 = math.pi/180.0 # constants used", "= lockContinuous self.lockOneTurn = lockOneTurn self.setArrow() # configure with user-defined", "current vector ang = math.acos(ma) # find the sign of", "'#DDDDDD' apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) ) apply( canvas.coords, (self.arrowPolborder1,)", "type(0.0), type(incr) ) self.increment = self.type(incr) self.offsetValue = self.value self.incrementOld", "current value of widget self.oldValue = 0.0 # old value", "= self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.drawArrow() if self.showLabel ==", "and self.increment != 0. and not force: offset = self.offsetValue%self.increment", "self.labelFormat = \"%d\" self.int_value = self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\"", "= lockShowLabel self.lockValue = lockValue self.lockType = lockType self.lockContinuous =", "self.offsetValue%self.increment dval = round(val/self.increment) * self.increment if val < dval:", "2: # no widget labels on mouse release self.canvas.itemconfigure(self.labelId2, text='')", "1 self.lockType = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self,", "incr is not None: assert type(incr) in [types.IntType, types.FloatType],\\ \"Illegal", "key=='lockMax': self.lockMaxCB(value) elif key=='lockBMax': self.lockBMaxCB(value) elif key=='lockIncrement': self.lockIncrementCB(value) elif key=='lockBIncrement':", "< dval: dval = dval + offset - self.increment else:", "library is distributed in the hope that it will be", "key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous':", "if not 'side' in self.labCfg.keys(): self.labCfg['side'] = 'left' if not", "value as an argument. An optional label can be displayed", "# find the cosine of the angle between new hand", "Tkinter Label options self.labelFont = ( ensureFontCase('helvetica'), 14, 'bold') #", "the dial has to be specified at instanciation. Other parameters", "def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0, precision=2,", "for example the case if the dial # is set", "# fixme we would like to pop this up in", "+ self.vector[0]*self.rad y1 = self.ym - self.vector[1]*self.rad # point at", "'#DDDDDD' col2 = 'black' else: col1 = 'black' col2 =", "self.drawArrow() self.opPanel = OptionsPanel(master = self, title=\"Dial Options\") # pack", "hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int: w.setvalue('int')", "size+2) self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 =", "be displayed at the center of the Dial widget. The", "lockContinuous self.lockOneTurn = lockOneTurn self.setArrow() # configure with user-defined values", "angle corresponding to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval <0.0:", "self.showLabel == 2: # no widget labels on mouse release", "= 1 self.precision = val if self.type == float: self.labelFormat", "self.setSize(size) aS = self.size/40 self.arrowLength = max(3, 3*aS) # arrow", "labels self.showLabel=0 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') if val == 1:", "point x1 = self.xm + self.vector[0]*self.rad y1 = self.ym -", "1 or 2 0: no label 1: label is always", "'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def setArrow(self, size=None): if size is", "is not None: assert type(min) in [types.IntType, types.FloatType],\\ \"Illegal type", "# width of arrow head base def mouseDown(self, event): #", "Expected type %s or %s, got %s\"%( type(0), type(0.0), type(max)", "errors if ma > 1.0: ma = 1.0 elif ma", "1 self.lockContinuous = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self,", "outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center', text='', font =", "> self.max: dval = self.max # recompute vector and angle", "y1 = self.ym - self.vector[1]*self.rad # point at arrow head", "expected type %s, got %s\"%(type(1), type(size) ) assert size >", "not None and val > self.max: val = self.max #", "# show always widget labels self.showLabel=1 self.printLabel() if val ==", "assert type(min) in [types.IntType, types.FloatType],\\ \"Illegal type for minimum. Expected", "n == 0.0: v = [0.0, 0.0] else: v =", "set to 1, else they get called when the mouse", "if val != 0 and val != 1 and val", "They get called with the # current value as an", "1 or 2\" return self.showLabel = val self.toggleWidgetLabel(val) if hasattr(self.opPanel,", "that there is no min and no max. One turn", "lEventNum = event.num if lEventNum == 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn)", "0.0] else: v = [dx/n, dy/n] # find the cosine", "force=True, i.e. dial.set(<value>, force=True)), which will set the value to", "event.num if lEventNum == 4: self.set(self.value+self.oneTurn) else: self.set(self.value-self.oneTurn) def get(self):", "be able to set the value, disregarding the current active", "0: mode = 1 self.lockPrecision = mode if hasattr(self.opPanel, 'optionsForm'):", "= 1 self.lockValue = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='', font =", "callbacks elif key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value)", "lockIncrementCB(self, mode): # increment entry field if mode != 0:", "= oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi =", "if the value is set to 3, and the increment", "# value increment for 1 full turn self.value = 0.0", "or key=='plus': if key == 'period': key = '.' elif", "self.arrowBorderwidth) self.arrowPolborder2 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='white', width = self.arrowBorderwidth )", "assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for value: expected", "component of vector prod. oldv = self.vector normz = oldv[0]*v[1]", "self.set(self.max) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.maxInput.set(self.labelFormat%self.max) self.opPanel.toggleMax.set(1) self.opPanel.max_entry.configure(state='normal', fg='gray0') self.maxOld =", "self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): # increment checkbutton if mode !=", "length self.arrowWidth = max(2, aS) # half the arrow body", "self.setValue(value) self.setLabel(self.labCfg) self.createCanvas(master) canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp)", "self.vector[0]*self.rad y1 = self.ym - self.vector[1]*self.rad # point at arrow", "ensureFontCase from optionsPanel import OptionsPanel from KeyboardEntry import KeyboardEntry class", "This is for example the case if the dial #", "force=0): # if force is set to 1, we call", "= self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w", "self.type = eval(Type) else: self.type = Type if self.type ==", "self.opPanel.lockUnlockDisplay() def lockValueCB(self, mode): if mode != 0: mode =", "int: w.setvalue('int') elif self.type == 'float': w.setvalue('float') if self.opPanel: self.opPanel.updateDisplay()", "math.acos(ma) # find the sign of the rotation, sign of", "is not None and val > self.max: val = self.max", "continuous=1, oneTurn=360., size=50, callback=None, lockMin=0, lockBMin=0, lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0,", "outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black', justify='center',", "key.isdigit() or key=='period' or key=='minus' or key=='plus': if key ==", "if self.continuous or force: if update and self.oldValue != newVal", "to 3, and the increment is set to 2, setting", "canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\", self.toggleOptPanel) if os.name == 'nt':", "fg='gray40') def setIncrement(self, incr): if incr is not None: assert", "places self.min = None # minimum value self.max = None", "if self.min and max < self.min: max = self.min self.max", "if val == 1: # show always widget labels self.showLabel=1", "math.sqrt(dx*dx+dy*dy) if n == 0.0: v = [0.0, 0.0] else:", "0.0 # current value of widget self.oldValue = 0.0 #", "0 and val != 1 and val != 2: print", "self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat = \"%d\" if hasattr(self.opPanel, 'optionsForm'):", "self.callbacks.AddCallback(cb) self.callback = cb def toggleOptPanel(self, event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb()", "type for value: expected %s or %s, got %s\"%( type(1),", ") apply( canvas.coords, (self.arrowPolborder1,) + tuple(pts1) ) canvas.itemconfigure( self.arrowPolborder1, fill=col1", "can be specified as well as the min and max", "'set' parameter callbacks if key=='labCfg': self.setLabel(value) elif key=='type': self.setType(value) elif", "lockBMin self.lockBMax = lockBMax self.lockBIncrement = lockBIncrement self.lockPrecision = lockPrecision", "type %s or %s, got %s\"%( type(0), type(0.0), type(min) )", "is set/modified\"\"\" assert cb is None or callable(cb) or type(cb)", "self.max and min > self.max: min = self.max self.min =", "went down self.lastx = event.x self.lasty = event.y def mouseUp(self,", "self.minOld = 0. # used to store old values self.maxOld", "by default. A dial can also operate in discrete mode", "= None # user specified callback self.opPanel = None #", "def setMin(self, min): if min is not None: assert type(min)", "text=self.labelFormat%self.value)#newVal) def set(self, val, update=1, force=0): # if force is", "if self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas", "fill='x') self.toggleWidgetLabel(self.showLabel) def toggleWidgetLabel(self, val): if val == 0: #", "widget callback. Must be callable function. Callback is called every", "def configure(self, **kw): for key,value in kw.items(): # the 'set'", "= self, title=\"Dial Options\") ## if self.callback: ## self.callbacks.AddCallback(self.callback) def", "lockOneTurn=0, **kw): Tkinter.Frame.__init__(self, master) Tkinter.Pack.config(self) self.callbacks = CallbackManager() # object", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if", "= math.sqrt(dx*dx+dy*dy) if n == 0.0: v = [0.0, 0.0]", "canvas = self.canvas self.circleId = canvas.create_oval(2,2,size,size, width=1, fill=self.unusedArcColor) self.arcId =", "lockMax=0, lockBMax=0, lockIncrement=0, lockBIncrement=0, lockPrecision=0, lockShowLabel=0, lockValue=0, lockType=0, lockContinuous=0, lockOneTurn=0,", "lockType self.lockContinuous = lockContinuous self.lockOneTurn = lockOneTurn self.setArrow() # configure", "FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## Lesser", "\"Illegal callback must be callable. Got %s\"%func self.callbacks.AddCallback(func) else: self.callbacks.AddCallback(cb)", "mode = 1 self.lockBMin = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "justify='center', text='', font = self.labelFont) self.drawArrow() self.opPanel = OptionsPanel(master =", "type(0.0), type(val) ) val = int(val) if val > 10:", "actual value will 'snap' to the next increment. i.e., if", "callback self.opPanel = None # option panel widget self.oneTurn =", "your option) any later version. ## ## This library is", "= None # maximum value self.increment = increment # value", "val = self.value + ang*self.oneTurnOver2pi self.set(val) self.lastx = event.x self.lasty", "d={} for k, w in self.labCfg.items(): if k == 'side':", "assert val in [0,1,2],\\ \"Illegal value for showLabel. Expected 0,", "int and greater than 0\"\"\" assert isinstance(size, types.IntType),\\ \"Illegal size:", "self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min else: self.min = None if", "self.increment = increment # value increment self.minOld = 0. #", "self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if mode != 0: mode =", "maximum value self.increment = increment # value increment self.minOld =", "= 1 self.lockShowLabel = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def", "to None meaning that there is no min and no", "new <value> \"\"\" def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None,", "configure with user-defined values self.setSize(size) self.setCallback(callback) self.setContinuous(continuous) self.setType(type) self.setPrecision(precision) self.setOneTurn(oneTurn)", "TSRI 2016 ## ################################################################################ ######################################################################### # # Date: Mai 2001", "arrow head base xb = self.xm + self.vector[0]*self.radNoArrow yb =", "called every time the widget value is set/modified\"\"\" assert cb", "self.continuous = 1 # set to 1 to call callbacks", "self.lockIncrementCB(value) elif key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value)", "None and self.increment != 0. and not force: offset =", "if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if mode !=", "if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else:", "else: d[k] = w if not 'side' in self.labCfg.keys(): self.labCfg['side']", "or %s, got %s\"%( type(0), type(0.0), type(max) ) if self.min", "self.oneTurn = oneTurn self.threeSixtyOver1turn = 360./oneTurn self.piOver1turn = math.pi/oneTurn self.oneTurnOver2pi", "self.type(self.value) def printLabel(self): if self.canvas is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal)", "import OptionsPanel from KeyboardEntry import KeyboardEntry class Dial(Tkinter.Frame, KeyboardEntry): \"\"\"This", "= self.angle*self.pyOver180 self.vector = [math.sin(a), math.cos(a)] self.value = dval self.offsetValue", "'always' elif self.showLabel == 2: label = 'move' w.setvalue(label) if", "= 0.0 # old value of widget self.showLabel = 1", "canvas.itemconfigure( self.arrowPolborder1, fill=col1 ) apply( canvas.coords, (self.arrowPolborder2,) + tuple(pts2) )", "= increment self.size = 50 # defines widget size self.offsetValue", "1 and val != 2: print \"Illegal value. Must be", "show label only when value changes\"\"\" assert val in [0,1,2],\\", "traceback.print_exc() def handleKeyStroke(self, event): # handle key strokes for numbers", "mglutil.util.callback import CallbackManager from mglutil.util.misc import ensureFontCase from optionsPanel import", "type for datatype. Expected %s or %s, got %s\"%( type('a'),", "canvas = self.canvas canvas.bind(\"<ButtonPress-1>\", self.mouseDown) canvas.bind(\"<ButtonRelease-1>\", self.mouseUp) canvas.bind(\"<B1-Motion>\", self.mouseMove) canvas.bind(\"<Button-3>\",", "if self.increment is not None and self.increment != 0. and", "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301", "key=='lockType': self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax':", "%s, got %s\"%( type(1), type(1.0), type(val) ) # setValue does", "hand position ma = v[0]*self.vector[0] + v[1]*self.vector[1] # assure no", "newVal self.callbacks.CallCallbacks(newVal) if self.showLabel==2: self.printLabel() else: if self.showLabel==2: self.printLabel() if", "a pointer that can be moved around a circle. The", "lock/unlock entries in optionpanel self.lockIncrement = lockIncrement self.lockBMin = lockBMin", "called with the # current value as an argument #", "call callbacks if not in continuous mode if not self.continuous:", "= self.xm + self.vector[0]*self.rad y1 = self.ym + self.vector[1]*self.rad canvas", "either None or callable, or list. Got %s\"%cb if cb", "self.opPanel.toggleMin.set(0) self.opPanel.min_entry.configure(state='disabled', fg='gray40') def setMax(self, max): if max is not", "setPrecision(self, val): assert type(val) in [types.IntType, types.FloatType],\\ \"Illegal type for", "+= key self.typedValueTK.configure(text=self.typedValue) else: KeyboardEntry.handleKeyStroke(self, event) def setSize(self, size): \"\"\"Set", "self.arrowPolId = canvas.create_polygon( 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 = canvas.create_line(", "0: no label 1: label is always shown 2: show", "mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min entry", "max checkbutton if mode != 0: mode = 1 self.lockBMax", "and no max. One turn corresponds to 360 units by", "self.lock() self.lockMax = lockMax # to lock/unlock entries in optionpanel", "or %s, got %s\"%( type(0), type(0.0), type(incr) ) self.increment =", "the size of the arrow according to the size of", "size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD', outline='white') canvas.create_oval(self.xm-r,self.ym-r+off,self.xm+r,self.ym+r+off, fill='black', outline='black')", "is not None and dval < self.min: dval = self.min", "def setArrow(self, size=None): if size is not None: self.setSize(size) aS", "self.arrowBorderwidth ) r = size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2, fill='#DDDDDD',", "else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget']", "- oldv[1]*v[0] if normz>0: ang = -1. * ang #", "and min > self.max: min = self.max self.min = self.type(min)", "call this method regardless of the # widget configuration. This", "Type in ('int','float'),\\ \"Illegal type descriptor. Expected 'int' or 'float',", "to 6 will actually result in 7 (3,5,7,9,.....) To still", "dial.set(<value>, force=True)), which will set the value to <value>. The", "Software Foundation; either ## version 2.1 of the License, or", "elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue': self.lockValueCB(value) elif key=='lockContinuous': self.lockContinuousCB(value) elif", "<value> \"\"\" def __init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None,", "'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if self.opPanel: self.opPanel.updateDisplay() # and", "if mode != 0: mode = 1 self.lockShowLabel = mode", "to call callbacks at # each value change, else gets", "[0, 1] x1 = self.xm + self.vector[0]*self.rad y1 = self.ym", "tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent = 0.0-self.angle)", "= max(3, 3*aS) # arrow head length self.arrowWidth = max(2,", "self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val, update=1, force=0): # if force", "does NOT call a callback! if self.min is not None", "increment for 1 full turn self.value = 0.0 # current", ") if self.min and max < self.min: max = self.min", "mouseWheel(self, event): #print \"mouseWheel\", event, event.num if os.name == 'nt':", "event): dx = event.x-self.xm dy = self.ym-event.y n = math.sqrt(dx*dx+dy*dy)", "1] x1 = self.xm + self.vector[0]*self.rad y1 = self.ym +", "get called when the mouse button is released. They always", "None # maximum value self.increment = increment # value increment", "entry label key = event.keysym if key.isdigit() or key=='period' or", "in optionpanel self.lockIncrement = lockIncrement self.lockBMin = lockBMin self.lockBMax =", "in cb: assert callable(func), \"Illegal callback must be callable. Got", "will set the value to <value>. The increment will now", "angle corresponding to value self.labCfg = labCfg # Tkinter Label", "event=None): if self.opPanel.flag: self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1)", "pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1,", "type for minimum. Expected type %s or %s, got %s\"%(", "Foundation; either ## version 2.1 of the License, or (at", "= 0. self.incrementOld = increment self.size = 50 # defines", "= '.' elif key == 'minus': key = '-' elif", "val <0.0: self.angle = self.angle - 360.0 a = self.angle*self.pyOver180", "event): # handle key strokes for numbers only in widget", "[types.IntType, types.FloatType],\\ \"Illegal type for increment. Expected type %s or", "self.lockTypeCB(value) elif key=='lockMin': self.lockMinCB(value) elif key=='lockBMin': self.lockBMinCB(value) elif key=='lockMax': self.lockMaxCB(value)", "value, continuous, oneTurn can be set this way. master, labCfg", "lockIncrement self.lockBMin = lockBMin self.lockBMax = lockBMax self.lockBIncrement = lockBIncrement", "return elif type(cb) is types.ListType: for func in cb: assert", "and TSRI 2016 ## ################################################################################ ######################################################################### # # Date: Mai", "self.showLabel == 1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self, labCfg):", "self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master = self, title=\"Dial", "always widget labels self.showLabel=1 self.printLabel() if val == 2: #", "lockMinCB(self, mode): #min entry field if mode != 0: mode", "# each value change, else gets called # on button", "<instance>.lock(<component>=<value>) components see configure(). value is 0 or 1. 1", "(C) Copyrights Dr. <NAME> and TSRI 2016 ## ################################################################################ #########################################################################", "= oneTurn / (2*math.pi) if self.opPanel: self.opPanel.updateDisplay() ##################################################################### # the", "for datatype. Expected %s or %s, got %s\"%( type('a'), type(type),", "canvas.bind(\"<Button-4>\", self.mouseWheel) canvas.bind(\"<Button-5>\", self.mouseWheel) KeyboardEntry.__init__(self, (canvas,), self.setFromEntry) self.opPanel = OptionsPanel(master", "if self.type == int: w.setvalue('int') elif self.type == 'float': w.setvalue('float')", "only when mouse moves self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def", "= [0.0, 0.0] else: v = [dx/n, dy/n] # find", "Dr. <NAME> and TSRI 2016 ## ################################################################################ ######################################################################### # #", "self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal) def set(self, val, update=1, force=0): #", "= 1 # turn on to display label on self.continuous", "sign of the rotation, sign of z component of vector", "self.opPanel.incr_entry.configure(state='normal', fg='gray0') else: self.increment = self.type(0) if hasattr(self.opPanel, 'optionsForm'): self.opPanel.toggleIncr.set(0)", "Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## ##", "Must be callable function. Callback is called every time the", "mouseUp(self, event): # call callbacks if not in continuous mode", "= dval else: # 'regular' mode, i.e. no step-wise increment", "] pts2 = [ x1, y1, xb-n[0]*self.arrowHeadWidth, yb-n[1]*self.arrowHeadWidth, xb-n[0]*self.arrowWidth, yb-n[1]*self.arrowWidth,", "def lockBMinCB(self, mode): # min checkbutton if mode != 0:", "if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int:", "= self.labelFont) self.labelId = canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='', font", "__name__ == '__main__': def foo(val): print val d = Dial(size=50)", "4 else: lEventNum = 5 else: lEventNum = event.num if", "mode): # min checkbutton if mode != 0: mode =", "the value is set in the options panel # snap", "d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text) ##################################################################### # the 'configure'", "key=='lockBIncrement': self.lockBIncrementCB(value) elif key=='lockPrecision': self.lockPrecisionCB(value) elif key=='lockShowLabel': self.lockShowLabelCB(value) elif key=='lockValue':", "1 or 2, got %s\"%val if val != 0 and", "min=None, max=None, increment=.0, precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50, callback=None,", "of self.increment. The Widget has a Callback manager. Callback functions", "the cosine of the angle between new hand position and", "\"Illegal value for continuous: expected None, 0 or 1, got", "# filled arc color of unused portion self.pyOver180 = math.pi/180.0", "self.opPanel.Dismiss_cb() else: if not hasattr(self.opPanel, 'optionsForm'): self.opPanel.displayPanel(create=1) else: self.opPanel.displayPanel(create=0) def", "def setCallback(self, cb): \"\"\"Set widget callback. Must be callable function.", "self.arrowWidth/2) # width of arrow # shadow lines self.arrowHeadWidth =", "self.opPanel.minInput.set(self.labelFormat%self.min) self.opPanel.toggleMin.set(1) self.opPanel.min_entry.configure(state='normal', fg='gray0') self.minOld = self.min else: self.min =", "self.opPanel.incrInput.set(self.labelFormat%0) self.opPanel.incr_entry.configure(state='disabled', fg='gray40') def setPrecision(self, val): assert type(val) in [types.IntType,", "self.toggleWidgetLabel(val) if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel ==", "w = self.opPanel.idf.entryByName['togLabel']['widget'] if self.showLabel == 0: label = 'never'", "if not self.continuous: self.callbacks.CallCallbacks(self.opPanel.valInput.get()) if self.showLabel == 2: # no", "to be multiples of self.increment. The Widget has a Callback", "# label color self.canvas = None # the canvas to", "and angle corresponding to val self.angle = (dval%self.oneTurn)*self.threeSixtyOver1turn if dval", "gets called # on button release event self.angle = 0.", "os from mglutil.util.callback import CallbackManager from mglutil.util.misc import ensureFontCase from", "= 360. # value increment for 1 full turn self.value", "= \"%d\" if hasattr(self.opPanel, 'optionsForm'): w = self.opPanel.idf.entryByName['selPrec']['widget'] w.setvalue(val) if", "= '-' elif key == 'plus': key = '+' self.typedValue", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockPrecisionCB(self, mode): if mode != 0: mode", "types.FloatType],\\ \"Illegal type for value: expected %s or %s, got", "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ##", "# compute angle increment compared to current vector ang =", "int(val) if val > 10: val = 10 if val", "else: lEventNum = event.num if lEventNum == 4: self.set(self.value+self.oneTurn) else:", "= '#cccccc' # filled arc color of unused portion self.pyOver180", "label only when value changes\"\"\" assert val in [0,1,2],\\ \"Illegal", "else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val): \"\"\"Show label", "self.opPanel.toggleMax.set(0) self.opPanel.max_entry.configure(state='disabled', fg='gray40') def setIncrement(self, incr): if incr is not", "cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel: self.opPanel.updateDisplay() def setShowLabel(self, val):", "be of type int and greater than 0\"\"\" assert isinstance(size,", "0: lEventNum = 4 else: lEventNum = 5 else: lEventNum", "self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def drawArrow(self): if self.canvas is", "# setValue does NOT call a callback! if self.min is", "== 1: # show always widget labels self.showLabel=1 self.printLabel() if", "hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockContinuousCB(self, mode): if mode != 0:", "val if self.type == float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else: self.labelFormat", "'#cccccc' # filled arc color of unused portion self.pyOver180 =", "optionpanel self.lockIncrement = lockIncrement self.lockBMin = lockBMin self.lockBMax = lockBMax", "= '#DDDDDD' apply( canvas.coords, (self.arrowPolId,) + tuple(pts1+pts2) ) apply( canvas.coords,", "key=='oneTurn': self.setOneTurn(value) # the 'lock' entries callbacks elif key=='lockType': self.lockTypeCB(value)", "self.showLabel=2 self.canvas.itemconfigure(self.labelId2, text='') self.canvas.itemconfigure(self.labelId, text='') def setValue(self, val): if type(val)", "else: self.type = Type if self.type == int: self.labelFormat =", "Authors: <NAME>, <NAME> # # <EMAIL> # <EMAIL> # #", "self.opPanel.idf.entryByName['togIntFloat']['widget'] if self.type == int: w.setvalue('int') elif self.type == 'float':", "[types.IntType, types.FloatType],\\ \"Illegal type for minimum. Expected type %s or", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockMinCB(self, mode): #min entry field if mode", "return # end point x1 = self.xm + self.vector[0]*self.rad y1", "canvas.create_text(self.xm, self.ym, fill=self.labelColor, justify='center', text='', font = self.labelFont) self.drawArrow() self.opPanel", "self.precision = 2 # decimal places self.min = None #", "elif key=='type': self.setType(value) elif key=='min': self.setMin(value) elif key=='max': self.setMax(value) elif", "def mouseDown(self, event): # remember where the mouse went down", "the current active increment, the set method understands the optional", "of widget self.oldValue = 0.0 # old value of widget", "hand position and previous # hand position ma = v[0]*self.vector[0]", "self.lab: self.lab = Tkinter.Label(self, d) self.lab.pack(side=self.labCfg['side']) self.lab.bind(\"<Button-3>\", self.toggleOptPanel) else: self.lab.configure(text)", "= 'always' elif self.showLabel == 2: label = 'move' w.setvalue(label)", "dval + offset - self.increment else: dval = dval +", "fill='black', outline='black') canvas.create_oval(self.xm-r,self.ym-r,self.xm+r,self.ym+r, fill='gray70', outline='#DDDDDD') self.labelId2 = canvas.create_text(self.xm+2, self.ym+2, fill='black',", "panel. Usage: <instance>.lock(<component>=<value>) components see configure(). value is 0 or", "== 'period': key = '.' elif key == 'minus': key", "(self.arrowPolborder2,) + tuple(pts2) ) canvas.itemconfigure( self.arrowPolborder2, fill=col2 ) canvas.itemconfigure(self.arcId, extent", "is released. They always get called with the current value", "callback. Must be callable function. Callback is called every time", "if not, write to the Free Software ## Foundation, Inc.,", "License for more details. ## ## You should have received", "n = [-self.vector[1], -self.vector[0]] pts1 = [ self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth,", "\"Illegal size: expected type %s, got %s\"%(type(1), type(size) ) assert", "mode = 1 self.lockOneTurn = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "to disable the various gui components of the options panel.", "cont in [None, 0, 1],\\ \"Illegal value for continuous: expected", "mode the values will be restrained to be multiples of", "self.int_value = self.value else: self.labelFormat = \"%.\"+str(self.precision)+\"f\" if hasattr(self.opPanel, 'optionsForm'):", "mode = 1 self.lockPrecision = mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay()", "'optionsForm'): self.opPanel.lockUnlockDisplay() def lockOneTurnCB(self, mode): if mode != 0: mode", "[0.0, 0.0] else: v = [dx/n, dy/n] # find the", "printLabel(self): if self.canvas is None: return self.canvas.itemconfigure(self.labelId2, text=self.labelFormat%self.value)#newVal) self.canvas.itemconfigure(self.labelId, text=self.labelFormat%self.value)#newVal)", "= mode if hasattr(self.opPanel, 'optionsForm'): self.opPanel.lockUnlockDisplay() def lockBIncrementCB(self, mode): #", "max(3, 3*aS) # arrow head length self.arrowWidth = max(2, aS)", "type(cb) is types.ListType,\\ \"Illegal callback: must be either None or", "0,0,0,0,0,0,0,0, fill='gray75' ) self.arrowPolborder1 = canvas.create_line( 0,0,0,0,0,0,0,0, fill='black', width =", "and self.showLabel == 1: self.printLabel() def setContinuous(self, cont): \"\"\" cont", "vars are used in self.lock() self.lockMax = lockMax # to", "if mode != 0: mode = 1 self.lockBMax = mode", "== '__main__': def foo(val): print val d = Dial(size=50) d.configure(showLabel=1)", "# the 'set' parameter callbacks if key=='labCfg': self.setLabel(value) elif key=='type':", "# ######################################################################### import Tkinter import math import types import sys", "__init__(self, master=None, type='float', labCfg={'fg':'black','side':'left', 'text':None}, min=None, max=None, increment=.0, precision=2, showLabel=1,", "maximum. Expected type %s or %s, got %s\"%( type(0), type(0.0),", "from mglutil.util.callback import CallbackManager from mglutil.util.misc import ensureFontCase from optionsPanel", "size is not None: self.setSize(size) aS = self.size/40 self.arrowLength =", "oneTurn): assert type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal type for oneTurn.", "for showLabel. Expected 0, 1 or 2, got %s\"%val if", "center of the Dial widget. The size of the dial", "if self.showLabel==2: self.printLabel() if self.showLabel==1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%newVal) def", "Tkinter.Frame(self, borderwidth=3, relief='sunken') self.canvas = Tkinter.Canvas(self.frame, width=size+2, height=size+2) self.xm =", "max=None, increment=.0, precision=2, showLabel=1, value=0.0, continuous=1, oneTurn=360., size=50, callback=None, lockMin=0,", "self.xm+n[0]*self.arrowWidth, self.ym+n[1]*self.arrowWidth, xb+n[0]*self.arrowWidth, yb+n[1]*self.arrowWidth, xb+n[0]*self.arrowHeadWidth, yb+n[1]*self.arrowHeadWidth, x1, y1 ] pts2", "= val if self.type == float: self.labelFormat = \"%.\"+str(self.precision)+\"f\" else:", "if self.showLabel == 1: self.printLabel() if self.opPanel: self.opPanel.valInput.set(self.labelFormat%self.value) def setLabel(self,", "cb is None or callable(cb) or type(cb) is types.ListType,\\ \"Illegal", "= 0.0-self.angle) def createCanvas(self, master): size = self.size self.frame =", "\"Illegal value for showLabel. Expected 0, 1 or 2, got", "self.labCfg.keys(): self.labCfg['side'] = 'left' if not self.lab: self.lab = Tkinter.Label(self,", "always get called with the current value as an argument.", "methods: ##################################################################### def lockTypeCB(self, mode): if mode != 0: mode", "= self.min elif self.max is not None and dval >", "dval self.offsetValue = dval else: # 'regular' mode, i.e. no", "= self.arrowBorderwidth ) r = size/20 off = self.arrowBorderwidth canvas.create_oval(self.xm-r,self.ym-r-off/2,self.xm+r,self.ym+r-off/2,", "key=='precision': self.setPrecision(value) elif key=='showLabel': self.setShowLabel(value) elif key=='continuous': self.setContinuous(value) elif key=='oneTurn':", "Floor, Boston, MA 02110-1301 USA ## ## (C) Copyrights Dr.", "be 0, 1 or 2 0: no label 1: label", "setOneTurn(self, oneTurn): assert type(oneTurn) in [types.IntType, types.FloatType],\\ \"Illegal type for", "self.min if self.max is not None and val > self.max:", "w = self.opPanel.idf.entryByName['togCont']['widget'] if cont: w.setvalue('on')#i=1 else: w.setvalue('off')#i=0 if self.opPanel:", "= [0, 1] x1 = self.xm + self.vector[0]*self.rad y1 =", "type(0), type(0.0), type(val) ) val = int(val) if val >", "= self.xm + self.vector[0]*self.radNoArrow yb = self.xm - self.vector[1]*self.radNoArrow #" ]
[ "'darwin': filename = 'makeinstall.darwin' else: print \"Unsupported platform: \", sys.platform", "https://www.qt.io/terms-conditions. For further # information use the contact form at", "subFolders, files in os.walk(rootdir): for file in (subFolders + files):", "0: print \"'%s' is empty!\" % f fileDict[f[len(rootdir)+1:]] = perm", "if len(args) != 1: usage() sys.exit(2) rootdir = args[0] if", "formattedlist; def usage(): print \"Usage: %s [-g | --generate] <dir>\"", "the file LICENSE.GPL3-EXCEPT # included in the packaging of this", "3 as published by the Free Software # Foundation with", "print \"Do not forget to commit\", referenceFile() else: hasDiff =", "getopt def referenceFile(): if sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif sys.platform.startswith('win'):", "hasDiff = False for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"):", "0777 if os.path.getsize(f) == 0: print \"'%s' is empty!\" %", "formattedlist = [] for name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"%", "in ('-g', '--generate'): generateMode = True if len(args) != 1:", "= True if hasDiff: sys.exit(1) if __name__ == \"__main__\": main()", "difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff = True if hasDiff:", "# included in the packaging of this file. Please review", "License version 3 as published by the Free Software #", "# Alternatively, this file may be used under the terms", "Contact: https://www.qt.io/licensing/ # # This file is part of Qt", "1: usage() sys.exit(2) rootdir = args[0] if generateMode: f =", "os.stat(f).st_mode & 0777 if os.path.getsize(f) == 0: print \"'%s' is", "https://www.qt.io/contact-us. # # GNU General Public License Usage # Alternatively,", "# Software or, alternatively, in accordance with the terms contained", "The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This", "with exceptions as appearing in the file LICENSE.GPL3-EXCEPT # included", "o in ('-h', '--help'): usage() sys.exit(0) if o in ('-g',", "commercial Qt licenses may use this file in # accordance", "the contact form at https://www.qt.io/contact-us. # # GNU General Public", "\"Usage: %s [-g | --generate] <dir>\" % os.path.basename(sys.argv[0]) def main():", "len(args) != 1: usage() sys.exit(2) rootdir = args[0] if generateMode:", "'generate']) except: print str(err) usage() sys.exit(2) for o, a in", "published by the Free Software # Foundation with exceptions as", "this file in # accordance with the commercial license agreement", "For further # information use the contact form at https://www.qt.io/contact-us.", "# # GNU General Public License Usage # Alternatively, this", "False for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff", "in the file LICENSE.GPL3-EXCEPT # included in the packaging of", "sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif sys.platform.startswith('win'): filename = 'makeinstall.windows' elif", "= os.path.join(root,file) perm = os.stat(f).st_mode & 0777 if os.path.getsize(f) ==", "fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff = True if hasDiff: sys.exit(1) if", "print \"Unsupported platform: \", sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return", "os.walk(rootdir): for file in (subFolders + files): f = os.path.join(root,file)", "generateReference(rootdir): fileDict = {} for root, subFolders, files in os.walk(rootdir):", "(C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ #", "Public License requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################", "in # accordance with the commercial license agreement provided with", "& 0777 if os.path.getsize(f) == 0: print \"'%s' is empty!\"", "license agreement provided with the # Software or, alternatively, in", "with the terms contained in # a written agreement between", "# General Public License version 3 as published by the", "be used under the terms of the GNU # General", "sys.stdout.write(line) hasDiff = True if hasDiff: sys.exit(1) if __name__ ==", "Software or, alternatively, in accordance with the terms contained in", "if sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif sys.platform.startswith('win'): filename = 'makeinstall.windows'", "in # a written agreement between you and The Qt", "empty!\" % f fileDict[f[len(rootdir)+1:]] = perm # generate new list", "the GNU General Public License requirements will # be met:", "GNU General Public License requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html.", "This file is part of Qt Creator. # # Commercial", "General Public License Usage # Alternatively, this file may be", "the terms of the GNU # General Public License version", "\"Do not forget to commit\", referenceFile() else: hasDiff = False", "a written agreement between you and The Qt Company. For", "def main(): generateMode = False try: opts, args = getopt.gnu_getopt(sys.argv[1:],", "try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except: print", "or, alternatively, in accordance with the terms contained in #", "Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file", "# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT", "accordance with the terms contained in # a written agreement", "('-h', '--help'): usage() sys.exit(0) if o in ('-g', '--generate'): generateMode", "% os.path.basename(sys.argv[0]) def main(): generateMode = False try: opts, args", "in opts: if o in ('-h', '--help'): usage() sys.exit(0) if", "in the packaging of this file. Please review the following", "file may be used under the terms of the GNU", "[] for line in f: filelist.append(line) f.close() return filelist def", "exceptions as appearing in the file LICENSE.GPL3-EXCEPT # included in", "https://www.qt.io/licensing/ # # This file is part of Qt Creator.", "Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part", "as published by the Free Software # Foundation with exceptions", "Usage # Alternatively, this file may be used under the", "Software # Foundation with exceptions as appearing in the file", "else: print \"Unsupported platform: \", sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe()))", "sys.platform.startswith('win'): filename = 'makeinstall.windows' elif sys.platform == 'darwin': filename =", "filename) def readReferenceFile(): # read file with old diff f", "Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is", "2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # #", "{} for root, subFolders, files in os.walk(rootdir): for file in", "name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name)) return formattedlist;", "General Public License version 3 as published by the Free", "licensing terms # and conditions see https://www.qt.io/terms-conditions. For further #", "Free Software # Foundation with exceptions as appearing in the", "in (subFolders + files): f = os.path.join(root,file) perm = os.stat(f).st_mode", "sys.platform == 'darwin': filename = 'makeinstall.darwin' else: print \"Unsupported platform:", "# GNU General Public License Usage # Alternatively, this file", "os.path.join(root,file) perm = os.stat(f).st_mode & 0777 if os.path.getsize(f) == 0:", "[] for name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name))", "file in (subFolders + files): f = os.path.join(root,file) perm =", "included in the packaging of this file. Please review the", "may use this file in # accordance with the commercial", "= [] for line in f: filelist.append(line) f.close() return filelist", "= {} for root, subFolders, files in os.walk(rootdir): for file", "General Public License requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html. #", "met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os import sys import stat", "%s [-g | --generate] <dir>\" % os.path.basename(sys.argv[0]) def main(): generateMode", "# information use the contact form at https://www.qt.io/contact-us. # #", "line in f: filelist.append(line) f.close() return filelist def generateReference(rootdir): fileDict", "commit\", referenceFile() else: hasDiff = False for line in difflib.unified_diff(readReferenceFile(),", "Public License version 3 as published by the Free Software", "as appearing in the file LICENSE.GPL3-EXCEPT # included in the", "GNU # General Public License version 3 as published by", "information to ensure the GNU General Public License requirements will", "['help', 'generate']) except: print str(err) usage() sys.exit(2) for o, a", "'r'); filelist = [] for line in f: filelist.append(line) f.close()", "filelist = [] for line in f: filelist.append(line) f.close() return", "for root, subFolders, files in os.walk(rootdir): for file in (subFolders", "# Licensees holding valid commercial Qt licenses may use this", "GNU General Public License Usage # Alternatively, this file may", "fileDict[f[len(rootdir)+1:]] = perm # generate new list formattedlist = []", "agreement between you and The Qt Company. For licensing terms", "line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff = True", "Please review the following # information to ensure the GNU", "Licensees holding valid commercial Qt licenses may use this file", "= args[0] if generateMode: f = open(referenceFile(), 'w') for item", "%s\\n\"% (perm, name)) return formattedlist; def usage(): print \"Usage: %s", "hasDiff = True if hasDiff: sys.exit(1) if __name__ == \"__main__\":", "f = open(referenceFile(), 'w') for item in generateReference(rootdir): f.write(item) f.close()", "(subFolders + files): f = os.path.join(root,file) perm = os.stat(f).st_mode &", "\"'%s' is empty!\" % f fileDict[f[len(rootdir)+1:]] = perm # generate", "def usage(): print \"Usage: %s [-g | --generate] <dir>\" %", "the following # information to ensure the GNU General Public", "old diff f = open(referenceFile(), 'r'); filelist = [] for", "True if len(args) != 1: usage() sys.exit(2) rootdir = args[0]", "f = open(referenceFile(), 'r'); filelist = [] for line in", "if generateMode: f = open(referenceFile(), 'w') for item in generateReference(rootdir):", "return formattedlist; def usage(): print \"Usage: %s [-g | --generate]", "between you and The Qt Company. For licensing terms #", "in generateReference(rootdir): f.write(item) f.close() print \"Do not forget to commit\",", "def readReferenceFile(): # read file with old diff f =", "is part of Qt Creator. # # Commercial License Usage", "f.close() return filelist def generateReference(rootdir): fileDict = {} for root,", "'makeinstall.windows' elif sys.platform == 'darwin': filename = 'makeinstall.darwin' else: print", "Public License Usage # Alternatively, this file may be used", "return filelist def generateReference(rootdir): fileDict = {} for root, subFolders,", "inspect import getopt def referenceFile(): if sys.platform.startswith('linux'): filename = 'makeinstall.linux'", "% f fileDict[f[len(rootdir)+1:]] = perm # generate new list formattedlist", "generateMode = False try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help',", "packaging of this file. Please review the following # information", "Commercial License Usage # Licensees holding valid commercial Qt licenses", "open(referenceFile(), 'w') for item in generateReference(rootdir): f.write(item) f.close() print \"Do", "filename = 'makeinstall.linux' elif sys.platform.startswith('win'): filename = 'makeinstall.windows' elif sys.platform", "filename = 'makeinstall.windows' elif sys.platform == 'darwin': filename = 'makeinstall.darwin'", "print str(err) usage() sys.exit(2) for o, a in opts: if", "sys.exit(2) rootdir = args[0] if generateMode: f = open(referenceFile(), 'w')", "'w') for item in generateReference(rootdir): f.write(item) f.close() print \"Do not", "contained in # a written agreement between you and The", "############################################################################ # # Copyright (C) 2016 The Qt Company Ltd.", "# # This file is part of Qt Creator. #", "version 3 as published by the Free Software # Foundation", "further # information use the contact form at https://www.qt.io/contact-us. #", "import difflib import inspect import getopt def referenceFile(): if sys.platform.startswith('linux'):", "Qt Creator. # # Commercial License Usage # Licensees holding", "agreement provided with the # Software or, alternatively, in accordance", "o, a in opts: if o in ('-h', '--help'): usage()", "use the contact form at https://www.qt.io/contact-us. # # GNU General", "alternatively, in accordance with the terms contained in # a", "f fileDict[f[len(rootdir)+1:]] = perm # generate new list formattedlist =", "this file may be used under the terms of the", "sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name)) return formattedlist; def usage(): print", "perm # generate new list formattedlist = [] for name,", "appearing in the file LICENSE.GPL3-EXCEPT # included in the packaging", "\", sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename)", "opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except: print str(err)", "in accordance with the terms contained in # a written", "Creator. # # Commercial License Usage # Licensees holding valid", "diff f = open(referenceFile(), 'r'); filelist = [] for line", "file is part of Qt Creator. # # Commercial License", "import stat import difflib import inspect import getopt def referenceFile():", "is empty!\" % f fileDict[f[len(rootdir)+1:]] = perm # generate new", "to commit\", referenceFile() else: hasDiff = False for line in", "of the GNU # General Public License version 3 as", "sys.exit(0) if o in ('-g', '--generate'): generateMode = True if", "perm = os.stat(f).st_mode & 0777 if os.path.getsize(f) == 0: print", "# accordance with the commercial license agreement provided with the", "this file. Please review the following # information to ensure", "files in os.walk(rootdir): for file in (subFolders + files): f", "valid commercial Qt licenses may use this file in #", "file with old diff f = open(referenceFile(), 'r'); filelist =", "The Qt Company. For licensing terms # and conditions see", "licenses may use this file in # accordance with the", "for o, a in opts: if o in ('-h', '--help'):", "forget to commit\", referenceFile() else: hasDiff = False for line", "Company. For licensing terms # and conditions see https://www.qt.io/terms-conditions. For", "= 'makeinstall.windows' elif sys.platform == 'darwin': filename = 'makeinstall.darwin' else:", "args[0] if generateMode: f = open(referenceFile(), 'w') for item in", "import sys import stat import difflib import inspect import getopt", "Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/", "with old diff f = open(referenceFile(), 'r'); filelist = []", "else: hasDiff = False for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(),", "usage() sys.exit(0) if o in ('-g', '--generate'): generateMode = True", "= perm # generate new list formattedlist = [] for", "sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile():", "args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except: print str(err) usage()", "generate new list formattedlist = [] for name, perm in", "name)) return formattedlist; def usage(): print \"Usage: %s [-g |", "python ############################################################################ # # Copyright (C) 2016 The Qt Company", "def referenceFile(): if sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif sys.platform.startswith('win'): filename", "for line in f: filelist.append(line) f.close() return filelist def generateReference(rootdir):", "print \"'%s' is empty!\" % f fileDict[f[len(rootdir)+1:]] = perm #", "print \"Usage: %s [-g | --generate] <dir>\" % os.path.basename(sys.argv[0]) def", "generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff = True if hasDiff: sys.exit(1)", "os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile(): # read file", "# and conditions see https://www.qt.io/terms-conditions. For further # information use", "os.path.basename(sys.argv[0]) def main(): generateMode = False try: opts, args =", "'makeinstall.linux' elif sys.platform.startswith('win'): filename = 'makeinstall.windows' elif sys.platform == 'darwin':", "# read file with old diff f = open(referenceFile(), 'r');", "list formattedlist = [] for name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o", "getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except: print str(err) usage() sys.exit(2) for", "the terms contained in # a written agreement between you", "= [] for name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm,", "= False try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate'])", "# Contact: https://www.qt.io/licensing/ # # This file is part of", "readReferenceFile(): # read file with old diff f = open(referenceFile(),", "!= 1: usage() sys.exit(2) rootdir = args[0] if generateMode: f", "of this file. Please review the following # information to", "Alternatively, this file may be used under the terms of", "review the following # information to ensure the GNU General", "# This file is part of Qt Creator. # #", "use this file in # accordance with the commercial license", "information use the contact form at https://www.qt.io/contact-us. # # GNU", "f: filelist.append(line) f.close() return filelist def generateReference(rootdir): fileDict = {}", "= False for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line)", "filelist def generateReference(rootdir): fileDict = {} for root, subFolders, files", "formattedlist.append(\"%o %s\\n\"% (perm, name)) return formattedlist; def usage(): print \"Usage:", "item in generateReference(rootdir): f.write(item) f.close() print \"Do not forget to", "contact form at https://www.qt.io/contact-us. # # GNU General Public License", "== 'darwin': filename = 'makeinstall.darwin' else: print \"Unsupported platform: \",", "may be used under the terms of the GNU #", "'reference', filename) def readReferenceFile(): # read file with old diff", "(perm, name)) return formattedlist; def usage(): print \"Usage: %s [-g", "| --generate] <dir>\" % os.path.basename(sys.argv[0]) def main(): generateMode = False", "filename = 'makeinstall.darwin' else: print \"Unsupported platform: \", sys.platform sys.exit(-1)", "in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name)) return formattedlist; def usage():", "not forget to commit\", referenceFile() else: hasDiff = False for", "be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os import sys import", "under the terms of the GNU # General Public License", "('-g', '--generate'): generateMode = True if len(args) != 1: usage()", "= open(referenceFile(), 'r'); filelist = [] for line in f:", "at https://www.qt.io/contact-us. # # GNU General Public License Usage #", "a in opts: if o in ('-h', '--help'): usage() sys.exit(0)", "referenceFile(): if sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif sys.platform.startswith('win'): filename =", "usage(): print \"Usage: %s [-g | --generate] <dir>\" % os.path.basename(sys.argv[0])", "terms contained in # a written agreement between you and", "in f: filelist.append(line) f.close() return filelist def generateReference(rootdir): fileDict =", "Qt Company. For licensing terms # and conditions see https://www.qt.io/terms-conditions.", "# be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os import sys", "perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name)) return formattedlist; def", "# ############################################################################ import os import sys import stat import difflib", "in ('-h', '--help'): usage() sys.exit(0) if o in ('-g', '--generate'):", "and The Qt Company. For licensing terms # and conditions", "the commercial license agreement provided with the # Software or,", "#!/usr/bin/env python ############################################################################ # # Copyright (C) 2016 The Qt", "License requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import", "the packaging of this file. Please review the following #", "for name, perm in sorted(fileDict.iteritems()): formattedlist.append(\"%o %s\\n\"% (perm, name)) return", "see https://www.qt.io/terms-conditions. For further # information use the contact form", "import inspect import getopt def referenceFile(): if sys.platform.startswith('linux'): filename =", "requirements will # be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os", "if os.path.getsize(f) == 0: print \"'%s' is empty!\" % f", "'--generate'): generateMode = True if len(args) != 1: usage() sys.exit(2)", "following # information to ensure the GNU General Public License", "form at https://www.qt.io/contact-us. # # GNU General Public License Usage", "scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile(): #", "# # Copyright (C) 2016 The Qt Company Ltd. #", "if o in ('-h', '--help'): usage() sys.exit(0) if o in", "file in # accordance with the commercial license agreement provided", "return os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile(): # read file with", "import getopt def referenceFile(): if sys.platform.startswith('linux'): filename = 'makeinstall.linux' elif", "License Usage # Alternatively, this file may be used under", "# information to ensure the GNU General Public License requirements", "file. Please review the following # information to ensure the", "sys.exit(2) for o, a in opts: if o in ('-h',", "https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os import sys import stat import", "f.write(item) f.close() print \"Do not forget to commit\", referenceFile() else:", "main(): generateMode = False try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg',", "= open(referenceFile(), 'w') for item in generateReference(rootdir): f.write(item) f.close() print", "the # Software or, alternatively, in accordance with the terms", "rootdir = args[0] if generateMode: f = open(referenceFile(), 'w') for", "+ files): f = os.path.join(root,file) perm = os.stat(f).st_mode & 0777", "holding valid commercial Qt licenses may use this file in", "for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff =", "root, subFolders, files in os.walk(rootdir): for file in (subFolders +", "in os.walk(rootdir): for file in (subFolders + files): f =", "commercial license agreement provided with the # Software or, alternatively,", "part of Qt Creator. # # Commercial License Usage #", "Qt licenses may use this file in # accordance with", "accordance with the commercial license agreement provided with the #", "usage() sys.exit(2) rootdir = args[0] if generateMode: f = open(referenceFile(),", "for item in generateReference(rootdir): f.write(item) f.close() print \"Do not forget", "you and The Qt Company. For licensing terms # and", "used under the terms of the GNU # General Public", "For licensing terms # and conditions see https://www.qt.io/terms-conditions. For further", "referenceFile() else: hasDiff = False for line in difflib.unified_diff(readReferenceFile(), generateReference(rootdir),", "'--help'): usage() sys.exit(0) if o in ('-g', '--generate'): generateMode =", "sys import stat import difflib import inspect import getopt def", "sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename) def", "usage() sys.exit(2) for o, a in opts: if o in", "with the commercial license agreement provided with the # Software", "files): f = os.path.join(root,file) perm = os.stat(f).st_mode & 0777 if", "os.path.getsize(f) == 0: print \"'%s' is empty!\" % f fileDict[f[len(rootdir)+1:]]", "[-g | --generate] <dir>\" % os.path.basename(sys.argv[0]) def main(): generateMode =", "conditions see https://www.qt.io/terms-conditions. For further # information use the contact", "of Qt Creator. # # Commercial License Usage # Licensees", "and conditions see https://www.qt.io/terms-conditions. For further # information use the", "= os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile(): # read", "terms of the GNU # General Public License version 3", "f = os.path.join(root,file) perm = os.stat(f).st_mode & 0777 if os.path.getsize(f)", "False try: opts, args = getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except:", "elif sys.platform.startswith('win'): filename = 'makeinstall.windows' elif sys.platform == 'darwin': filename", "str(err) usage() sys.exit(2) for o, a in opts: if o", "# a written agreement between you and The Qt Company.", "# Commercial License Usage # Licensees holding valid commercial Qt", "read file with old diff f = open(referenceFile(), 'r'); filelist", "License Usage # Licensees holding valid commercial Qt licenses may", "written agreement between you and The Qt Company. For licensing", "generateMode: f = open(referenceFile(), 'w') for item in generateReference(rootdir): f.write(item)", "in difflib.unified_diff(readReferenceFile(), generateReference(rootdir), fromfile=referenceFile(), tofile=\"generated\"): sys.stdout.write(line) hasDiff = True if", "Usage # Licensees holding valid commercial Qt licenses may use", "new list formattedlist = [] for name, perm in sorted(fileDict.iteritems()):", "'hg', ['help', 'generate']) except: print str(err) usage() sys.exit(2) for o,", "\"Unsupported platform: \", sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests',", "tofile=\"generated\"): sys.stdout.write(line) hasDiff = True if hasDiff: sys.exit(1) if __name__", "the GNU # General Public License version 3 as published", "file LICENSE.GPL3-EXCEPT # included in the packaging of this file.", "= os.stat(f).st_mode & 0777 if os.path.getsize(f) == 0: print \"'%s'", "= 'makeinstall.linux' elif sys.platform.startswith('win'): filename = 'makeinstall.windows' elif sys.platform ==", "with the # Software or, alternatively, in accordance with the", "LICENSE.GPL3-EXCEPT # included in the packaging of this file. Please", "# generate new list formattedlist = [] for name, perm", "= 'makeinstall.darwin' else: print \"Unsupported platform: \", sys.platform sys.exit(-1) scriptDir", "# Copyright (C) 2016 The Qt Company Ltd. # Contact:", "= getopt.gnu_getopt(sys.argv[1:], 'hg', ['help', 'generate']) except: print str(err) usage() sys.exit(2)", "= True if len(args) != 1: usage() sys.exit(2) rootdir =", "def generateReference(rootdir): fileDict = {} for root, subFolders, files in", "will # be met: https://www.gnu.org/licenses/gpl-3.0.html. # ############################################################################ import os import", "<dir>\" % os.path.basename(sys.argv[0]) def main(): generateMode = False try: opts,", "f.close() print \"Do not forget to commit\", referenceFile() else: hasDiff", "os import sys import stat import difflib import inspect import", "for file in (subFolders + files): f = os.path.join(root,file) perm", "stat import difflib import inspect import getopt def referenceFile(): if", "open(referenceFile(), 'r'); filelist = [] for line in f: filelist.append(line)", "############################################################################ import os import sys import stat import difflib import", "platform: \", sys.platform sys.exit(-1) scriptDir = os.path.dirname(inspect.getfile(inspect.currentframe())) return os.path.join(scriptDir,'..','tests', 'reference',", "'makeinstall.darwin' else: print \"Unsupported platform: \", sys.platform sys.exit(-1) scriptDir =", "generateMode = True if len(args) != 1: usage() sys.exit(2) rootdir", "== 0: print \"'%s' is empty!\" % f fileDict[f[len(rootdir)+1:]] =", "o in ('-g', '--generate'): generateMode = True if len(args) !=", "except: print str(err) usage() sys.exit(2) for o, a in opts:", "the Free Software # Foundation with exceptions as appearing in", "# # Commercial License Usage # Licensees holding valid commercial", "opts: if o in ('-h', '--help'): usage() sys.exit(0) if o", "terms # and conditions see https://www.qt.io/terms-conditions. For further # information", "if o in ('-g', '--generate'): generateMode = True if len(args)", "generateReference(rootdir): f.write(item) f.close() print \"Do not forget to commit\", referenceFile()", "by the Free Software # Foundation with exceptions as appearing", "difflib import inspect import getopt def referenceFile(): if sys.platform.startswith('linux'): filename", "fileDict = {} for root, subFolders, files in os.walk(rootdir): for", "--generate] <dir>\" % os.path.basename(sys.argv[0]) def main(): generateMode = False try:", "elif sys.platform == 'darwin': filename = 'makeinstall.darwin' else: print \"Unsupported", "to ensure the GNU General Public License requirements will #", "os.path.join(scriptDir,'..','tests', 'reference', filename) def readReferenceFile(): # read file with old", "provided with the # Software or, alternatively, in accordance with", "import os import sys import stat import difflib import inspect", "Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT #", "ensure the GNU General Public License requirements will # be", "filelist.append(line) f.close() return filelist def generateReference(rootdir): fileDict = {} for" ]
[ "experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name + \".pth\", )", "does not include specifications file \" + '\"specs.json\"'.format(experiment_directory) ) return", "data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch = __import__( \"networks.\" + experiment_specs[\"NetworkArch\"],", "load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join( experiment_directory, latent_codes_subdir, checkpoint + \".pth\"", "optimizations_codes_subdir = \"Codes\" specifications_filename = \"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir", "get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name,", "Reserved. import json import os import torch model_params_subdir = \"ModelParameters\"", "dict \"{}\" does not exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return", "= torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch =", "create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False):", "dataset, class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir,", "raise Exception( \"The experiment directory ({}) does not include a", "get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and not", "for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings, embedding_dim", "= os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir)", "renders_subdir = \"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir", "return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir,", "dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent and not os.path.isdir(dir):", "def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset,", "def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return os.path.join(", "num_vecs = data[\"latent_codes\"].size()[0] lat_vecs = [] for i in range(num_vecs):", "os.path.isdir(dir): os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir,", "checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent and", "= \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir =", "return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir) if", "decoder) return (decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join(", "= \"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir =", "os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir)", "instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name,", "class_name, instance_name + \".ply\", ) def get_reconstructed_code_filename( experiment_dir, epoch, dataset,", "str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name + \".ply\", ) def get_reconstructed_code_filename(", "evaluation_subdir = \"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir", "create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_normalization_params_filename( data_dir,", "and not os.path.isdir(dir): os.makedirs(dir) return dir def get_normalization_params_filename( data_dir, dataset_name,", "reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir", "get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return os.path.join( experiment_dir,", "checkpoint) ) data = torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs =", ") def get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return", "reconstruction_codes_subdir, dataset, class_name, instance_name + \".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint,", "lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename(", "return dir def get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name ): return", "latent_codes_subdir = \"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir", "+ \".pth\" ) if not os.path.isfile(filename): raise Exception( \"The experiment", "not os.path.isdir(dir): os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir =", "\"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename = \"Logs.pth\"", "\"Codes\" specifications_filename = \"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir = \"Evaluation\"", "import os import torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\"", "def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and", "str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name + \".pth\", ) def get_evaluation_dir(experiment_dir,", "experiment directory ({}) does not include specifications file \" +", "= [] for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else:", "return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name +", "checkpoint) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def", "torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename)", "does not exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def", "return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir) if", "= load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint):", "return lat_vecs else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings,", "experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda()", "num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return", "+ \".ply\", ) def get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name, instance_name", "= os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return", "os.path.isfile(filename): raise Exception( \"The experiment directory ({}) does not include", "dataset, class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir,", "state dict \"{}\" does not exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"])", "get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and not", "data = torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs", "checkpoint, decoder): filename = os.path.join( experiment_directory, model_params_subdir, checkpoint + \".pth\"", "({}) does not include a latent code file\" + \"", "dir def get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name ): return os.path.join(", "data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch", "class_name, instance_name ): return os.path.join( data_dir, normalization_param_subdir, dataset_name, class_name, instance_name", "data_source_map_filename = \".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir", "\"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir = \"Optimizations\"", "not os.path.isdir(dir): os.makedirs(dir) return dir def get_normalization_params_filename( data_dir, dataset_name, class_name,", "return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name, instance_name", "= data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def", "= \"Codes\" specifications_filename = \"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir =", "torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder, epoch) def", "= os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return", "class_name, instance_name + \".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir", "Facebook. All Rights Reserved. import json import os import torch", "def build_decoder(experiment_directory, experiment_specs): arch = __import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"]", "= build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder = torch.nn.DataParallel(decoder) epoch =", "arch = __import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size =", "specifications file \" + '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def load_model_parameters(experiment_directory,", "os import torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir", "does not include a latent code file\" + \" for", "if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir,", "not exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory,", "experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name + \".ply\", )", "epoch) def load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join( experiment_directory, latent_codes_subdir, checkpoint", "def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and", "surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def", "= __import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"]", "os.path.isdir(dir): os.makedirs(dir) return dir def get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name", "decoder = torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder,", "i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings, embedding_dim =", "= \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir =", "= \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory,", "# Copyright 2004-present Facebook. All Rights Reserved. import json import", "experiment_specs) if data_parallel: decoder = torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint,", "epoch, dataset, class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch),", "code file\" + \" for checkpoint '{}'\".format(experiment_directory, checkpoint) ) data", "filename = os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename): raise Exception( \"The", "\"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\"", "def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint) if", "reconstruction_codes_subdir = \"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir", "embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def", "decoder def load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True ): decoder =", "return os.path.join( data_dir, normalization_param_subdir, dataset_name, class_name, instance_name + \".npz\", )", "optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename", "optimizer_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def", "if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir,", "include specifications file \" + '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def", "class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset,", "create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and not os.path.isdir(dir):", "#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import", "data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return", "torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\"", "decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder( experiment_directory, experiment_specs,", "Rights Reserved. import json import os import torch model_params_subdir =", "data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir):", "build_decoder(experiment_directory, experiment_specs): arch = __import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] )", "reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name + \".pth\", ) def", "experiment_dir, epoch, dataset, class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir,", "a latent code file\" + \" for checkpoint '{}'\".format(experiment_directory, checkpoint)", "fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return", "checkpoint '{}'\".format(experiment_directory, checkpoint) ) data = torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor):", "build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder = torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory,", "torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch = __import__(", "lat_vecs = [] for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs", "<reponame>huajian1069/non-convex_optimisation #!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved.", "= \"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir =", "\"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename):", "else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"])", "instance_name ): return os.path.join( data_dir, normalization_param_subdir, dataset_name, class_name, instance_name +", "file\" + \" for checkpoint '{}'\".format(experiment_directory, checkpoint) ) data =", "\"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\"", "= os.path.join( experiment_directory, latent_codes_subdir, checkpoint + \".pth\" ) if not", "dataset, class_name, instance_name + \".ply\", ) def get_reconstructed_code_filename( experiment_dir, epoch,", "get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and not", "os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch, dataset, class_name, instance_name ):", "file \" + '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint,", "\"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir = \"Codes\"", "evaluation_subdir, checkpoint) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir", "reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name + \".ply\", ) def", "dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent", "model_params_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename): raise Exception('model", "return (decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join( experiment_directory,", "load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint): filename", "os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir", "import json import os import torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir", "Exception('model state dict \"{}\" does not exist'.format(filename)) data = torch.load(filename)", "os.path.isdir(dir): os.makedirs(dir) return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir,", "sdf_samples_subdir = \"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir", ") if not os.path.isfile(filename): raise Exception('model state dict \"{}\" does", "not include a latent code file\" + \" for checkpoint", "\"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir = \"Codes\"", "({}) does not include specifications file \" + '\"specs.json\"'.format(experiment_directory) )", "instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name,", "latent_codes_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename): raise Exception(", "if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_model_params_dir(experiment_dir,", "\"{}\" does not exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"]", "= \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename =", "load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename): raise Exception(", "instance_name + \".ply\", ) def get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name,", "reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir", "if data_parallel: decoder = torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint, decoder)", "\"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir = \"SurfaceSamples\"", "lat_vecs else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim)", "os.path.isfile(filename): raise Exception('model state dict \"{}\" does not exist'.format(filename)) data", "All Rights Reserved. import json import os import torch model_params_subdir", "os.makedirs(dir) return dir def get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name ):", "+ \".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir,", "torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs = []", "return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch = __import__( \"networks.\" +", "logs_filename = \"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir", "arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True", "epoch = load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder, epoch) def load_latent_vectors(experiment_directory,", "optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename = \"specs.json\" data_source_map_filename", "not include specifications file \" + '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename))", "experiment_directory, latent_codes_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename): raise", "dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent", "return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir) if", ") return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder): filename = os.path.join(", "checkpoint): filename = os.path.join( experiment_directory, latent_codes_subdir, checkpoint + \".pth\" )", "python3 # Copyright 2004-present Facebook. All Rights Reserved. import json", "experiment_directory, experiment_specs, checkpoint, data_parallel=True ): decoder = build_decoder(experiment_directory, experiment_specs) if", "\" + '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder):", "= torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs =", "): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name", "instance_name + \".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir =", "in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape", "\" for checkpoint '{}'\".format(experiment_directory, checkpoint) ) data = torch.load(filename) if", "\"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir = \"Reconstructions\"", "\".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir = \"Renders\"", "include a latent code file\" + \" for checkpoint '{}'\".format(experiment_directory,", "embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach()", "specifications_filename = \"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir", "experiment_specs, checkpoint, data_parallel=True ): decoder = build_decoder(experiment_directory, experiment_specs) if data_parallel:", ") data = torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0]", "checkpoint, data_parallel=True ): decoder = build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder", "\"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename)", "raise Exception( \"The experiment directory ({}) does not include specifications", "torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs = [] for i in", "= os.path.join( experiment_directory, model_params_subdir, checkpoint + \".pth\" ) if not", "\"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename = \"specs.json\" data_source_map_filename = \".datasources.json\"", "experiment_specs): arch = __import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size", "decoder = build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder = torch.nn.DataParallel(decoder) epoch", "\"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename = \"specs.json\"", "**experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True ):", "def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and", "\"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename", "not os.path.isfile(filename): raise Exception('model state dict \"{}\" does not exist'.format(filename))", "\"Meshes\" reconstruction_codes_subdir = \"Codes\" optimizations_subdir = \"Optimizations\" optimizations_meshes_subdir = \"Meshes\"", "= torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir,", "= \"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename = \"specs.json\" data_source_map_filename =", "optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir", "and not os.path.isdir(dir): os.makedirs(dir) return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir", "latent_codes_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def", "[] for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings,", "model_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def", "os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir)", "): decoder = build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder = torch.nn.DataParallel(decoder)", "= \"LatentCodes\" logs_filename = \"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir =", "): return os.path.join( data_dir, normalization_param_subdir, dataset_name, class_name, instance_name + \".npz\",", "): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name", "dir = os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir)", "os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir", "= experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder(", "= os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return", "data_parallel: decoder = torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint, decoder) return", "os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name + \".pth\",", "directory ({}) does not include specifications file \" + '\"specs.json\"'.format(experiment_directory)", "+ experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size,", "Exception( \"The experiment directory ({}) does not include a latent", "range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs", "dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent", "def load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True ): decoder = build_decoder(experiment_directory,", "checkpoint + \".pth\" ) if not os.path.isfile(filename): raise Exception('model state", "raise Exception('model state dict \"{}\" does not exist'.format(filename)) data =", "lat_vecs = torch.nn.Embedding(num_embeddings, embedding_dim) lat_vecs.load_state_dict(data[\"latent_codes\"]) return lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return", "Copyright 2004-present Facebook. All Rights Reserved. import json import os", "\".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir,", "json import os import torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir =", "import torch model_params_subdir = \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir =", "experiment directory ({}) does not include a latent code file\"", "reconstruction_meshes_subdir, dataset, class_name, instance_name + \".ply\", ) def get_reconstructed_code_filename( experiment_dir,", "if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_normalization_params_filename(", "for checkpoint '{}'\".format(experiment_directory, checkpoint) ) data = torch.load(filename) if isinstance(data[\"latent_codes\"],", "\"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\"", "= \"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir =", "\".pth\" ) if not os.path.isfile(filename): raise Exception('model state dict \"{}\"", "create_if_nonexistent=False): dir = os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and not os.path.isdir(dir):", "checkpoint, decoder) return (decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint): filename =", "not os.path.isdir(dir): os.makedirs(dir) return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir =", "= \".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir =", "exist'.format(filename)) data = torch.load(filename) decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs):", "2004-present Facebook. All Rights Reserved. import json import os import", "\".ply\", ) def get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name, instance_name ):", "get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent", "+ '\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder): filename", "if not os.path.isfile(filename): raise Exception('model state dict \"{}\" does not", "filename = os.path.join( experiment_directory, model_params_subdir, checkpoint + \".pth\" ) if", "\"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"] decoder =", "specifications_filename) if not os.path.isfile(filename): raise Exception( \"The experiment directory ({})", "and not os.path.isdir(dir): os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False): dir", "os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir", "dataset, class_name, instance_name + \".pth\", ) def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False):", "get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name ): return os.path.join( data_dir, normalization_param_subdir,", "filename = os.path.join( experiment_directory, latent_codes_subdir, checkpoint + \".pth\" ) if", "dataset_name, class_name, instance_name ): return os.path.join( data_dir, normalization_param_subdir, dataset_name, class_name,", "(decoder, epoch) def load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join( experiment_directory, latent_codes_subdir,", "os.path.isdir(dir): os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir,", "+ \" for checkpoint '{}'\".format(experiment_directory, checkpoint) ) data = torch.load(filename)", "def get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return os.path.join(", "create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent and not", "def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename): raise", "\".pth\" ) if not os.path.isfile(filename): raise Exception( \"The experiment directory", "dir = os.path.join(experiment_dir, optimizer_params_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir)", "= \"Renders\" surface_samples_subdir = \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir =", "return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder): filename = os.path.join( experiment_directory,", "and not os.path.isdir(dir): os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir", "normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename =", "\"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir = \"SdfSamples\"", ") if not os.path.isfile(filename): raise Exception( \"The experiment directory ({})", "Exception( \"The experiment directory ({}) does not include specifications file", "get_reconstructed_code_filename( experiment_dir, epoch, dataset, class_name, instance_name ): return os.path.join( experiment_dir,", "= torch.nn.DataParallel(decoder) epoch = load_model_parameters(experiment_directory, checkpoint, decoder) return (decoder, epoch)", "= data[\"latent_codes\"].size()[0] lat_vecs = [] for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda())", "create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False):", "'{}'\".format(experiment_directory, checkpoint) ) data = torch.load(filename) if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs", "latent_size = experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def", "json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder): filename = os.path.join( experiment_directory, model_params_subdir,", "if not os.path.isfile(filename): raise Exception( \"The experiment directory ({}) does", "decoder.load_state_dict(data[\"model_state_dict\"]) return data[\"epoch\"] def build_decoder(experiment_directory, experiment_specs): arch = __import__( \"networks.\"", "data[\"latent_codes\"].size()[0] lat_vecs = [] for i in range(num_vecs): lat_vecs.append(data[\"latent_codes\"][i].cuda()) return", "not os.path.isdir(dir): os.makedirs(dir) return dir def get_latent_codes_dir(experiment_dir, create_if_nonexistent=False): dir =", "= \"Evaluation\" sdf_samples_subdir = \"SdfSamples\" renders_subdir = \"Renders\" surface_samples_subdir =", "dir = os.path.join(experiment_dir, latent_codes_subdir) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir)", "data_parallel=True ): decoder = build_decoder(experiment_directory, experiment_specs) if data_parallel: decoder =", "not os.path.isfile(filename): raise Exception( \"The experiment directory ({}) does not", "directory ({}) does not include a latent code file\" +", "os.path.join( experiment_directory, latent_codes_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename):", "= os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename): raise Exception( \"The experiment", "experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder( experiment_directory,", "\"The experiment directory ({}) does not include specifications file \"", "= \"Logs.pth\" reconstructions_subdir = \"Reconstructions\" reconstruction_meshes_subdir = \"Meshes\" reconstruction_codes_subdir =", "data_dir, dataset_name, class_name, instance_name ): return os.path.join( data_dir, normalization_param_subdir, dataset_name,", "def load_model_parameters(experiment_directory, checkpoint, decoder): filename = os.path.join( experiment_directory, model_params_subdir, checkpoint", "os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_meshes_subdir, dataset, class_name, instance_name + \".ply\",", "= \"Optimizations\" optimizations_meshes_subdir = \"Meshes\" optimizations_codes_subdir = \"Codes\" specifications_filename =", "training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename) if", "os.path.join( experiment_directory, model_params_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename):", "model_params_subdir = \"ModelParameters\" optimizer_params_subdir = \"OptimizerParameters\" latent_codes_subdir = \"LatentCodes\" logs_filename", ") latent_size = experiment_specs[\"CodeLength\"] decoder = arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder", "\"The experiment directory ({}) does not include a latent code", "class_name, instance_name ): return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset,", "decoder): filename = os.path.join( experiment_directory, model_params_subdir, checkpoint + \".pth\" )", "return os.path.join( experiment_dir, reconstructions_subdir, str(epoch), reconstruction_codes_subdir, dataset, class_name, instance_name +", "create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir) if create_if_nonexistent and not os.path.isdir(dir):", "def get_normalization_params_filename( data_dir, dataset_name, class_name, instance_name ): return os.path.join( data_dir,", "experiment_directory, model_params_subdir, checkpoint + \".pth\" ) if not os.path.isfile(filename): raise", "os.path.join(experiment_directory, specifications_filename) if not os.path.isfile(filename): raise Exception( \"The experiment directory", "load_model_parameters(experiment_directory, checkpoint, decoder): filename = os.path.join( experiment_directory, model_params_subdir, checkpoint +", "latent code file\" + \" for checkpoint '{}'\".format(experiment_directory, checkpoint) )", "= \"SurfaceSamples\" normalization_param_subdir = \"NormalizationParameters\" training_meshes_subdir = \"TrainingMeshes\" def load_experiment_specifications(experiment_directory):", "= \"specs.json\" data_source_map_filename = \".datasources.json\" evaluation_subdir = \"Evaluation\" sdf_samples_subdir =", "= arch.Decoder(latent_size, **experiment_specs[\"NetworkSpecs\"]).cuda() return decoder def load_decoder( experiment_directory, experiment_specs, checkpoint,", "checkpoint + \".pth\" ) if not os.path.isfile(filename): raise Exception( \"The", "lat_vecs.weight.data.detach() def get_data_source_map_filename(data_dir): return os.path.join(data_dir, data_source_map_filename) def get_reconstructed_mesh_filename( experiment_dir, epoch,", "lat_vecs.append(data[\"latent_codes\"][i].cuda()) return lat_vecs else: num_embeddings, embedding_dim = data[\"latent_codes\"][\"weight\"].shape lat_vecs =", "isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs = [] for i", "create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return dir def get_optimizer_params_dir(experiment_dir, create_if_nonexistent=False):", "= \"TrainingMeshes\" def load_experiment_specifications(experiment_directory): filename = os.path.join(experiment_directory, specifications_filename) if not", "def load_latent_vectors(experiment_directory, checkpoint): filename = os.path.join( experiment_directory, latent_codes_subdir, checkpoint +", "__import__( \"networks.\" + experiment_specs[\"NetworkArch\"], fromlist=[\"Decoder\"] ) latent_size = experiment_specs[\"CodeLength\"] decoder", "return decoder def load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True ): decoder", "os.path.join(experiment_dir, evaluation_subdir, checkpoint) if create_if_nonexistent and not os.path.isdir(dir): os.makedirs(dir) return", "+ \".pth\" ) if not os.path.isfile(filename): raise Exception('model state dict", "'\"specs.json\"'.format(experiment_directory) ) return json.load(open(filename)) def load_model_parameters(experiment_directory, checkpoint, decoder): filename =", "load_decoder( experiment_directory, experiment_specs, checkpoint, data_parallel=True ): decoder = build_decoder(experiment_directory, experiment_specs)", "if isinstance(data[\"latent_codes\"], torch.Tensor): num_vecs = data[\"latent_codes\"].size()[0] lat_vecs = [] for", ") def get_evaluation_dir(experiment_dir, checkpoint, create_if_nonexistent=False): dir = os.path.join(experiment_dir, evaluation_subdir, checkpoint)", "os.makedirs(dir) return dir def get_model_params_dir(experiment_dir, create_if_nonexistent=False): dir = os.path.join(experiment_dir, model_params_subdir)" ]
[ "import DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection import train_test_split", "EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets import", "verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save model configuration", "from EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator", "channels = 1 verbose = True print('--------------- Convolutional Dropout Model", "dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels) print('Training net...') model = ConvolutionalNNDropout(target_dimensions,", "print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset", "verbose = True print('--------------- Convolutional Dropout Model -------------------') print('Loading data...')", "= DataGenerator().fit(test_images, test_labels) print('Training net...') model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(),", "import resource_filename,resource_exists validation_split = 0.15 target_dimensions = (48, 48) channels", "from EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets", "as np from pkg_resources import resource_filename,resource_exists validation_split = 0.15 target_dimensions", "= True print('--------------- Convolutional Dropout Model -------------------') print('Loading data...') directory_path", "data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing training/testing data...') train_images, train_labels =", "= (48, 48) channels = 1 verbose = True print('---------------", "ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) #", "print('--------------- Convolutional Dropout Model -------------------') print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory')", "pkg_resources import resource_filename,resource_exists validation_split = 0.15 target_dimensions = (48, 48)", "import CSVDataLoader from EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout", "True print('--------------- Convolutional Dropout Model -------------------') print('Loading data...') directory_path =", "data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data() if verbose: dataset.print_data_details()", "0.15 target_dimensions = (48, 48) channels = 1 verbose =", "dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels) test_images, test_labels = dataset.get_test_data() test_gen", "test_images, test_labels = dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels) print('Training net...')", "CSVDataLoader from EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout from", "EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection import train_test_split import numpy as", "model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5),", "Convolutional Dropout Model -------------------') print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader", "validation_split = 0.15 target_dimensions = (48, 48) channels = 1", "batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save model configuration # model.export_model('output/conv2d_model.json','output/conv2d_weights.h5',\"output/conv2d_emotion_map.json\",", "data...') train_images, train_labels = dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels) test_images,", "= resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data() if", "test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save model configuration # model.export_model('output/conv2d_model.json','output/conv2d_weights.h5',\"output/conv2d_emotion_map.json\", emotion_map)", "import DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator import DataGenerator", "resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data() if verbose:", "dataset = data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing training/testing data...') train_images,", "Dropout Model -------------------') print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader =", "train_labels = dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels) test_images, test_labels =", "train_labels) test_images, test_labels = dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels) print('Training", "DataGenerator().fit(train_images, train_labels) test_images, test_labels = dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels)", "print('Preparing training/testing data...') train_images, train_labels = dataset.get_training_data() train_gen = DataGenerator().fit(train_images,", "= DataGenerator().fit(train_images, train_labels) test_images, test_labels = dataset.get_test_data() test_gen = DataGenerator().fit(test_images,", "train_gen = DataGenerator().fit(train_images, train_labels) test_images, test_labels = dataset.get_test_data() test_gen =", "= dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels) print('Training net...') model =", "DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator import DataGenerator from", "= 1 verbose = True print('--------------- Convolutional Dropout Model -------------------')", "test_labels = dataset.get_test_data() test_gen = DataGenerator().fit(test_images, test_labels) print('Training net...') model", "DataGenerator().fit(test_images, test_labels) print('Training net...') model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True)", "training/testing data...') train_images, train_labels = dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels)", "np from pkg_resources import resource_filename,resource_exists validation_split = 0.15 target_dimensions =", "from EmoPy.src.fermodel import FERModel from EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader", "= data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing training/testing data...') train_images, train_labels", "EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader from EmoPy.src.data_generator import", "EmoPy.src.fermodel import FERModel from EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader import", "DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection import train_test_split import", "FERModel from EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader from", "train_test_split import numpy as np from pkg_resources import resource_filename,resource_exists validation_split", "train_images, train_labels = dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels) test_images, test_labels", "import ConvolutionalNNDropout from sklearn.model_selection import train_test_split import numpy as np", "model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save model configuration #", "test_gen = DataGenerator().fit(test_images, test_labels) print('Training net...') model = ConvolutionalNNDropout(target_dimensions, channels,", "= ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15)", "from EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection import train_test_split import numpy", "-------------------') print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split)", "verbose: dataset.print_data_details() print('Preparing training/testing data...') train_images, train_labels = dataset.get_training_data() train_gen", "if verbose: dataset.print_data_details() print('Preparing training/testing data...') train_images, train_labels = dataset.get_training_data()", "Model -------------------') print('Loading data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path,", "target_dimensions = (48, 48) channels = 1 verbose = True", "dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save model", "from EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection", "from sklearn.model_selection import train_test_split import numpy as np from pkg_resources", "net...') model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions,", "<reponame>Rahmatullina/FinalYearProject<filename>EmoPy/EmoPy/examples/convolutional_dropout_model.py from EmoPy.src.fermodel import FERModel from EmoPy.src.directory_data_loader import DirectoryDataLoader from", "sklearn.model_selection import train_test_split import numpy as np from pkg_resources import", "DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing training/testing", "(48, 48) channels = 1 verbose = True print('--------------- Convolutional", "resource_filename,resource_exists validation_split = 0.15 target_dimensions = (48, 48) channels =", "print('Training net...') model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5),", "from pkg_resources import resource_filename,resource_exists validation_split = 0.15 target_dimensions = (48,", "test_labels) print('Training net...') model = ConvolutionalNNDropout(target_dimensions, channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions,", "= dataset.get_training_data() train_gen = DataGenerator().fit(train_images, train_labels) test_images, test_labels = dataset.get_test_data()", "import train_test_split import numpy as np from pkg_resources import resource_filename,resource_exists", "numpy as np from pkg_resources import resource_filename,resource_exists validation_split = 0.15", "= DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing", "directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset = data_loader.load_data()", "EmoPy.src.data_generator import DataGenerator from EmoPy.src.neuralnets import ConvolutionalNNDropout from sklearn.model_selection import", "import FERModel from EmoPy.src.directory_data_loader import DirectoryDataLoader from EmoPy.src.csv_data_loader import CSVDataLoader", "import numpy as np from pkg_resources import resource_filename,resource_exists validation_split =", "dataset.print_data_details() print('Preparing training/testing data...') train_images, train_labels = dataset.get_training_data() train_gen =", "1 verbose = True print('--------------- Convolutional Dropout Model -------------------') print('Loading", "48) channels = 1 verbose = True print('--------------- Convolutional Dropout", "validation_split=validation_split) dataset = data_loader.load_data() if verbose: dataset.print_data_details() print('Preparing training/testing data...')", "= 0.15 target_dimensions = (48, 48) channels = 1 verbose", "ConvolutionalNNDropout from sklearn.model_selection import train_test_split import numpy as np from", "data...') directory_path = resource_filename('EmoPy.examples','image_data/sample_image_directory') data_loader = DirectoryDataLoader(datapath=directory_path, validation_split=validation_split) dataset =", "channels, dataset.get_emotion_index_map(), verbose=True) model.fit_generator(train_gen.generate(target_dimensions, batch_size=5), test_gen.generate(target_dimensions, batch_size=5), epochs=15) # Save" ]
[ "jinja2.ext import Extension class TestExtension(Extension): tags = {'test_ext'} def parse(self,", "Extension class TestExtension(Extension): tags = {'test_ext'} def parse(self, parser): return", "import nodes from jinja2.ext import Extension class TestExtension(Extension): tags =", "<filename>ENV/lib/python3.6/site-packages/pyramid_jinja2/tests/extensions.py from jinja2 import nodes from jinja2.ext import Extension class", "jinja2 import nodes from jinja2.ext import Extension class TestExtension(Extension): tags", "class TestExtension(Extension): tags = {'test_ext'} def parse(self, parser): return nodes.Const(\"This", "= {'test_ext'} def parse(self, parser): return nodes.Const(\"This is test extension\")", "tags = {'test_ext'} def parse(self, parser): return nodes.Const(\"This is test", "import Extension class TestExtension(Extension): tags = {'test_ext'} def parse(self, parser):", "TestExtension(Extension): tags = {'test_ext'} def parse(self, parser): return nodes.Const(\"This is", "from jinja2 import nodes from jinja2.ext import Extension class TestExtension(Extension):", "from jinja2.ext import Extension class TestExtension(Extension): tags = {'test_ext'} def", "nodes from jinja2.ext import Extension class TestExtension(Extension): tags = {'test_ext'}" ]
[ "declated it in the DBIRTH newValue4 = metric.int_value print (\"CMD", "deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\" + myNodeName,", "LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A", "# Publish a message Input 2 #publishBirth() elif metric.name ==", "our DBIRTH message and we're emulating an output. # So,", "we declated it in the DBIRTH newValue = metric.string_value print", "pyds.get_string() to get the string content. py_nvosd_text_params.display_text = \"Frame Number={}", "pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64():", "\"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\",", "2020, NVIDIA CORPORATION. All rights reserved. # # Permission is", "totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\" + myNodeName", "# Create the node death payload deathPayload = sparkplug.getNodeDeathPayload() #", "PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0,", "0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\",", "break obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next except StopIteration: break #", "PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer = info.get_buffer() if not gst_buffer:", "run inferencing on camera's output, # behaviour of inferencing is", "= 49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA =", "\"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\" Unable to create v4l2src capsfilter", "feed gstreamer bus mesages to it loop = GObject.MainLoop() bus", "addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10,", "to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) # Text background color", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "-> nvosd -> video-renderer print(\"Linking elements in the Pipeline \\n\")", "Create nvstreammux instance to form batches from one or more", "an NCMD used to tell a device/client application to reboot", "Input2\" or metric.alias == AliasMap.Device_Input2: # This is a metric", "received from the server. ###################################################################### def on_message(client, userdata, msg): print(\"Message", "sink: sys.stderr.write(\" Unable to create egl sink \\n\") print(\"Playing cam", "newValue7 = metric.int_value print (\"CMD message for output/Device Input7 -", "1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync = false", "57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT = 54", "permission notice shall be included in # all copies or", "global myNodeName # Subscribing in on_connect() means that if we", "a message Input 1 #publishBirth() elif metric.name == \"output/Device Input1\"", "MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\",", "Object7 = obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10", "implemented in this example\") elif metric.name == \"Node Control/Rebirth\" or", "newValue9) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size = 10 # set(red, green,", "print(\"Playing cam %s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\"))", "PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0,", "\"/\" + myDeviceName, totalByteArray, 0, False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data):", "portions of the Software. # # THE SOFTWARE IS PROVIDED", "obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8 = obj_counter[newValue8]", "Text background color py_nvosd_text_params.set_bg_clr = 1 # set(red, green, blue,", "to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie)", "0 Object7 = 0 Object8 = 0 Object9 = 0", "1.0, 1.0, 1.0) # Text background color py_nvosd_text_params.set_bg_clr = 1", "7 Device_Metric3 = 8 Device_Metric4 = 9 Device_counter1 = 10", "it in the DBIRTH newValue2 = metric.int_value print (\"CMD message", "any person obtaining a # copy of this software and", "= \"Frame Number={} Number of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP],", "= 23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT =", "to # the sink pad of the osd element, since", "by that time, the buffer would have # had got", "0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\",", "20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE = 17", "# Now set the offsets where the string should appear", "== \"output/Device Metric2\" or metric.alias == AliasMap.Device_Metric2: # This is", "it in the DBIRTH newValue = metric.string_value print (\"CMD message", "convertor to convert from NV12 to RGBA as required by", "create v4l2src capsfilter \\n\") print(\"Creating Video Converter \\n\") # Adding", "import paho.mqtt.client as mqtt import sparkplug_b as sparkplug import time", "we fake a full reboot with a republishing of the", "metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\" Unable to", "+ myNodeName, byteArray, 0, False) ###################################################################### ###################################################################### # Publish the", "inferencing on camera's output, # behaviour of inferencing is set", "the DBIRTH newValue2 = metric.int_value print (\"CMD message for output/Device", "\"onscreendisplay\") if not nvosd: sys.stderr.write(\" Unable to create nvosd \\n\")", "= 6 Device_Metric2 = 7 Device_Metric3 = 8 Device_Metric4 =", "print(\"Unable to get GstBuffer \") return # Retrieve batch metadata", "Controls addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node", "import pyds # Application Variables serverUrl = \"localhost\" myGroupId =", "0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\",", "Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String,", "publishBirth() elif metric.name == \"Node Control/Reboot\" or metric.alias == AliasMap.Reboot:", "= 26 Device_Output6 = 27 Device_Output7 = 28 Device_Output8 =", "py_nvosd_text_params.set_bg_clr = 1 # set(red, green, blue, alpha); set to", "NBIRTH or DBIRTH. This is why the application must send", "\"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\",", "remains in # the C code so downstream plugins can", "of how we declated it in the DBIRTH newValue6 =", "= metric.int_value print (\"CMD message for output/Device Input4 - New", "addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3,", "tokens[3] == myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in", "69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD = 66", "= 8 Device_Metric4 = 9 Device_counter1 = 10 Device_counter2 =", "return Gst.PadProbeReturn.OK ###################################################################### def main(args): # Check input arguments if", "messages. publishBirth() elif metric.name == \"Node Control/Reboot\" or metric.alias ==", "elements together # v4l2src -> nvvideoconvert -> mux -> #", "PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT", "= 27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK =", "HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #", "Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink: sys.stderr.write(\" Unable to create egl", "- New Value: {}\".format(newValue8)) # Create the DDATA payload -", "= obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5 =", "print(\"Creating Pipeline \\n \") pipeline = Gst.Pipeline() if not pipeline:", "included in # all copies or substantial portions of the", "= 15 Device_Input5 = 16 Device_Input6 = 17 Device_Input7 =", "Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2 = obj_counter[newValue2]", "srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink)", "output # value. If this were a real output we'd", "DBIRTH newValue10 = metric.int_value print (\"CMD message for output/Device Input10", "because of how we declated it in the DBIRTH newValue8", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10,", "code, so the Python garbage collector will leave # it", "= 53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI =", "print (\"Publishing Device Birth\") # Get the payload payload =", "form batches from one or more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\",", "35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL = 32", "12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9", "PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT", "\"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball", "from the file print(\"Creating Source \\n \") source = Gst.ElementFactory.make(\"v4l2src\",", "0 Object8 = 0 Object9 = 0 Object10 = 0", "py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) # Text background color py_nvosd_text_params.set_bg_clr =", "PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK", "PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT =", "addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device Metric1\",", "42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE = 39", "= 9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN =", "pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx", "v4l2src -> nvvideoconvert -> mux -> # nvinfer -> nvvideoconvert", "to create nvvidconv \\n\") # Create OSD to draw on", "AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish a message data byteArray =", "###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### # Publish the", "Acquiring a display meta object. The memory ownership remains in", "GStreamer plugins' capability negotiation # shall be intelligent enough to", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish a", "supported by nvvideoconvert; # Say YUYV is unsupported - which", "\"Sparkplug B Devices\" myNodeName = \"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod", "TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN", "the device/client application to resend # its full NBIRTH and", "C address of the # allocated string. Use pyds.get_string() to", "\"/#\") client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\" + myNodeName + \"/#\")", "# to connect to. print (\"'Node Control/Next Server' is not", "num_rectsx ) addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "15 Device_Input5 = 16 Device_Input6 = 17 Device_Input7 = 18", "that was not published in the # original NBIRTH or", "In case we have a camera with raw format supported", "of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform)", "streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\" Unable to get the sink", "via a soft reboot. # In this case, we fake", "# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF", "screen # Note that the pyds module allocates a buffer", "Device_counter2 = 11 Device_Input1 = 12 Device_Input2 = 13 Device_Input3", "set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) # Using pyds.get_string()", "use the alias because this isn't the DBIRTH payload =", "+ \"/\" + myDeviceName, byteArray, 0, False) # Publish a", "reboot # This can be used for devices that need", "Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if", "pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync = false to avoid late", "range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting pipeline \\n\")", "the application must send all known metrics in # its", "the garbage collector will claim it when this probe function", "be claimed by the garbage collector. # Reading the display_text", "AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) #", "PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0,", "PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD", "font-color and font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size = 10 #", "to run inferencing on camera's output, # behaviour of inferencing", "create capsfilter \\n\") # Create nvstreammux instance to form batches", "application if it receives an NDATA or DDATA with a", "NCMD used to tell the device/client application to # disconnect", "White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) # Text background color py_nvosd_text_params.set_bg_clr", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "connect to the next MQTT server in the # list", "= 42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE =", "Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd: sys.stderr.write(\" Unable to create nvosd", "= obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10 = obj_counter[newValue10] # Now", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) # Using", "\"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16,", "can still access it. Otherwise # the garbage collector will", "bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\" + myNodeName, byteArray, 0,", "for output/Device Input4 - New Value: {}\".format(newValue4)) # Create the", "reading from the file print(\"Creating Source \\n \") source =", "in our DBIRTH message and we're emulating an output. #", "Unable to create capsfilter \\n\") # Create nvstreammux instance to", "5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE = 2", "\"XavierNX\" publishPeriod = 5000 myUsername = \"admin\" myPassword = \"<PASSWORD>\"", "Setting display text to be shown on screen # Note", "notice shall be included in # all copies or substantial", "time, threading import random import string import gi gi.require_version('Gst', '1.0')", "a real output we'd write to the output and then", "MetricDataType.Int16, newValue) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "# in the C code, so the Python garbage collector", "the file print(\"Creating Source \\n \") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\")", "MQTT server in the # list of available servers. This", "print(\"Creating Video Converter \\n\") # Adding videoconvert -> nvvideoconvert as", "the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\")", "in the DBIRTH newValue = metric.string_value print (\"CMD message for", "nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\" Unable to", "need to confirm this) # videoconvert to make sure a", "PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK", "0, False) #global newValue4 #publishBirth() elif metric.name == \"output/Device Metric4\"", "the offsets where the string should appear py_nvosd_text_params.x_offset = 10", "some random data to the inputs addMetric(payload, \"input/number of objects\",", "and this permission notice shall be included in # all", "newValue6) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "Value: {}\".format(newValue4)) # Create the DDATA payload - Use the", "# original NBIRTH or DBIRTH. This is why the application", "is not None: try: # Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data)", "AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish a message data byteArray =", "as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except StopIteration:", "26 Device_Output6 = 27 Device_Output7 = 28 Device_Output8 = 29", "\\n\") # nvvideoconvert to convert incoming raw buffers to NVMM", "# disconnect from the current MQTT server and connect to", "else: print (\"Unknown command: \" + metric.name) else: print (\"Unknown", "the new output # value. If this were a real", "and to permit persons to whom the # Software is", "will send this NCMD to a device/client # application if", "is a metric we declared in our DBIRTH message and", "file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie: sys.stderr.write(\" Unable", "batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while l_frame is not", "# Publish the birth certificates publishBirth() def foo(): # Periodically", "= 46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE =", "= 14 Device_Input4 = 15 Device_Input5 = 16 Device_Input6 =", "\\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink) else:", "in # nvvideoconvert, GStreamer plugins' capability negotiation # shall be", "Object8 global Object9 global Object10 #Intiallizing object counter with 0.", "10 Device_counter2 = 11 Device_Input1 = 12 Device_Input2 = 13", "PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD", "arrived: \" + msg.topic) tokens = msg.topic.split(\"/\") global newValue1 global", "Object2 = obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5", "(the \"Software\"), # to deal in the Software without restriction,", "because of how we declated it in the DBIRTH newValue3", "not None: try: # Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except", "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS", "certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\" +", "\"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\",", "from gi.repository import GObject, Gst from common.is_aarch_64 import is_aarch64 from", "\"Serif\" py_nvosd_text_params.font_params.font_size = 10 # set(red, green, blue, alpha); set", "# had got all the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if", "\"Stop sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\",", "add probe to # the sink pad of the osd", "addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5,", "+ myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\" +", "\"/\" + myDeviceName, byteArray, 0, False) # Publish a message", "how we declated it in the DBIRTH newValue2 = metric.int_value", "addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9,", "elif metric.name == \"output/Device Input6\" or metric.alias == AliasMap.Device_Input6: #", "Object10 #Intiallizing object counter with 0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0,", "the rights to use, copy, modify, merge, publish, distribute, sublicense,", "output, # behaviour of inferencing is set through config file", "0, False) # Publish a message Input 1 #publishBirth() elif", "Input 3 #publishBirth() elif metric.name == \"output/Device Input3\" or metric.alias", "3 Device_num_rectsx = 4 Device_Metric0 = 5 Device_Metric1 = 6", "= 12 # Font , font-color and font-size py_nvosd_text_params.font_params.font_name =", "the Software, and to permit persons to whom the #", "AliasMap.Device_Input5: # This is a metric we declared in our", "global Object6 global Object7 global Object8 global Object9 global Object10", "myUsername = \"admin\" myPassword = \"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883,", "Note that pyds.gst_buffer_get_nvds_batch_meta() expects the # C address of gst_buffer", "= info.get_buffer() if not gst_buffer: print(\"Unable to get GstBuffer \")", "# the C code so downstream plugins can still access", "if not pipeline: sys.stderr.write(\" Unable to create Pipeline \\n\") #", "Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16,", "\"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish the initial data", "0 newValue7 = 0 newValue8 = 0 newValue9 = 0", "or metric.alias == AliasMap.Device_Metric3: # This is a metric we", "person obtaining a # copy of this software and associated", "is hereby granted, free of charge, to any person obtaining", "message for output/Device Input7 - New Value: {}\".format(newValue7)) # Create", "a CONNACK response from the server. ###################################################################### def on_connect(client, userdata,", "Unable to create v4l2src capsfilter \\n\") print(\"Creating Video Converter \\n\")", "# v4l2src -> nvvideoconvert -> mux -> # nvinfer ->", "0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\",", "a message Input 10 #publishBirth() elif metric.name == \"output/Device Input10\"", "underlying memory # in the C code, so the Python", "is unsupported - which is the common # raw format", "random data to the inputs addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx,", "NBIRTH and DBIRTH # messages. publishBirth() elif metric.name == \"output/Device", "means that if we lose the connection and # reconnect", "associated documentation files (the \"Software\"), # to deal in the", "a cast to pyds.NvDsFrameMeta # The casting is done by", "probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params = display_meta.text_params[0]", "because of how we declated it in the DBIRTH newValue2", "capsfilter \\n\") # Create nvstreammux instance to form batches from", "\"../../../client_libraries/python/\") import paho.mqtt.client as mqtt import sparkplug_b as sparkplug import", "= 0 num_rectsx = 0 counter1 = 0 counter2 =", "with a republishing of the NBIRTH and DBIRTH # messages.", "we declated it in the DBIRTH newValue8 = metric.int_value print", "20 Device_Input10 = 21 Device_Output1 = 22 Device_Output2 = 23", "#publishBirth() elif metric.name == \"output/Device Input5\" or metric.alias == AliasMap.Device_Input5:", "global Object10 #Intiallizing object counter with 0. obj_counter = {", "Rebirth = 1 Reboot = 2 Device_frame_numberx = 3 Device_num_rectsx", "the NBIRTH and DBIRTH # messages. publishBirth() elif metric.name ==", "a message Input 6 #publishBirth() elif metric.name == \"output/Device Input6\"", "31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR =", "sink pad of the osd element, since by that time,", "def foo(): # Periodically publish some new data payload =", "add probe to get informed of the meta data generated,", "l_frame is not None: try: # Note that l_frame.data needs", "\"output/Device Input1\" or metric.alias == AliasMap.Device_Input1: # This is a", "pyds.gst_buffer_get_nvds_batch_meta() expects the # C address of gst_buffer as input,", "PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0,", "= metric.int_value print (\"CMD message for output/Device Input8 - New", "None, AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish a message data byteArray", "to make sure a superset of raw formats are supported", "message Input 9 #publishBirth() elif metric.name == \"output/Device Input9\" or", "from the server. ###################################################################### def on_message(client, userdata, msg): print(\"Message arrived:", "newValue9 = metric.int_value print (\"CMD message for output/Device Input9 -", "\"/DDATA/\" + myNodeName + \"/\" + myDeviceName, byteArray, 0, False)", "if not caps_vidconvsrc: sys.stderr.write(\" Unable to create capsfilter \\n\") #", "cast to pyds.NvDsFrameMeta # The casting is done by pyds.NvDsFrameMeta.cast()", "\" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width',", "if not pgie: sys.stderr.write(\" Unable to create pgie \\n\") #", "import gi gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst from", "# Publish a message Input 6 #publishBirth() elif metric.name ==", "args[0]) sys.exit(1) # Standard GStreamer initialization GObject.threads_init() Gst.init(None) # Create", "\"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\",", "if rc == 0: print(\"Connected with result code \"+str(rc)) else:", "PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0,", "byteArray, 0, False) # Publish a message Input 10 #publishBirth()", "0, False) #publishBirth() elif metric.name == \"output/Device Metric3\" or metric.alias", "\"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### # The callback for", "metrics in # its original NBIRTH and DBIRTH messages. publishBirth()", "PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0,", "why the application must send all known metrics in #", "# before publishing a DDATA message. # We know this", "granted, free of charge, to any person obtaining a #", "next MQTT server in the # list of available servers.", "AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish a message data byteArray =", "- New Value: {}\".format(newValue6)) # Create the DDATA payload -", "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #", "3 #publishBirth() elif metric.name == \"output/Device Input3\" or metric.alias ==", "rights reserved. # # Permission is hereby granted, free of", "Use pyds.get_string() to get the string content. py_nvosd_text_params.display_text = \"Frame", "Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\",", "string content. py_nvosd_text_params.display_text = \"Frame Number={} Number of Objects={} Bird_count={}", "DBIRTH newValue8 = metric.int_value print (\"CMD message for output/Device Input8", "or outbound events for _ in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS,", "newValue8 = 0 newValue9 = 0 newValue10 = 0 class", "because of how we declated it in the DBIRTH newValue4", "11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT = 8", "# Permission is hereby granted, free of charge, to any", "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #", "of how we declated it in the DBIRTH newValue1 =", "AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload,", "addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device Metric0\",", "PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0,", "to create egl sink \\n\") print(\"Playing cam %s \" %args[1])", "newValue2 global newValue3 global newValue4 global newValue5 global newValue6 global", "used to tell the device/client application to # disconnect from", "Metric3\" or metric.alias == AliasMap.Device_Metric3: # This is a metric", "= \"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod = 5000 myUsername =", "Device_Input2 = 13 Device_Input3 = 14 Device_Input4 = 15 Device_Input5", "the device/client application to # disconnect from the current MQTT", "0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\",", "myDeviceName, totalByteArray, 0, False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx", "14 Device_Input4 = 15 Device_Input5 = 16 Device_Input6 = 17", "myDeviceName, byteArray, 0, False) else: print (\"Unknown command: \" +", "AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish a message data byteArray =", "Application Variables serverUrl = \"localhost\" myGroupId = \"Sparkplug B Devices\"", "RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd: sys.stderr.write(\"", "to get the string content. py_nvosd_text_params.display_text = \"Frame Number={} Number", "we declated it in the DBIRTH newValue = metric.int_value print", "= \"Sparkplug B Devices\" myNodeName = \"NVIDIA\" myDeviceName = \"XavierNX\"", "is an NCMD used to tell the device/client application to", "to resend # its full NBIRTH and DBIRTH again. MQTT", "raw formats are supported by nvvideoconvert; # Say YUYV is", "of how we declated it in the DBIRTH newValue2 =", "MetricDataType.Boolean, False) # Publish the node birth certificate byteArray =", "= 14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN =", "\\n\") # Create OSD to draw on the converted RGBA", "we declated it in the DBIRTH newValue7 = metric.int_value print", "PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0,", "by pyds.NvDsFrameMeta.cast() # The casting also keeps ownership of the", "Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0)", "sparkplug import time import time, threading import random import string", "\"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### # The callback", "it in the DBIRTH newValue3 = metric.int_value print (\"CMD message", "Object5 = 0 Object6 = 0 Object7 = 0 Object8", "\"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\",", "\"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic light\",", "arguments if len(args) != 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0])", "addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9,", "(\"CMD message for output/Device Input5 - New Value: {}\".format(newValue5)) #", "to form batches from one or more sources. streammux =", "\"admin\" myPassword = \"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS", "pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform) # we", "Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\",", "PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0,", "= 68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE =", "# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE", "Publish a message Input 2 #publishBirth() elif metric.name == \"output/Device", "AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload,", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16,", "to create nvosd \\n\") # Finally render the osd output", "PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET", "addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish the initial", "43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS = 40", "Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) # Publish the node birth certificate", "AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx", "of the NBIRTH and DBIRTH # messages. publishBirth() elif metric.name", "DBIRTH newValue1 = metric.int_value print (\"CMD message for output/Device Input1", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\",", "= 73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER =", "False) else: print (\"Unknown command: \" + metric.name) else: print", "== myGroupId and (tokens[2] == \"NCMD\" or tokens[2] == \"DCMD\")", "= 25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA =", "client = mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS = 1 frame_numberx =", "\"/\" + myDeviceName, byteArray, 0, False) # Sit and wait", "more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux: sys.stderr.write(\"", "myGroupId + \"/NDEATH/\" + myNodeName, deathByteArray, 0, False) client.connect(serverUrl, 1883,", "full application reset via a soft reboot. # In this", "pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform) # we link", "create an event loop and feed gstreamer bus mesages to", "to any person obtaining a # copy of this software", "gstreamer bus mesages to it loop = GObject.MainLoop() bus =", "of main program - Set up the MQTT client connection", "PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0,", "nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\" Unable to get sink pad", "26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE = 23", "AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload,", "DBIRTH newValue = metric.boolean_value print (\"CMD message for output/Device Metric3", "+ myDeviceName, byteArray, 0, False) else: print (\"Unknown command: \"", "\"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16,", "Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish the initial data with", "meta object. The memory ownership remains in # the C", "MetricDataType.String, \"start\") # Publish the initial data with the Device", "string import gi gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst", "# copy of this software and associated documentation files (the", "PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0,", "* import pyds # Application Variables serverUrl = \"localhost\" myGroupId", "# its full NBIRTH and DBIRTH again. MQTT Engine will", "loop.run() except: pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL) if __name__ ==", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish a", "0, False) # Publish a message Input 6 #publishBirth() elif", "\"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\",", "# Publish a message Input 9 #publishBirth() elif metric.name ==", "DBIRTH message and we're emulating an output. # So, on", "AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload,", "to the inputs addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx", "\\n\") print(\"Creating Video Converter \\n\") # Adding videoconvert -> nvvideoconvert", "Unable to create nvvidconv \\n\") # Create OSD to draw", "bus_call, loop) # Lets add probe to get informed of", "Input 10 #publishBirth() elif metric.name == \"output/Device Input10\" or metric.alias", "\"/#\") ###################################################################### ###################################################################### # The callback for when a PUBLISH", "Set sync = false to avoid late frame drops at", "bus.connect (\"message\", bus_call, loop) # Lets add probe to get", "the Python garbage collector will leave # it alone. frame_meta", "byteArray, 0, False) # Publish a message Input 2 #publishBirth()", "sparkplug.getNodeBirthPayload() # Set up the Node Controls addMetric(payload, \"Node Control/Next", "module allocates a buffer for the string, and the #", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT", "elif metric.name == \"output/Device Input1\" or metric.alias == AliasMap.Device_Input1: #", "= 18 Device_Input8 = 19 Device_Input9 = 20 Device_Input10 =", "that if we lose the connection and # reconnect then", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9,", "plugins can still access it. Otherwise # the garbage collector", "print (\"CMD message for output/Device Input2 - New Value: {}\".format(newValue2))", "not caps_vidconvsrc: sys.stderr.write(\" Unable to create capsfilter \\n\") # Create", "== AliasMap.Rebirth: # 'Node Control/Rebirth' is an NCMD used to", "payload - use the alias because this isn't the DBIRTH", "needs a cast to pyds.NvDsFrameMeta # The casting is done", "29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG = 26", "= 2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\",", "allocates a buffer for the string, and the # memory", "myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\" +", "addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10,", "# Create OSD to draw on the converted RGBA buffer", "addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6,", "= 78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE =", "(\"message\", bus_call, loop) # Lets add probe to get informed", "36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE = 33", "because this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None,", "will leave # it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration:", "MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device", "= metric.int_value print (\"CMD message for output/Device Metric2 - New", "or metric.alias == AliasMap.Device_Input8: # This is a metric we", "not nvosd: sys.stderr.write(\" Unable to create nvosd \\n\") # Finally", "how we declated it in the DBIRTH newValue7 = metric.int_value", "common # raw format for many logi usb cams #", "Device_Output4 = 25 Device_Output5 = 26 Device_Output6 = 27 Device_Output7", "the DDATA payload - Use the alias because this isn't", "and we're emulating an output. # So, on incoming 'writes'", "with 0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0,", "# Text background color py_nvosd_text_params.set_bg_clr = 1 # set(red, green,", "== AliasMap.Device_Input8: # This is a metric we declared in", "metric that was not published in the # original NBIRTH", "obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7 = obj_counter[newValue7]", "Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout',", "it in the DBIRTH newValue = metric.boolean_value print (\"CMD message", "== \"output/Device Input4\" or metric.alias == AliasMap.Device_Input4: # This is", "Control/Rebirth' is an NCMD used to tell the device/client application", "len(args) != 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0]) sys.exit(1) #", "text to be shown on screen # Note that the", "formats are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc:", "Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload,", "= 21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP =", "if not streammux: sys.stderr.write(\" Unable to create NvStreamMux \\n\") #", "myGroupId = \"Sparkplug B Devices\" myNodeName = \"NVIDIA\" myDeviceName =", "AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish a message data byteArray =", "nvvideoconvert -> mux -> # nvinfer -> nvvideoconvert -> nvosd", "publishPeriod = 5000 myUsername = \"admin\" myPassword = \"<PASSWORD>\" client", "for output/Device Input6 - New Value: {}\".format(newValue6)) # Create the", "for the string, and the # memory will not be", "= metric.int_value print (\"CMD message for output/Device Input7 - New", "== AliasMap.Device_Input1: # This is a metric we declared in", "to create videoconvert \\n\") # nvvideoconvert to convert incoming raw", "PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS", "#publishBirth() elif metric.name == \"output/Device Input4\" or metric.alias == AliasMap.Device_Input4:", "deathPayload = sparkplug.getNodeDeathPayload() # Start of main program - Set", "it in the DBIRTH newValue1 = metric.int_value print (\"CMD message", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish", "\"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\",", "can be used for devices that need a full application", "PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA", "send this NCMD to a device/client # application if it", "PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG", "- Set up the MQTT client connection client.on_connect = on_connect", "\"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\",", "soft reboot. # In this case, we fake a full", "Periodically publish some new data payload = sparkplug.getDdataPayload() # Add", "+ myDeviceName, byteArray, 0, False) #publishBirth() elif metric.name == \"output/Device", "it in the DBIRTH newValue8 = metric.int_value print (\"CMD message", "print(\"Adding elements to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc)", "24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR = 21", "Input 4 #publishBirth() elif metric.name == \"output/Device Input4\" or metric.alias", "when this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params", "exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params = display_meta.text_params[0] # Setting", "= Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie: sys.stderr.write(\" Unable to create", "\"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### # The callback for when", "# The callback for when a PUBLISH message is received", "Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish a", "args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path',", "an NDATA or DDATA with a metric that was not", "are supported by nvvideoconvert; # Say YUYV is unsupported -", "Unable to create videoconvert \\n\") # nvvideoconvert to convert incoming", "myGroupId + \"/DDATA/\" + myNodeName + \"/\" + myDeviceName, byteArray,", "AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish a message data byteArray =", "\"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire", "and (tokens[2] == \"NCMD\" or tokens[2] == \"DCMD\") and tokens[3]", "PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0,", "== \"spBv1.0\" and tokens[1] == myGroupId and (tokens[2] == \"NCMD\"", "Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10)", "transform.link(sink) else: nvosd.link(sink) # create an event loop and feed", "AliasMap.Device_Input6: # This is a metric we declared in our", "PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL", "###################################################################### ###################################################################### # Publish the NBIRTH certificate ###################################################################### def publishNodeBirth():", "camera with raw format supported in # nvvideoconvert, GStreamer plugins'", "ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED", "client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try:", "DBIRTH again. MQTT Engine will send this NCMD to a", "from sparkplug_b import * import pyds # Application Variables serverUrl", "= 79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS =", "\\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if not", "in this example\") elif metric.name == \"Node Control/Rebirth\" or metric.alias", "Input 7 #publishBirth() elif metric.name == \"output/Device Input7\" or metric.alias", "use, copy, modify, merge, publish, distribute, sublicense, # and/or sell", "srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\" Unable to get", "case we have a camera with raw format supported in", "#publishBirth() elif metric.name == \"output/Device Metric3\" or metric.alias == AliasMap.Device_Metric3:", "return the C address of the # allocated string. Use", "Unable to create Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if", "PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0,", "# and/or sell copies of the Software, and to permit", "PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE", "Device_Input4 = 15 Device_Input5 = 16 Device_Input6 = 17 Device_Input7", "\\n\") # Source element for reading from the file print(\"Creating", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,", "THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ################################################################################", "\"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16,", "except StopIteration: break # Acquiring a display meta object. The", "\"nvvideo-renderer\") if not sink: sys.stderr.write(\" Unable to create egl sink", "= 13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT =", "= 17 Device_Input7 = 18 Device_Input8 = 19 Device_Input9 =", "Create OSD to draw on the converted RGBA buffer nvosd", "caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height',", "byteArray, 0, False) ###################################################################### ###################################################################### # Publish the DBIRTH certificate", "payload = sparkplug.getDeviceBirthPayload() # Add some device metrics addMetric(payload, \"input/Frame", "MQTT client connection client.on_connect = on_connect client.on_message = on_message client.username_pw_set(myUsername,", "the # memory will not be claimed by the garbage", "66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP = 63", "bus_call from sparkplug_b import * import pyds # Application Variables", "global newValue4 global newValue5 global newValue6 global newValue7 global newValue8", "newValue6 = metric.int_value print (\"CMD message for output/Device Input6 -", "to create capsfilter \\n\") # Create nvstreammux instance to form", "# Create nvstreammux instance to form batches from one or", "Device_Output1 = 22 Device_Output2 = 23 Device_Output3 = 24 Device_Output4", "sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as mqtt import sparkplug_b as", "17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD = 14", "global Object5 global Object6 global Object7 global Object8 global Object9", "###################################################################### # Publish the DBIRTH certificate ###################################################################### def publishDeviceBirth(): print", "== AliasMap.Device_Input4: # This is a metric we declared in", "PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0,", "the C code so downstream plugins can still access it.", "28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA = 25", "= Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\" Unable to create", "\\n\") # Finally render the osd output if is_aarch64(): transform", "PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0,", "bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\",", "Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\"", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "= obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10 =", "Metric4 - New Value: {}\".format(newValue)) # Create the DDATA payload", "OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR", "if not source: sys.stderr.write(\" Unable to create Source \\n\") caps_v4l2src", "pipeline = Gst.Pipeline() if not pipeline: sys.stderr.write(\" Unable to create", "tokens[0] == \"spBv1.0\" and tokens[1] == myGroupId and (tokens[2] ==", "= nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\" Unable to get sink", "1 try: l_obj=l_obj.next except StopIteration: break # Acquiring a display", "WAIT_SECONDS = 1 frame_numberx = 0 num_rectsx = 0 counter1", "# Note that the pyds module allocates a buffer for", "obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3 =", "# Subscribing in on_connect() means that if we lose the", "= 12 Device_Input2 = 13 Device_Input3 = 14 Device_Input4 =", "PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS", "API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\" Unable", "subscriptions will be renewed. client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\" +", "declated it in the DBIRTH newValue10 = metric.int_value print (\"CMD", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "collector. # Reading the display_text field here will return the", "caps_vidconvsrc: sys.stderr.write(\" Unable to create capsfilter \\n\") # Create nvstreammux", "caps_v4l2src: sys.stderr.write(\" Unable to create v4l2src capsfilter \\n\") print(\"Creating Video", "= pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta", "metric.name == \"output/Device Input10\" or metric.alias == AliasMap.Device_Input10: # This", "is obtained with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list", "msg.topic.split(\"/\") global newValue1 global newValue2 global newValue3 global newValue4 global", "#publishBirth() elif metric.name == \"output/Device Input6\" or metric.alias == AliasMap.Device_Input6:", "Metric3 - New Value: %r\" % newValue) # Create the", "Input1 - New Value: {}\".format(newValue1)) # Create the DDATA payload", "with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while l_frame", "streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync = false to", "clients that have a pool of MQTT servers # to", "AliasMap.Device_Metric3: # This is a metric we declared in our", "Object1 = obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4", "== \"Node Control/Rebirth\" or metric.alias == AliasMap.Rebirth: # 'Node Control/Rebirth'", "newValue4 #publishBirth() elif metric.name == \"output/Device Metric4\" or metric.alias ==", "= metric.string_value print (\"CMD message for output/Device Metric4 - New", "(\"Unknown command...\") print (\"Done publishing\") ##################################################################### ###################################################################### ###################################################################### # Publish", "one or more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not", "we declated it in the DBIRTH newValue9 = metric.int_value print", "New Value: {}\".format(newValue9)) # Create the DDATA payload - Use", "garbage collector. # Reading the display_text field here will return", "== AliasMap.Device_Input2: # This is a metric we declared in", "= 23 Device_Output3 = 24 Device_Output4 = 25 Device_Output5 =", "0 counter1 = 0 counter2 = 0 Object1 = 0", "from NV12 to RGBA as required by nvosd nvvidconv =", "this permission notice shall be included in # all copies", "Input10\" or metric.alias == AliasMap.Device_Input10: # This is a metric", "\"Node Control/Rebirth\" or metric.alias == AliasMap.Rebirth: # 'Node Control/Rebirth' is", "AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload,", "= 6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE =", "foo() ###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass", "Publish the NBIRTH certificate ###################################################################### def publishNodeBirth(): print (\"Publishing Node", "from common.is_aarch_64 import is_aarch64 from common.bus_call import bus_call from sparkplug_b", "and font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size = 10 # set(red,", "addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish a message data", "is an Boolean because of how we declated it in", "PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK", "Device_Input8 = 19 Device_Input9 = 20 Device_Input10 = 21 Device_Output1", "#publishBirth() elif metric.name == \"output/Device Input3\" or metric.alias == AliasMap.Device_Input3:", "connection client.on_connect = on_connect client.on_message = on_message client.username_pw_set(myUsername, myPassword) deathByteArray", "12 # Font , font-color and font-size py_nvosd_text_params.font_params.font_name = \"Serif\"", "newValue8) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "msg): print(\"Message arrived: \" + msg.topic) tokens = msg.topic.split(\"/\") global", "AliasMap.Device_Input4: # This is a metric we declared in our", "is furnished to do so, subject to the following conditions:", "0 Object4 = 0 Object5 = 0 Object6 = 0", "glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\",", "addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7,", "output/Device Metric2 - New Value: {}\".format(newValue)) # Create the DDATA", "\"output/Device Input10\" or metric.alias == AliasMap.Device_Input10: # This is a", "False) #publishBirth() elif metric.name == \"output/Device Metric3\" or metric.alias ==", "Publish the DBIRTH certificate ###################################################################### def publishDeviceBirth(): print (\"Publishing Device", "drops at the display-sink sink.set_property('sync', False) print(\"Adding elements to Pipeline", "myNodeName + \"/\" + myDeviceName, byteArray, 0, False) # Publish", "newValue = metric.int_value print (\"CMD message for output/Device Metric2 -", "Device_Input3 = 14 Device_Input4 = 15 Device_Input5 = 16 Device_Input6", "None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish a message data byteArray", "newValue5 = 0 newValue6 = 0 newValue7 = 0 newValue8", "= 0 Object8 = 0 Object9 = 0 Object10 =", "= Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source: sys.stderr.write(\" Unable to create", "Object2 = 0 Object3 = 0 Object4 = 0 Object5", "this is an Boolean because of how we declated it", "osd_sink_pad_buffer_probe, 0) ###################################################################### # Create the node death payload deathPayload", "newValue = metric.boolean_value print (\"CMD message for output/Device Metric3 -", "ARISING # FROM, OUT OF OR IN CONNECTION WITH THE", "and tokens[3] == myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric", "\"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\",", "Control/Next Server' is not implemented in this example\") elif metric.name", "sys.exit() global myGroupId global myNodeName # Subscribing in on_connect() means", "random import string import gi gi.require_version('Gst', '1.0') from gi.repository import", "= 0 newValue8 = 0 newValue9 = 0 newValue10 =", "Device_Output7 = 28 Device_Output8 = 29 Device_Output9 = 30 Device_Output10", "inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics: if metric.name == \"Node Control/Next", "streammux: sys.stderr.write(\" Unable to create NvStreamMux \\n\") # Use nvinfer", "\"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0,", "again. MQTT Engine will send this NCMD to a device/client", "Object6 = 0 Object7 = 0 Object8 = 0 Object9", "Device_Input9 = 20 Device_Input10 = 21 Device_Output1 = 22 Device_Output2", "= 17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD =", "print(\"Creating EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink:", "addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16,", "PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL", "device/client application to reboot # This can be used for", "4 Device_Metric0 = 5 Device_Metric1 = 6 Device_Metric2 = 7", "newValue4) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\",", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16,", "was not published in the # original NBIRTH or DBIRTH.", "of the # allocated string. Use pyds.get_string() to get the", "print (\"Done publishing\") ##################################################################### ###################################################################### ###################################################################### # Publish the BIRTH", "11 Device_Input1 = 12 Device_Input2 = 13 Device_Input3 = 14", "Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0)", "\"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0)", "+ \"/#\") ###################################################################### ###################################################################### # The callback for when a", "Object5 global Object6 global Object7 global Object8 global Object9 global", "pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next", "deathByteArray, 0, False) client.connect(serverUrl, 1883, 60) # Publish the birth", "= metric.int_value print (\"CMD message for output/Device Input6 - New", "to draw on the converted RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\",", "message for output/Device Input5 - New Value: {}\".format(newValue5)) # Create", "newValue4 = metric.int_value print (\"CMD message for output/Device Input4 -", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) #", "= 0 counter1 = 0 counter2 = 0 Object1 =", "display meta object. The memory ownership remains in # the", "###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass #cleanup", "= 13 Device_Input3 = 14 Device_Input4 = 15 Device_Input5 =", "buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd: sys.stderr.write(\" Unable", "newValue10) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "Value: %r\" % newValue) # Create the DDATA payload -", "a message Input 9 #publishBirth() elif metric.name == \"output/Device Input9\"", "pipeline: sys.stderr.write(\" Unable to create Pipeline \\n\") # Source element", "on_message client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId +", "PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\",", "= sparkplug.getNodeDeathPayload() # Start of main program - Set up", "global newValue10 if tokens[0] == \"spBv1.0\" and tokens[1] == myGroupId", "AliasMap.Device_Input2: # This is a metric we declared in our", "byteArray, 0, False) # Publish a message Input 5 #publishBirth()", "the DBIRTH newValue = metric.boolean_value print (\"CMD message for output/Device", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue) #", "Object4 = obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7", "Value: {}\".format(newValue2)) # Create the DDATA payload - Use the", "\"primary-inference\") if not pgie: sys.stderr.write(\" Unable to create pgie \\n\")", "common.bus_call import bus_call from sparkplug_b import * import pyds #", "0, False) # Publish a message Input 3 #publishBirth() elif", "# 'Node Control/Rebirth' is an NCMD used to tell the", "= 1 py_nvosd_text_params = display_meta.text_params[0] # Setting display text to", "= obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8 =", "global newValue3 global newValue4 global newValue5 global newValue6 global newValue7", "streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) #", "gst_buffer: print(\"Unable to get GstBuffer \") return # Retrieve batch", "MetricDataType.Int16, newValue5) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "= 64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET =", "PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str=", "\"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean,", "AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload,", "because of how we declated it in the DBIRTH newValue9", "- which is the common # raw format for many", "on_connect() means that if we lose the connection and #", "== AliasMap.Next_Server: # 'Node Control/Next Server' is an NCMD used", "addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6,", "the C code, so the Python garbage collector will leave", "pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call, loop) # Lets add probe", "output/Device Input7 - New Value: {}\".format(newValue7)) # Create the DDATA", "\"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\",", "Object3 = obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6", "39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD = 36", "= 48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL =", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) #", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "Otherwise # the garbage collector will claim it when this", "# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY", "def on_connect(client, userdata, flags, rc): if rc == 0: print(\"Connected", "\"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16,", "cam %s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device',", "message. # We know this is an Int16 because of", "obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next except StopIteration: break # Acquiring", "elif metric.name == \"output/Device Input5\" or metric.alias == AliasMap.Device_Input5: #", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) #", "an output. # So, on incoming 'writes' to the output", "\"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16,", "= 39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD =", "PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA", "PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON", "'Node Control/Reboot' is an NCMD used to tell a device/client", "AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0)", "= Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv: sys.stderr.write(\" Unable to create", "Value: {}\".format(newValue10)) # Create the DDATA payload - Use the", "set(red, green, blue, alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0,", "0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\",", "= bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\" + myNodeName, byteArray,", "37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT = 34", "dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis", "# set(red, green, blue, alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0,", "= 54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT =", "declated it in the DBIRTH newValue6 = metric.int_value print (\"CMD", "{ PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0,", "Object8 = obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10 = obj_counter[newValue10] #", "frame drops at the display-sink sink.set_property('sync', False) print(\"Adding elements to", "= 35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL =", "MetricDataType.Int16, newValue2) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6,", "declated it in the DBIRTH newValue3 = metric.int_value print (\"CMD", "PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR", "if it receives an NDATA or DDATA with a metric", "py_nvosd_text_params.y_offset = 12 # Font , font-color and font-size py_nvosd_text_params.font_params.font_name", "all # raw formats are supported by nvvideoconvert; # Say", "inputs addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload,", "nvstreammux instance to form batches from one or more sources.", "Publish a message Input 8 #publishBirth() elif metric.name == \"output/Device", "and the # memory will not be claimed by the", "Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\"", "= 0 Object1 = 0 Object2 = 0 Object3 =", "\"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean,", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16,", "is_aarch64 from common.bus_call import bus_call from sparkplug_b import * import", "AliasMap.Device_Input3: # This is a metric we declared in our", "to a device/client # application if it receives an NDATA", "Sit and wait for inbound or outbound events for _", "MetricDataType.Int16, newValue6) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "Software without restriction, including without limitation # the rights to", "AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload,", "= 50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE =", "PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK", "alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) # Text", "myGroupId global myNodeName # Subscribing in on_connect() means that if", "This is why the application must send all known metrics", "\"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\",", "in the DBIRTH newValue9 = metric.int_value print (\"CMD message for", "we declated it in the DBIRTH newValue2 = metric.int_value print", "\"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\",", "1.0) # Using pyds.get_string() to get display_text as string #", "= 72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN =", "bus = pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call, loop) # Lets", "myDeviceName, byteArray, 0, False) # Publish a message Input 8", "# shall be intelligent enough to reduce compute by #", "PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0,", "PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER", "of the meta data generated, we add probe to #", "# the sink pad of the osd element, since by", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "whom the # Software is furnished to do so, subject", "hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### #", "NV12 to RGBA as required by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\",", "certificate ###################################################################### def publishDeviceBirth(): print (\"Publishing Device Birth\") # Get", "to reboot # This can be used for devices that", "metric.alias == AliasMap.Device_Input2: # This is a metric we declared", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish", "l_obj is not None: try: # Casting l_obj.data to pyds.NvDsObjectMeta", "field here will return the C address of the #", "publishBirth() def foo(): # Periodically publish some new data payload", "0, False) # Publish a message Input 9 #publishBirth() elif", "device/client application to resend # its full NBIRTH and DBIRTH", "AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload,", "= 58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE =", "\"output/Device Input3\" or metric.alias == AliasMap.Device_Input3: # This is a", "metric.alias == AliasMap.Device_Input7: # This is a metric we declared", "caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink)", "publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### # Publish the NBIRTH certificate ######################################################################", "Device_Output9 = 30 Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79", "False) # Publish a message Input 9 #publishBirth() elif metric.name", "caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\" Unable to", "required by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv:", "addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4,", "0 newValue6 = 0 newValue7 = 0 newValue8 = 0", "\"Node Control/Next Server\" or metric.alias == AliasMap.Next_Server: # 'Node Control/Next", "sinkpad = streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\" Unable to get", "== AliasMap.Device_Input6: # This is a metric we declared in", "global newValue5 global newValue6 global newValue7 global newValue8 global newValue9", "newValue1 = metric.int_value print (\"CMD message for output/Device Input1 -", "###################################################################### ###################################################################### # Publish the BIRTH certificates ###################################################################### def publishBirth():", "as not all # raw formats are supported by nvvideoconvert;", "its original NBIRTH and DBIRTH messages. publishBirth() elif metric.name ==", "Input10 - New Value: {}\".format(newValue10)) # Create the DDATA payload", "to avoid late frame drops at the display-sink sink.set_property('sync', False)", "= obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7 =", "PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED =", "# we link the elements together # v4l2src -> nvvideoconvert", "= frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is not None: try: #", "def on_message(client, userdata, msg): print(\"Message arrived: \" + msg.topic) tokens", "plugins' capability negotiation # shall be intelligent enough to reduce", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish", "global newValue9 global newValue10 if tokens[0] == \"spBv1.0\" and tokens[1]", "_ in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting", "Add some random data to the inputs addMetric(payload, \"input/number of", "PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0,", "is an Int16 because of how we declated it in", "newValue5 global newValue6 global newValue7 global newValue8 global newValue9 global", "\"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String,", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish a message", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish a message", "collector will leave # it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except", "\"output/Device Input9\" or metric.alias == AliasMap.Device_Input9: # This is a", "for output/Device Metric2 - New Value: {}\".format(newValue)) # Create the", "PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP", "10 #publishBirth() elif metric.name == \"output/Device Input10\" or metric.alias ==", "metric.name == \"output/Device Input1\" or metric.alias == AliasMap.Device_Input1: # This", "Publish the node birth certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" +", "0, False) # Publish a message Input 7 #publishBirth() elif", "\"/\" + myDeviceName, byteArray, 0, False) else: print (\"Unknown command:", "= obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6 =", "to convert incoming raw buffers to NVMM Mem (NvBufSurface API)", "in inboundPayload.metrics: if metric.name == \"Node Control/Next Server\" or metric.alias", "\"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\",", "data generated, we add probe to # the sink pad", "addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1,", "to tell the device/client application to resend # its full", "5 Device_Metric1 = 6 Device_Metric2 = 7 Device_Metric3 = 8", "- New Value: {}\".format(newValue1)) # Create the DDATA payload -", "source pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if", "pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass #cleanup print(\"Exiting app\\n\")", "format for many logi usb cams # In case we", "0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0,", "metric.int_value print (\"CMD message for output/Device Input8 - New Value:", "= Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\" Unable to create", "break # Acquiring a display meta object. The memory ownership", "0, False) # Sit and wait for inbound or outbound", "newValue1) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "to get source pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv)", "be shown on screen # Note that the pyds module", "PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0,", "\"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine", "\"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### # The callback for when the", "element for reading from the file print(\"Creating Source \\n \")", "(\"CMD message for output/Device Input6 - New Value: {}\".format(newValue6)) #", "objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16,", "# Note that l_frame.data needs a cast to pyds.NvDsFrameMeta #", "the BIRTH certificates ###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ######################################################################", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish", "- New Value: {}\".format(newValue3)) # Create the DDATA payload -", "Object7 global Object8 global Object9 global Object10 #Intiallizing object counter", "MetricDataType.Int16, Object10) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH", "48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL = 45", "result code \"+str(rc)) else: print(\"Failed to connect with result code", "addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5,", "# Lets add probe to get informed of the meta", "AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload,", "message for output/Device Metric2 - New Value: {}\".format(newValue)) # Create", "\\n\") # Create nvstreammux instance to form batches from one", "try: # Note that l_frame.data needs a cast to pyds.NvDsFrameMeta", "47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON = 44", "AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM,", "num_rects = frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is", "\"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports", "Gst.PadProbeReturn.OK ###################################################################### def main(args): # Check input arguments if len(args)", "AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload,", "osdsinkpad = nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\" Unable to get", "AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload,", "= 75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR =", "AliasMap.Device_Input10: # This is a metric we declared in our", "Metric4\" or metric.alias == AliasMap.Device_Metric4: # This is a metric", "raw buffers to NVMM Mem (NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\",", "else: print (\"Unknown command...\") print (\"Done publishing\") ##################################################################### ###################################################################### ######################################################################", "Device_Input6 = 17 Device_Input7 = 18 Device_Input8 = 19 Device_Input9", "notice and this permission notice shall be included in #", "Object10 = obj_counter[newValue10] # Now set the offsets where the", "that the pyds module allocates a buffer for the string,", "print (\"CMD message for output/Device Metric2 - New Value: {}\".format(newValue))", "sure a superset of raw formats are supported vidconvsrc =", "StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8)", "metric.name == \"output/Device Input6\" or metric.alias == AliasMap.Device_Input6: # This", "None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish a message data byteArray", "myDeviceName, byteArray, 0, False) #publishBirth() elif metric.name == \"output/Device Metric3\"", "= Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux: sys.stderr.write(\" Unable to create", "THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN", "49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE = 47 PGIE_CLASS_ID_BANANA = 46", "convert from NV12 to RGBA as required by nvosd nvvidconv", "1883, 60) # Publish the birth certificates publishBirth() def foo():", "in the DBIRTH newValue = metric.boolean_value print (\"CMD message for", "else: nvosd.link(sink) # create an event loop and feed gstreamer", "the C address of the # allocated string. Use pyds.get_string()", "elements # Create Pipeline element that will form a connection", "#pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except StopIteration: break return Gst.PadProbeReturn.OK ######################################################################", "= 69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD =", "import random import string import gi gi.require_version('Gst', '1.0') from gi.repository", "newValue9 global newValue10 if tokens[0] == \"spBv1.0\" and tokens[1] ==", "declated it in the DBIRTH newValue = metric.string_value print (\"CMD", "obj_counter[newValue9] Object10 = obj_counter[newValue10] # Now set the offsets where", "to create pgie \\n\") # Use convertor to convert from", "as required by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not", "if len(args) != 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0]) sys.exit(1)", "because of how we declated it in the DBIRTH newValue5", "addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4,", "sys.stderr.write(\" Unable to create Pipeline \\n\") # Source element for", "Pipeline \\n \") pipeline = Gst.Pipeline() if not pipeline: sys.stderr.write(\"", "obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next except", "PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE", "node death payload deathPayload = sparkplug.getNodeDeathPayload() # Start of main", "sell copies of the Software, and to permit persons to", "AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload,", "streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\")", "\"/NCMD/\" + myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\"", "PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\",", "message Input 7 #publishBirth() elif metric.name == \"output/Device Input7\" or", "client.on_message = on_message client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" +", "newValue7 global newValue8 global newValue9 global newValue10 if tokens[0] ==", "we declated it in the DBIRTH newValue5 = metric.int_value print", "an NCMD used to tell the device/client application to resend", "from the gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the #", "# Font , font-color and font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size", "sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as mqtt import sparkplug_b as sparkplug", "instance to form batches from one or more sources. streammux", "Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0)", "PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0,", "capsfilter \\n\") print(\"Creating Video Converter \\n\") # Adding videoconvert ->", "Note that the pyds module allocates a buffer for the", "Value: {}\".format(newValue1)) # Create the DDATA payload - Use the", "Variables serverUrl = \"localhost\" myGroupId = \"Sparkplug B Devices\" myNodeName", "Device_Metric1 = 6 Device_Metric2 = 7 Device_Metric3 = 8 Device_Metric4", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue)", "through config file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie:", "PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET", "Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0)", "frame_numberx ) addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload,", "PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI", "1.0, 1.0) # Text background color py_nvosd_text_params.set_bg_clr = 1 #", "declated it in the DBIRTH newValue = metric.int_value print (\"CMD", "MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish", "import time, threading import random import string import gi gi.require_version('Gst',", "Device_Output6 = 27 Device_Output7 = 28 Device_Output8 = 29 Device_Output9", "# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO", "PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP", "how we declated it in the DBIRTH newValue10 = metric.int_value", "vidconvsrc: sys.stderr.write(\" Unable to create videoconvert \\n\") # nvvideoconvert to", "or metric.alias == AliasMap.Device_Metric2: # This is a metric we", "= Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink: sys.stderr.write(\" Unable to create", "message for output/Device Input2 - New Value: {}\".format(newValue2)) # Create", "Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId", "(\"CMD message for output/Device Input4 - New Value: {}\".format(newValue4)) #", "of charge, to any person obtaining a # copy of", "59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR = 56", "break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list", "it in the DBIRTH newValue9 = metric.int_value print (\"CMD message", "\"output/Device Input7\" or metric.alias == AliasMap.Device_Input7: # This is a", "14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN = 11", "reconnect then subscriptions will be renewed. client.subscribe(\"spBv1.0/\" + myGroupId +", "before publishing a DDATA message. # We know this is", "declated it in the DBIRTH newValue7 = metric.int_value print (\"CMD", "\" + metric.name) else: print (\"Unknown command...\") print (\"Done publishing\")", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "know this is an Boolean because of how we declated", "# raw formats are supported by nvvideoconvert; # Say YUYV", "= 4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE =", "+ myNodeName + \"/#\") ###################################################################### ###################################################################### # The callback for", "this were a real output we'd write to the output", "Publish the initial data with the Device BIRTH certificate totalByteArray", "AliasMap.Reboot, MetricDataType.Boolean, False) # Publish the node birth certificate byteArray", "4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync = false to avoid", "we'd write to the output and then read it back", "PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE", "output we'd write to the output and then read it", "0.0, 0.0, 1.0) # Using pyds.get_string() to get display_text as", "Input2 - New Value: {}\".format(newValue2)) # Create the DDATA payload", "FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN", "= 59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR =", "and DBIRTH again. MQTT Engine will send this NCMD to", "bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\",", "== \"output/Device Input2\" or metric.alias == AliasMap.Device_Input2: # This is", "elif metric.name == \"output/Device Input3\" or metric.alias == AliasMap.Device_Input3: #", "== AliasMap.Device_Input9: # This is a metric we declared in", "addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10,", "raw format for many logi usb cams # In case", "it receives an NDATA or DDATA with a metric that", "as sparkplug import time import time, threading import random import", "late frame drops at the display-sink sink.set_property('sync', False) print(\"Adding elements", "for clients that have a pool of MQTT servers #", "77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK = 74", "PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0,", "is the common # raw format for many logi usb", "27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK = 24", "3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON = 0", "of how we declated it in the DBIRTH newValue10 =", "\"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod = 5000 myUsername = \"admin\"", "% newValue) # Create the DDATA payload - use the", "\") return # Retrieve batch metadata from the gst_buffer #", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\",", "code \"+str(rc)) sys.exit() global myGroupId global myNodeName # Subscribing in", "2 #publishBirth() elif metric.name == \"output/Device Input2\" or metric.alias ==", "charge, to any person obtaining a # copy of this", "PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0,", "= metric.boolean_value print (\"CMD message for output/Device Metric3 - New", "addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish a message data", "sparkplug.getNodeDeathPayload() # Start of main program - Set up the", "in the DBIRTH newValue4 = metric.int_value print (\"CMD message for", "29 Device_Output9 = 30 Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH =", "payload = sparkplug.getNodeBirthPayload() # Set up the Node Controls addMetric(payload,", "###################################################################### # Publish the NBIRTH certificate ###################################################################### def publishNodeBirth(): print", "\\n \") pipeline = Gst.Pipeline() if not pipeline: sys.stderr.write(\" Unable", "rights to use, copy, modify, merge, publish, distribute, sublicense, #", "\"/NBIRTH/\" + myNodeName, byteArray, 0, False) ###################################################################### ###################################################################### # Publish", "import is_aarch64 from common.bus_call import bus_call from sparkplug_b import *", "Reading the display_text field here will return the C address", ") addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\",", "of gst_buffer as input, which is obtained with hash(gst_buffer) batch_meta", "(\"CMD message for output/Device Input8 - New Value: {}\".format(newValue8)) #", "\"config_infer_primary_yoloV3.txt\") # Set sync = false to avoid late frame", "PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer = info.get_buffer() if", "osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### # Create the node death payload", "= 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK =", "Use nvinfer to run inferencing on camera's output, # behaviour", "create egl sink \\n\") print(\"Playing cam %s \" %args[1]) caps_v4l2src.set_property('caps',", "PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN", "addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7,", "we must publish a DDATA with the new output #", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1,", "print (\"CMD message for output/Device Input8 - New Value: {}\".format(newValue8))", "PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT", "sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics: if metric.name == \"Node", "= 30 Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER", "batches from one or more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\")", "compute by # videoconvert doing passthrough (TODO we need to", "Source element for reading from the file print(\"Creating Source \\n", "the next MQTT server in the # list of available", "obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0,", "# Publish a message Input 3 #publishBirth() elif metric.name ==", "for when the client receives a CONNACK response from the", "0, False) # Publish a message Input 10 #publishBirth() elif", "it in the DBIRTH newValue4 = metric.int_value print (\"CMD message", "Now set the offsets where the string should appear py_nvosd_text_params.x_offset", "v4l2src capsfilter \\n\") print(\"Creating Video Converter \\n\") # Adding videoconvert", "PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK", "+ myNodeName + \"/\" + myDeviceName, byteArray, 0, False) #publishBirth()", "to connect to. print (\"'Node Control/Next Server' is not implemented", "client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\" + myNodeName, byteArray, 0, False)", "function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params = display_meta.text_params[0] #", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6)", "# Set sync = false to avoid late frame drops", "Device_Metric0 = 5 Device_Metric1 = 6 Device_Metric2 = 7 Device_Metric3", "device/client # application if it receives an NDATA or DDATA", "message and we're emulating an output. # So, on incoming", "Device_Input1 = 12 Device_Input2 = 13 Device_Input3 = 14 Device_Input4", "\\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\" Unable to", "available servers. This is used for clients that have a", "PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA =", "offsets where the string should appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset", "together # v4l2src -> nvvideoconvert -> mux -> # nvinfer", "= 19 Device_Input9 = 20 Device_Input10 = 21 Device_Output1 =", "= Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\" Unable to create", "counter2 = 0 Object1 = 0 Object2 = 0 Object3", "egl sink \\n\") print(\"Playing cam %s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw,", "newValue4 global newValue5 global newValue6 global newValue7 global newValue8 global", "###################################################################### def on_message(client, userdata, msg): print(\"Message arrived: \" + msg.topic)", "the # C address of gst_buffer as input, which is", "nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv: sys.stderr.write(\" Unable to", "gst_buffer as input, which is obtained with hash(gst_buffer) batch_meta =", "Finally render the osd output if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\",", "\"usb-cam-source\") if not source: sys.stderr.write(\" Unable to create Source \\n\")", "not sink: sys.stderr.write(\" Unable to create egl sink \\n\") print(\"Playing", "the DBIRTH newValue7 = metric.int_value print (\"CMD message for output/Device", "# Start of main program - Set up the MQTT", "source: sys.stderr.write(\" Unable to create Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\",", "B Devices\" myNodeName = \"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod =", "output/Device Input3 - New Value: {}\".format(newValue3)) # Create the DDATA", "sink pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### #", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish a message", "obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10 = obj_counter[newValue10]", "PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0,", "that time, the buffer would have # had got all", "#publishBirth() elif metric.name == \"output/Device Input1\" or metric.alias == AliasMap.Device_Input1:", "print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass #cleanup print(\"Exiting", "print (\"'Node Control/Next Server' is not implemented in this example\")", "\"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking", "newValue7) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,", "nvosd \\n\") # Finally render the osd output if is_aarch64():", "addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3,", "78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE = 75", "# Publish the BIRTH certificates ###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth()", "or substantial portions of the Software. # # THE SOFTWARE", "or metric.alias == AliasMap.Device_Input4: # This is a metric we", "print (\"CMD message for output/Device Metric3 - New Value: %r\"", "0 newValue2 = 0 newValue3 = 0 newValue4 = 0", "Input7 - New Value: {}\".format(newValue7)) # Create the DDATA payload", "False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) # Publish the", "to create Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not", "\"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16,", "how we declated it in the DBIRTH newValue8 = metric.int_value", "node birth certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId +", "= 2 Device_frame_numberx = 3 Device_num_rectsx = 4 Device_Metric0 =", "the # allocated string. Use pyds.get_string() to get the string", "nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### # Create the node", "OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR", "\"nvegl-transform\") print(\"Creating EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not", "AliasMap.Device_Input8: # This is a metric we declared in our", "= sparkplug.getDeviceBirthPayload() # Add some device metrics addMetric(payload, \"input/Frame Number\",", "sync = false to avoid late frame drops at the", "0, False) ###################################################################### ###################################################################### # Publish the DBIRTH certificate ######################################################################", "Metric2\" or metric.alias == AliasMap.Device_Metric2: # This is a metric", "num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is not None: try:", "must send all known metrics in # its original NBIRTH", "Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER = 78", "except StopIteration: break return Gst.PadProbeReturn.OK ###################################################################### def main(args): # Check", "CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION", "NCMD used to tell a device/client application to reboot #", "0) ###################################################################### # Create the node death payload deathPayload =", "61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA", "a superset of raw formats are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\",", "+ \"/DDATA/\" + myNodeName + \"/\" + myDeviceName, byteArray, 0,", "newValue1 = 0 newValue2 = 0 newValue3 = 0 newValue4", "message Input 1 #publishBirth() elif metric.name == \"output/Device Input1\" or", "message for output/Device Input6 - New Value: {}\".format(newValue6)) # Create", "the inputs addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx )", "ownership of the underlying memory # in the C code,", "== 0: print(\"Connected with result code \"+str(rc)) else: print(\"Failed to", "0 newValue1 = 0 newValue2 = 0 newValue3 = 0", "(c) 2020, NVIDIA CORPORATION. All rights reserved. # # Permission", "message is received from the server. ###################################################################### def on_message(client, userdata,", "Video Converter \\n\") # Adding videoconvert -> nvvideoconvert as not", "# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY", "9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN = 6", "the common # raw format for many logi usb cams", "= 10 Device_counter2 = 11 Device_Input1 = 12 Device_Input2 =", "-> nvvideoconvert -> nvosd -> video-renderer print(\"Linking elements in the", "addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish a message data", "Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6)", "and DBIRTH messages. publishBirth() elif metric.name == \"Node Control/Reboot\" or", "PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0", "DBIRTH. This is why the application must send all known", "Input1\" or metric.alias == AliasMap.Device_Input1: # This is a metric", "MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device", "would have # had got all the metadata. osdsinkpad =", "0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\",", "# Software is furnished to do so, subject to the", "Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # #", "AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish a message data byteArray =", "The casting is done by pyds.NvDsFrameMeta.cast() # The casting also", "fake a full reboot with a republishing of the NBIRTH", "elif metric.name == \"output/Device Metric3\" or metric.alias == AliasMap.Device_Metric3: #", "device metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,", "0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\",", "global Object4 global Object5 global Object6 global Object7 global Object8", "must publish a DDATA with the new output # value.", "<reponame>valdivj/Deepstream-IGN-Maker-YOLO #!/usr/bin/env python3 ################################################################################ # Copyright (c) 2020, NVIDIA CORPORATION.", "\"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop", "a DDATA message. # We know this is an Int16", "addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish a message data", "metric.name == \"output/Device Input9\" or metric.alias == AliasMap.Device_Input9: # This", "= caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\" Unable to get source", "newValue10 = metric.int_value print (\"CMD message for output/Device Input10 -", "Input 9 #publishBirth() elif metric.name == \"output/Device Input9\" or metric.alias", "data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\" +", "Publish a message Input 5 #publishBirth() elif metric.name == \"output/Device", "to whom the # Software is furnished to do so,", "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER", "publishBirth() elif metric.name == \"output/Device Metric2\" or metric.alias == AliasMap.Device_Metric2:", "the display-sink sink.set_property('sync', False) print(\"Adding elements to Pipeline \\n\") pipeline.add(source)", "# Use convertor to convert from NV12 to RGBA as", "###################################################################### def publishNodeBirth(): print (\"Publishing Node Birth\") # Create the", "all known metrics in # its original NBIRTH and DBIRTH", "so, subject to the following conditions: # # The above", "paho.mqtt.client as mqtt import sparkplug_b as sparkplug import time import", "+= 1 try: l_obj=l_obj.next except StopIteration: break # Acquiring a", "for devices that need a full application reset via a", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish a message", "because of how we declated it in the DBIRTH newValue", "30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE = 27", "the DBIRTH newValue1 = metric.int_value print (\"CMD message for output/Device", "if not caps_v4l2src: sys.stderr.write(\" Unable to create v4l2src capsfilter \\n\")", "Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0)", "not streammux: sys.stderr.write(\" Unable to create NvStreamMux \\n\") # Use", "metric.alias == AliasMap.Device_Metric3: # This is a metric we declared", "# Set up the Node Controls addMetric(payload, \"Node Control/Next Server\",", "global newValue2 global newValue3 global newValue4 global newValue5 global newValue6", "disconnect from the current MQTT server and connect to the", "Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16,", "0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\",", "ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\",", "# value. If this were a real output we'd write", "None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish a message data byteArray", "\"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16,", ", font-color and font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size = 10", "+ myGroupId + \"/DBIRTH/\" + myNodeName + \"/\" + myDeviceName,", "def main(args): # Check input arguments if len(args) != 2:", "Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5)", "the following conditions: # # The above copyright notice and", "l_obj=frame_meta.obj_meta_list while l_obj is not None: try: # Casting l_obj.data", "AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish a message data byteArray =", "while l_frame is not None: try: # Note that l_frame.data", "myNodeName, byteArray, 0, False) ###################################################################### ###################################################################### # Publish the DBIRTH", "# Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id]", "0 Object5 = 0 Object6 = 0 Object7 = 0", "IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS", "publishDeviceBirth(): print (\"Publishing Device Birth\") # Get the payload payload", "addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish a message data", "not vidconvsrc: sys.stderr.write(\" Unable to create videoconvert \\n\") # nvvideoconvert", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5)", "the string content. py_nvosd_text_params.display_text = \"Frame Number={} Number of Objects={}", "pipeline.add(sink) if is_aarch64(): pipeline.add(transform) # we link the elements together", "we declated it in the DBIRTH newValue4 = metric.int_value print", "+ myNodeName + \"/\" + myDeviceName, totalByteArray, 0, False) ######################################################################", "nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) # create an event loop and", "or DBIRTH. This is why the application must send all", "pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while l_frame is not None: try:", "9 Device_counter1 = 10 Device_counter2 = 11 Device_Input1 = 12", "with result code \"+str(rc)) else: print(\"Failed to connect with result", "in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting pipeline", "frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is not None:", "of inferencing is set through config file pgie = Gst.ElementFactory.make(\"nvinfer\",", "MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device", "Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2 =", "# the garbage collector will claim it when this probe", "of how we declated it in the DBIRTH newValue4 =", "MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\")", "PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0,", "PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0,", "string. Use pyds.get_string() to get the string content. py_nvosd_text_params.display_text =", "Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\" Unable to create capsfilter", "PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0,", "== \"DCMD\") and tokens[3] == myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload)", "# Publish a message Input 10 #publishBirth() elif metric.name ==", "!= 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0]) sys.exit(1) # Standard", "NBIRTH and DBIRTH messages. publishBirth() elif metric.name == \"Node Control/Reboot\"", "Use convertor to convert from NV12 to RGBA as required", "###################################################################### # The callback for when a PUBLISH message is", "in # all copies or substantial portions of the Software.", "if not sinkpad: sys.stderr.write(\" Unable to get the sink pad", "threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run()", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish", "(\"CMD message for output/Device Metric4 - New Value: {}\".format(newValue)) #", "all the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\"", "events for _ in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo()", "or metric.alias == AliasMap.Device_Input3: # This is a metric we", "or metric.alias == AliasMap.Reboot: # 'Node Control/Reboot' is an NCMD", "the server. ###################################################################### def on_connect(client, userdata, flags, rc): if rc", "60) WAIT_SECONDS = 1 frame_numberx = 0 num_rectsx = 0", "NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE", "16 Device_Input6 = 17 Device_Input7 = 18 Device_Input8 = 19", "Unable to create NvStreamMux \\n\") # Use nvinfer to run", "= 4 Device_Metric0 = 5 Device_Metric1 = 6 Device_Metric2 =", "== AliasMap.Device_Input10: # This is a metric we declared in", "Engine will send this NCMD to a device/client # application", "= 0 Object4 = 0 Object5 = 0 Object6 =", "files (the \"Software\"), # to deal in the Software without", "without restriction, including without limitation # the rights to use,", "in # the C code so downstream plugins can still", "myGroupId + \"/NBIRTH/\" + myNodeName, byteArray, 0, False) ###################################################################### ######################################################################", "byteArray, 0, False) # Publish a message Input 1 #publishBirth()", "it in the DBIRTH newValue6 = metric.int_value print (\"CMD message", "elif metric.name == \"output/Device Input8\" or metric.alias == AliasMap.Device_Input8: #", "Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT", "= 0 class AliasMap: Next_Server = 0 Rebirth = 1", "MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node", "inboundPayload.metrics: if metric.name == \"Node Control/Next Server\" or metric.alias ==", "THE SOFTWARE. ################################################################################ import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client", "NDATA or DDATA with a metric that was not published", "Input 5 #publishBirth() elif metric.name == \"output/Device Input5\" or metric.alias", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish a", "= 1 # set(red, green, blue, alpha); set to Black", "of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1]", "we link the elements together # v4l2src -> nvvideoconvert ->", "Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0)", "AliasMap.Rebirth: # 'Node Control/Rebirth' is an NCMD used to tell", "\"output/Device Metric4\" or metric.alias == AliasMap.Device_Metric4: # This is a", "of the Software, and to permit persons to whom the", "of how we declated it in the DBIRTH newValue3 =", "\"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16,", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish a", "metric.alias == AliasMap.Reboot: # 'Node Control/Reboot' is an NCMD used", "pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL) if __name__ == '__main__': sys.exit(main(sys.argv))", "19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG = 16", "output and then read it back # before publishing a", "distribute, sublicense, # and/or sell copies of the Software, and", "published in the # original NBIRTH or DBIRTH. This is", "Value: {}\".format(newValue)) # Create the DDATA payload - Use the", "(\"CMD message for output/Device Input2 - New Value: {}\".format(newValue2)) #", "PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0,", "mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS = 1 frame_numberx = 0 num_rectsx", "addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4,", "num_rects=0 gst_buffer = info.get_buffer() if not gst_buffer: print(\"Unable to get", "Input5\" or metric.alias == AliasMap.Device_Input5: # This is a metric", "to get sink pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0)", "PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR", "0.0, 1.0) # Using pyds.get_string() to get display_text as string", "PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0,", "and connect to the next MQTT server in the #", "display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except", "to the next MQTT server in the # list of", "case, we fake a full reboot with a republishing of", "PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0,", "byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\" + myNodeName", "# Add some device metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16,", "server. ###################################################################### def on_message(client, userdata, msg): print(\"Message arrived: \" +", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3,", "application to reboot # This can be used for devices", "or metric.alias == AliasMap.Next_Server: # 'Node Control/Next Server' is an", "WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING", "PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE", "print (\"CMD message for output/Device Input9 - New Value: {}\".format(newValue9))", "addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3,", "sys.stderr.write(\" Unable to create nvvidconv \\n\") # Create OSD to", "in the # list of available servers. This is used", "import string import gi gi.require_version('Gst', '1.0') from gi.repository import GObject,", "False) client.connect(serverUrl, 1883, 60) # Publish the birth certificates publishBirth()", "Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\",", "Server\" or metric.alias == AliasMap.Next_Server: # 'Node Control/Next Server' is", "= 41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET =", "\") pipeline = Gst.Pipeline() if not pipeline: sys.stderr.write(\" Unable to", "and DBIRTH # messages. publishBirth() elif metric.name == \"output/Device Metric2\"", "else: print(\"Failed to connect with result code \"+str(rc)) sys.exit() global", "Input9\" or metric.alias == AliasMap.Device_Input9: # This is a metric", "= 18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT =", "# This can be used for devices that need a", "False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\",", "\"+str(rc)) else: print(\"Failed to connect with result code \"+str(rc)) sys.exit()", "nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd: sys.stderr.write(\" Unable to", "of this software and associated documentation files (the \"Software\"), #", "application to resend # its full NBIRTH and DBIRTH again.", "myDeviceName, byteArray, 0, False) # Publish a message Input 6", "###################################################################### ###################################################################### # Publish the DBIRTH certificate ###################################################################### def publishDeviceBirth():", "we declared in our DBIRTH message and we're emulating an", "py_nvosd_text_params.display_text = \"Frame Number={} Number of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects,", "Device_Metric3 = 8 Device_Metric4 = 9 Device_counter1 = 10 Device_counter2", "= 27 Device_Output7 = 28 Device_Output8 = 29 Device_Output9 =", "Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2)", "False) # Publish a message Input 10 #publishBirth() elif metric.name", "# Create the node birth payload payload = sparkplug.getNodeBirthPayload() #", "Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\")", "AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload,", "print(\"Message arrived: \" + msg.topic) tokens = msg.topic.split(\"/\") global newValue1", "\"/NDEATH/\" + myNodeName, deathByteArray, 0, False) client.connect(serverUrl, 1883, 60) #", "myDeviceName, byteArray, 0, False) # Publish a message Input 3", "AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload,", "the osd element, since by that time, the buffer would", "Subscribing in on_connect() means that if we lose the connection", "\"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\",", "PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE", "get the string content. py_nvosd_text_params.display_text = \"Frame Number={} Number of", "False) # Publish a message Input 8 #publishBirth() elif metric.name", "False) # Sit and wait for inbound or outbound events", "PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0,", "global Object2 global Object3 global Object4 global Object5 global Object6", "0 num_rectsx = 0 counter1 = 0 counter2 = 0", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue)", "the converted RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not", "known metrics in # its original NBIRTH and DBIRTH messages.", "that have a pool of MQTT servers # to connect", "receives an NDATA or DDATA with a metric that was", "not caps_v4l2src: sys.stderr.write(\" Unable to create v4l2src capsfilter \\n\") print(\"Creating", "obj_counter[newValue8] Object9 = obj_counter[newValue9] Object10 = obj_counter[newValue10] # Now set", "a buffer for the string, and the # memory will", "tokens = msg.topic.split(\"/\") global newValue1 global newValue2 global newValue3 global", "of the Software. # # THE SOFTWARE IS PROVIDED \"AS", "not pipeline: sys.stderr.write(\" Unable to create Pipeline \\n\") # Source", "New Value: {}\".format(newValue2)) # Create the DDATA payload - Use", "PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH", "PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer = info.get_buffer() if not", "0 Rebirth = 1 Reboot = 2 Device_frame_numberx = 3", "(\"Done publishing\") ##################################################################### ###################################################################### ###################################################################### # Publish the BIRTH certificates", "metric in inboundPayload.metrics: if metric.name == \"Node Control/Next Server\" or", "NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT", "8 Device_Metric4 = 9 Device_counter1 = 10 Device_counter2 = 11", "%args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640)", "file print(\"Creating Source \\n \") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if", "copy, modify, merge, publish, distribute, sublicense, # and/or sell copies", "to create v4l2src capsfilter \\n\") print(\"Creating Video Converter \\n\") #", "video-renderer print(\"Linking elements in the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc)", "OSD to draw on the converted RGBA buffer nvosd =", "# Note that pyds.gst_buffer_get_nvds_batch_meta() expects the # C address of", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8,", "metric.name == \"output/Device Input5\" or metric.alias == AliasMap.Device_Input5: # This", "%r\" % newValue) # Create the DDATA payload - use", "gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst from common.is_aarch_64 import", "videoconvert to make sure a superset of raw formats are", "elements in the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad", "streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync =", "newValue3) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "Object1 = 0 Object2 = 0 Object3 = 0 Object4", "OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE", "myDeviceName = \"XavierNX\" publishPeriod = 5000 myUsername = \"admin\" myPassword", "\"output/Device Metric3\" or metric.alias == AliasMap.Device_Metric3: # This is a", "to convert from NV12 to RGBA as required by nvosd", "or metric.alias == AliasMap.Rebirth: # 'Node Control/Rebirth' is an NCMD", "the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if not osdsinkpad: sys.stderr.write(\" Unable", "= 9 Device_counter1 = 10 Device_counter2 = 11 Device_Input1 =", "PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR", "the NBIRTH certificate ###################################################################### def publishNodeBirth(): print (\"Publishing Node Birth\")", "message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\"", "DBIRTH messages. publishBirth() elif metric.name == \"Node Control/Reboot\" or metric.alias", "# to deal in the Software without restriction, including without", "had got all the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if not", "'1.0') from gi.repository import GObject, Gst from common.is_aarch_64 import is_aarch64", "import GObject, Gst from common.is_aarch_64 import is_aarch64 from common.bus_call import", "- use the alias because this isn't the DBIRTH payload", "SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR", "BIRTH certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\"", "MetricDataType.Int16, newValue3) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "newValue10 = 0 class AliasMap: Next_Server = 0 Rebirth =", "nvvidconv \\n\") # Create OSD to draw on the converted", "(\"Publishing Node Birth\") # Create the node birth payload payload", "this example\") elif metric.name == \"Node Control/Rebirth\" or metric.alias ==", "metric.alias == AliasMap.Device_Input9: # This is a metric we declared", "\"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16,", "5 #publishBirth() elif metric.name == \"output/Device Input5\" or metric.alias ==", "0 Object9 = 0 Object10 = 0 newValue1 = 0", "in # its original NBIRTH and DBIRTH messages. publishBirth() elif", "The casting also keeps ownership of the underlying memory #", "\"/\" + myDeviceName, byteArray, 0, False) #global newValue4 #publishBirth() elif", "message Input 2 #publishBirth() elif metric.name == \"output/Device Input2\" or", "supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc: sys.stderr.write(\" Unable", "0 newValue3 = 0 newValue4 = 0 newValue5 = 0", "THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE", "other elements print(\"Creating Pipeline \\n \") pipeline = Gst.Pipeline() if", "PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE", "above copyright notice and this permission notice shall be included", "OR OTHER # DEALINGS IN THE SOFTWARE. ################################################################################ import sys", "{}\".format(newValue)) # Create the DDATA payload - Use the alias", "NCMD to a device/client # application if it receives an", "PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0,", "Device Birth\") # Get the payload payload = sparkplug.getDeviceBirthPayload() #", "+ \"/NDEATH/\" + myNodeName, deathByteArray, 0, False) client.connect(serverUrl, 1883, 60)", "l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id] += 1", "it. Otherwise # the garbage collector will claim it when", "garbage collector will claim it when this probe function exits.", "2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0]) sys.exit(1) # Standard GStreamer", "PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE", "A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL #", "PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE", "None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish a message data byteArray", "# Finally render the osd output if is_aarch64(): transform =", "myDeviceName, byteArray, 0, False) #global newValue4 #publishBirth() elif metric.name ==", "an NCMD used to tell the device/client application to #", "the osd output if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating", "of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### # Create the", "addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16,", "the gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the # C", "46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE = 43", "Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0)", "+ myNodeName, deathByteArray, 0, False) client.connect(serverUrl, 1883, 60) # Publish", "MQTT server and connect to the next MQTT server in", "CORPORATION. All rights reserved. # # Permission is hereby granted,", "PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0,", "and wait for inbound or outbound events for _ in", "to confirm this) # videoconvert to make sure a superset", "myNodeName + \"/\" + myDeviceName, byteArray, 0, False) # Sit", "Object6 global Object7 global Object8 global Object9 global Object10 #Intiallizing", "if tokens[0] == \"spBv1.0\" and tokens[1] == myGroupId and (tokens[2]", "New Value: {}\".format(newValue)) # Create the DDATA payload - Use", "= bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\" + myNodeName +", "try: l_obj=l_obj.next except StopIteration: break # Acquiring a display meta", "here will return the C address of the # allocated", "if not osdsinkpad: sys.stderr.write(\" Unable to get sink pad of", "since by that time, the buffer would have # had", "to it loop = GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch() bus.connect", "PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0,", "Object5 = obj_counter[newValue5] Object6 = obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8", "1 # set(red, green, blue, alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0,", "of raw formats are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if", "AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) #", "= 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT =", "= 52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE =", "appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset = 12 # Font ,", "= sparkplug.getDdataPayload() # Add some random data to the inputs", "gi.repository import GObject, Gst from common.is_aarch_64 import is_aarch64 from common.bus_call", "a message Input 8 #publishBirth() elif metric.name == \"output/Device Input8\"", "this is an Int16 because of how we declated it", "Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0)", "gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the # C address", "if not srcpad: sys.stderr.write(\" Unable to get source pad of", "print (\"CMD message for output/Device Input10 - New Value: {}\".format(newValue10))", "0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\",", "server in the # list of available servers. This is", "= 0 Object6 = 0 Object7 = 0 Object8 =", "declated it in the DBIRTH newValue2 = metric.int_value print (\"CMD", "51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH = 48", "addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9,", "Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0)", "= 0 newValue7 = 0 newValue8 = 0 newValue9 =", "1 Reboot = 2 Device_frame_numberx = 3 Device_num_rectsx = 4", "in the DBIRTH newValue3 = metric.int_value print (\"CMD message for", "} num_rects=0 gst_buffer = info.get_buffer() if not gst_buffer: print(\"Unable to", "AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR", "Object3 = 0 Object4 = 0 Object5 = 0 Object6", "21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP = 18", "the sink pad of streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if", "AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload,", "metric.int_value print (\"CMD message for output/Device Input9 - New Value:", "{}\".format(newValue5)) # Create the DDATA payload - Use the alias", "DBIRTH newValue5 = metric.int_value print (\"CMD message for output/Device Input5", "= 0 Object9 = 0 Object10 = 0 newValue1 =", "for output/Device Input9 - New Value: {}\".format(newValue9)) # Create the", "# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. #", "OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,", "connect to. print (\"'Node Control/Next Server' is not implemented in", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish a message", "Object2 global Object3 global Object4 global Object5 global Object6 global", "light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ###################################################################### # The", "on_message(client, userdata, msg): print(\"Message arrived: \" + msg.topic) tokens =", "New Value: {}\".format(newValue3)) # Create the DDATA payload - Use", "or metric.alias == AliasMap.Device_Input6: # This is a metric we", "to the following conditions: # # The above copyright notice", "Standard GStreamer initialization GObject.threads_init() Gst.init(None) # Create gstreamer elements #", "AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello", "Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\",", "Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) # Using pyds.get_string() to get", "None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish a message data byteArray", "a message Input 3 #publishBirth() elif metric.name == \"output/Device Input3\"", "= 12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT =", "metric.int_value print (\"CMD message for output/Device Input3 - New Value:", "caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\" Unable to", "YUYV is unsupported - which is the common # raw", "sparkplug_b import * import pyds # Application Variables serverUrl =", "claimed by the garbage collector. # Reading the display_text field", "AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload,", "{}\".format(newValue4)) # Create the DDATA payload - Use the alias", "elif metric.name == \"output/Device Input7\" or metric.alias == AliasMap.Device_Input7: #", "GObject.threads_init() Gst.init(None) # Create gstreamer elements # Create Pipeline element", "# nvinfer -> nvvideoconvert -> nvosd -> video-renderer print(\"Linking elements", "PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0,", "elif metric.name == \"output/Device Metric2\" or metric.alias == AliasMap.Device_Metric2: #", "elif metric.name == \"output/Device Input4\" or metric.alias == AliasMap.Device_Input4: #", "PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0,", "\\n\") # Adding videoconvert -> nvvideoconvert as not all #", "# Publish a message Input 7 #publishBirth() elif metric.name ==", "display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params = display_meta.text_params[0] # Setting display", "+ metric.name) else: print (\"Unknown command...\") print (\"Done publishing\") #####################################################################", "not nvvidconvsrc: sys.stderr.write(\" Unable to create Nvvideoconvert \\n\") caps_vidconvsrc =", "initialization GObject.threads_init() Gst.init(None) # Create gstreamer elements # Create Pipeline", "memory # in the C code, so the Python garbage", "4 #publishBirth() elif metric.name == \"output/Device Input4\" or metric.alias ==", "frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is not None: try: # Casting", "# nvvideoconvert, GStreamer plugins' capability negotiation # shall be intelligent", "(\"'Node Control/Next Server' is not implemented in this example\") elif", "# Publish a message Input 4 #publishBirth() elif metric.name ==", "\"hello device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number", "sinkpad: sys.stderr.write(\" Unable to get the sink pad of streammux", "content. py_nvosd_text_params.display_text = \"Frame Number={} Number of Objects={} Bird_count={} Person_count={}\".format(frame_number,", "Publish a message Input 4 #publishBirth() elif metric.name == \"output/Device", "PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0,", "the current MQTT server and connect to the next MQTT", "display-sink sink.set_property('sync', False) print(\"Adding elements to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src)", "metric.int_value print (\"CMD message for output/Device Input4 - New Value:", "PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0,", "= 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT = 58", "OTHER # DEALINGS IN THE SOFTWARE. ################################################################################ import sys sys.path.append('../')", "PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0,", "is received from the server. ###################################################################### def on_message(client, userdata, msg):", "Object10) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "myNodeName + \"/\" + myDeviceName, byteArray, 0, False) #global newValue4", "with the Device BIRTH certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" +", "MetricDataType.Int16, newValue9) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "New Value: {}\".format(newValue8)) # Create the DDATA payload - Use", "Unable to create egl sink \\n\") print(\"Playing cam %s \"", "\"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16,", "Value: {}\".format(newValue6)) # Create the DDATA payload - Use the", "bus.add_signal_watch() bus.connect (\"message\", bus_call, loop) # Lets add probe to", "videoconvert \\n\") # nvvideoconvert to convert incoming raw buffers to", "'writes' to the output we must publish a DDATA with", "if not sink: sys.stderr.write(\" Unable to create egl sink \\n\")", "Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7)", "COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER", "metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload, \"input/Device", "PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer = info.get_buffer() if not gst_buffer: print(\"Unable", "at the display-sink sink.set_property('sync', False) print(\"Adding elements to Pipeline \\n\")", "batch metadata from the gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta() expects", "msg.topic) tokens = msg.topic.split(\"/\") global newValue1 global newValue2 global newValue3", "memory will not be claimed by the garbage collector. #", "21 Device_Output1 = 22 Device_Output2 = 23 Device_Output3 = 24", "myNodeName + \"/\" + myDeviceName, byteArray, 0, False) #publishBirth() elif", "All rights reserved. # # Permission is hereby granted, free", "\\n\") print(\"Playing cam %s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps',", "convert incoming raw buffers to NVMM Mem (NvBufSurface API) nvvidconvsrc", "= 28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA =", "num_rectsx global Object1 global Object2 global Object3 global Object4 global", "client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\" + myNodeName + \"/#\") client.subscribe(\"spBv1.0/\"", "+ msg.topic) tokens = msg.topic.split(\"/\") global newValue1 global newValue2 global", "on_connect(client, userdata, flags, rc): if rc == 0: print(\"Connected with", "= 1 frame_numberx = 0 num_rectsx = 0 counter1 =", "passthrough (TODO we need to confirm this) # videoconvert to", "myNodeName + \"/\" + myDeviceName, totalByteArray, 0, False) ###################################################################### ######################################################################", "message for output/Device Metric4 - New Value: {}\".format(newValue)) # Create", "a connection of other elements print(\"Creating Pipeline \\n \") pipeline", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16,", "= 0 newValue3 = 0 newValue4 = 0 newValue5 =", "DBIRTH newValue2 = metric.int_value print (\"CMD message for output/Device Input2", "(\"CMD message for output/Device Metric3 - New Value: %r\" %", "+ myGroupId + \"/NDEATH/\" + myNodeName, deathByteArray, 0, False) client.connect(serverUrl,", "\"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\",", "publishDeviceBirth() ###################################################################### ###################################################################### # Publish the NBIRTH certificate ###################################################################### def", "AliasMap.Device_Metric4: # This is a metric we declared in our", "mux -> # nvinfer -> nvvideoconvert -> nvosd -> video-renderer", "== \"NCMD\" or tokens[2] == \"DCMD\") and tokens[3] == myNodeName:", "and then read it back # before publishing a DDATA", "l_frame.data needs a cast to pyds.NvDsFrameMeta # The casting is", "publish, distribute, sublicense, # and/or sell copies of the Software,", "code \"+str(rc)) else: print(\"Failed to connect with result code \"+str(rc))", "PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT", "for metric in inboundPayload.metrics: if metric.name == \"Node Control/Next Server\"", "a republishing of the NBIRTH and DBIRTH # messages. publishBirth()", "print (\"CMD message for output/Device Input7 - New Value: {}\".format(newValue7))", "sys.stderr.write(\" Unable to create egl sink \\n\") print(\"Playing cam %s", "for many logi usb cams # In case we have", "loop and feed gstreamer bus mesages to it loop =", "= 22 Device_Output2 = 23 Device_Output3 = 24 Device_Output4 =", "= 0 newValue2 = 0 newValue3 = 0 newValue4 =", "because of how we declated it in the DBIRTH newValue6", "###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx global Object1 global", "PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD", "rc): if rc == 0: print(\"Connected with result code \"+str(rc))", "for output/Device Input7 - New Value: {}\".format(newValue7)) # Create the", "= display_meta.text_params[0] # Setting display text to be shown on", "If this were a real output we'd write to the", "\"convertor_src1\") if not vidconvsrc: sys.stderr.write(\" Unable to create videoconvert \\n\")", "DDATA message. # We know this is an Int16 because", "MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device", "to NVMM Mem (NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if", "- New Value: {}\".format(newValue2)) # Create the DDATA payload -", "pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform) # we link the elements", "AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish a message data byteArray =", "frame_numberx global num_rectsx global Object1 global Object2 global Object3 global", "pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### # Create", "= 37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT =", "devices that need a full application reset via a soft", "in the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad =", "# In case we have a camera with raw format", "# the rights to use, copy, modify, merge, publish, distribute,", "byteArray, 0, False) # Publish a message Input 7 #publishBirth()", "Input4\" or metric.alias == AliasMap.Device_Input4: # This is a metric", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish", "AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish a message data byteArray =", "expects the # C address of gst_buffer as input, which", "AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True)", "for output/Device Input5 - New Value: {}\".format(newValue5)) # Create the", "\"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16,", "message for output/Device Input10 - New Value: {}\".format(newValue10)) # Create", "###################################################################### # Publish the BIRTH certificates ###################################################################### def publishBirth(): publishNodeBirth()", "except StopIteration: break obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next except StopIteration:", "the output we must publish a DDATA with the new", "newValue = metric.string_value print (\"CMD message for output/Device Metric4 -", "message for output/Device Input1 - New Value: {}\".format(newValue1)) # Create", "output/Device Input10 - New Value: {}\".format(newValue10)) # Create the DDATA", "MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) # Publish", "PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0,", "string should appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset = 12 #", "of other elements print(\"Creating Pipeline \\n \") pipeline = Gst.Pipeline()", "nvinfer to run inferencing on camera's output, # behaviour of", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES", "\"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx,", "metric.alias == AliasMap.Device_Input6: # This is a metric we declared", "Node Birth\") # Create the node birth payload payload =", "-> nvvideoconvert -> mux -> # nvinfer -> nvvideoconvert ->", "0 newValue8 = 0 newValue9 = 0 newValue10 = 0", "the DBIRTH newValue5 = metric.int_value print (\"CMD message for output/Device", "# behaviour of inferencing is set through config file pgie", "got all the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\") if not osdsinkpad:", "l_frame = batch_meta.frame_meta_list while l_frame is not None: try: #", "DBIRTH newValue = metric.int_value print (\"CMD message for output/Device Metric2", "Number={} Number of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1", "- New Value: {}\".format(newValue)) # Create the DDATA payload -", "print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except StopIteration: break return Gst.PadProbeReturn.OK", "not pgie: sys.stderr.write(\" Unable to create pgie \\n\") # Use", "time import time, threading import random import string import gi", "= 3 Device_num_rectsx = 4 Device_Metric0 = 5 Device_Metric1 =", "to RGBA as required by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\")", "nvinfer -> nvvideoconvert -> nvosd -> video-renderer print(\"Linking elements in", "pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if", "to get GstBuffer \") return # Retrieve batch metadata from", "it loop = GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\",", "addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish a message data", "myDeviceName, byteArray, 0, False) # Publish a message Input 1", "\\n \") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source: sys.stderr.write(\"", "{}\".format(newValue3)) # Create the DDATA payload - Use the alias", "print (\"Unknown command...\") print (\"Done publishing\") ##################################################################### ###################################################################### ###################################################################### #", "myDeviceName, byteArray, 0, False) # Publish a message Input 10", "of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2,", "1 py_nvosd_text_params = display_meta.text_params[0] # Setting display text to be", "nvvidconv: sys.stderr.write(\" Unable to create nvvidconv \\n\") # Create OSD", "inbound or outbound events for _ in range(1): time.sleep(1) client.loop()", "TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR", "have # had got all the metadata. osdsinkpad = nvosd.get_static_pad(\"sink\")", "Use the alias because this isn't the DBIRTH payload =", "we declated it in the DBIRTH newValue10 = metric.int_value print", "free of charge, to any person obtaining a # copy", "a display meta object. The memory ownership remains in #", "on_connect client.on_message = on_message client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\"", "# The casting also keeps ownership of the underlying memory", "sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux: sys.stderr.write(\" Unable", "deal in the Software without restriction, including without limitation #", "# 'Node Control/Next Server' is an NCMD used to tell", "newValue3 = metric.int_value print (\"CMD message for output/Device Input3 -", "MetricDataType.Boolean, True) addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx )", "from one or more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if", "MetricDataType.Int16, newValue8) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "\"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16,", "CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR", "declated it in the DBIRTH newValue5 = metric.int_value print (\"CMD", "obtained with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while", "9 #publishBirth() elif metric.name == \"output/Device Input9\" or metric.alias ==", "# # The above copyright notice and this permission notice", "\"output/Device Input6\" or metric.alias == AliasMap.Device_Input6: # This is a", "sink \\n\") print(\"Playing cam %s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\"))", "be used for devices that need a full application reset", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish a", "# Check input arguments if len(args) != 2: sys.stderr.write(\"usage: %s", "Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\",", "Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean,", "the client receives a CONNACK response from the server. ######################################################################", "message for output/Device Input4 - New Value: {}\".format(newValue4)) # Create", "tell the device/client application to # disconnect from the current", "then read it back # before publishing a DDATA message.", "republishing of the NBIRTH and DBIRTH # messages. publishBirth() elif", "foo(): # Periodically publish some new data payload = sparkplug.getDdataPayload()", "+ myGroupId + \"/DDATA/\" + myNodeName + \"/\" + myDeviceName,", "newValue5) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480)", "= metric.int_value print (\"CMD message for output/Device Input5 - New", "copies of the Software, and to permit persons to whom", "DEALINGS IN THE SOFTWARE. ################################################################################ import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\")", "the pyds module allocates a buffer for the string, and", "Get the payload payload = sparkplug.getDeviceBirthPayload() # Add some device", "Pipeline element that will form a connection of other elements", "to deal in the Software without restriction, including without limitation", "incoming raw buffers to NVMM Mem (NvBufSurface API) nvvidconvsrc =", "python3 ################################################################################ # Copyright (c) 2020, NVIDIA CORPORATION. All rights", "or tokens[2] == \"DCMD\") and tokens[3] == myNodeName: inboundPayload =", "obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5 = obj_counter[newValue5]", "addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16,", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "format supported in # nvvideoconvert, GStreamer plugins' capability negotiation #", "event loop and feed gstreamer bus mesages to it loop", "OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.", "PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0,", "create NvStreamMux \\n\") # Use nvinfer to run inferencing on", "a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId +", "10 # set(red, green, blue, alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0,", "string, and the # memory will not be claimed by", "10 py_nvosd_text_params.y_offset = 12 # Font , font-color and font-size", "\"Software\"), # to deal in the Software without restriction, including", "PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer", "metric.alias == AliasMap.Device_Input5: # This is a metric we declared", "# Periodically publish some new data payload = sparkplug.getDdataPayload() #", "newValue3 global newValue4 global newValue5 global newValue6 global newValue7 global", "PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT", "Control/Rebirth\" or metric.alias == AliasMap.Rebirth: # 'Node Control/Rebirth' is an", "Server' is not implemented in this example\") elif metric.name ==", "message Input 4 #publishBirth() elif metric.name == \"output/Device Input4\" or", "object. The memory ownership remains in # the C code", "the underlying memory # in the C code, so the", "num_rectsx = 0 counter1 = 0 counter2 = 0 Object1", "6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE = 3", "Create Pipeline element that will form a connection of other", "obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9 = obj_counter[newValue9]", "original NBIRTH and DBIRTH messages. publishBirth() elif metric.name == \"Node", "including without limitation # the rights to use, copy, modify,", "Device_Metric2 = 7 Device_Metric3 = 8 Device_Metric4 = 9 Device_counter1", "in the # original NBIRTH or DBIRTH. This is why", "Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0)", "myNodeName + \"/#\") ###################################################################### ###################################################################### # The callback for when", "of the underlying memory # in the C code, so", "6 #publishBirth() elif metric.name == \"output/Device Input6\" or metric.alias ==", "we need to confirm this) # videoconvert to make sure", "pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform) #", "PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0,", "the string should appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset = 12", "+ \"/\" + myDeviceName, totalByteArray, 0, False) ###################################################################### ###################################################################### def", "sys.stderr.write(\" Unable to create videoconvert \\n\") # nvvideoconvert to convert", "to the output and then read it back # before", "metric.boolean_value print (\"CMD message for output/Device Metric3 - New Value:", "link the elements together # v4l2src -> nvvideoconvert -> mux", "elif metric.name == \"output/Device Input10\" or metric.alias == AliasMap.Device_Input10: #", "if not nvosd: sys.stderr.write(\" Unable to create nvosd \\n\") #", "22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW = 19", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16,", "global newValue8 global newValue9 global newValue10 if tokens[0] == \"spBv1.0\"", "to create Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not", "data with the Device BIRTH certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "be intelligent enough to reduce compute by # videoconvert doing", "New Value: {}\".format(newValue4)) # Create the DDATA payload - Use", "sparkplug.getDdataPayload() # Add some random data to the inputs addMetric(payload,", "in the C code, so the Python garbage collector will", "AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload,", "0 Object10 = 0 newValue1 = 0 newValue2 = 0", "Software, and to permit persons to whom the # Software", "Input3 - New Value: {}\".format(newValue3)) # Create the DDATA payload", "or more sources. streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux:", "the node birth payload payload = sparkplug.getNodeBirthPayload() # Set up", "4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE = 1", "The callback for when a PUBLISH message is received from", "# So, on incoming 'writes' to the output we must", "for when a PUBLISH message is received from the server.", "AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish the initial data with the", "== \"output/Device Input1\" or metric.alias == AliasMap.Device_Input1: # This is", "+ myGroupId + \"/NBIRTH/\" + myNodeName, byteArray, 0, False) ######################################################################", "we add probe to # the sink pad of the", "on the converted RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if", "that l_frame.data needs a cast to pyds.NvDsFrameMeta # The casting", "# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF", ") addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\",", "Device_Metric4 = 9 Device_counter1 = 10 Device_counter2 = 11 Device_Input1", "= 1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy", "outbound events for _ in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start()", "\\n\") # Use nvinfer to run inferencing on camera's output,", "None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish a message data byteArray", "\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #", "is not None: try: # Note that l_frame.data needs a", ") addMetric(payload, \"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device", "in the DBIRTH newValue5 = metric.int_value print (\"CMD message for", "%s <v4l2-device-path>\\n\" % args[0]) sys.exit(1) # Standard GStreamer initialization GObject.threads_init()", "22 Device_Output2 = 23 Device_Output3 = 24 Device_Output4 = 25", "SOFTWARE. ################################################################################ import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as", "= 30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE =", "phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot", "CONNACK response from the server. ###################################################################### def on_connect(client, userdata, flags,", "newValue) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "Retrieve batch metadata from the gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta()", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) #", "byteArray, 0, False) # Publish a message Input 8 #publishBirth()", "furnished to do so, subject to the following conditions: #", "65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR = 62", "= 22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW =", "# The above copyright notice and this permission notice shall", "for output/Device Input2 - New Value: {}\".format(newValue2)) # Create the", "the meta data generated, we add probe to # the", "except: pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL) if __name__ == '__main__':", "real output we'd write to the output and then read", "-> # nvinfer -> nvvideoconvert -> nvosd -> video-renderer print(\"Linking", "pool of MQTT servers # to connect to. print (\"'Node", "\\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL)", "set the offsets where the string should appear py_nvosd_text_params.x_offset =", "PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0,", "\"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) # Publish the node birth", "nvvideoconvert as not all # raw formats are supported by", "Input 6 #publishBirth() elif metric.name == \"output/Device Input6\" or metric.alias", "\\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ###################################################################### # Create the node death", "which is obtained with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame =", "None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish a message data byteArray", "sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as mqtt import sparkplug_b", "AliasMap.Device_Input7: # This is a metric we declared in our", "if is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) # create an event", "Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device Output10\",", "Converter \\n\") # Adding videoconvert -> nvvideoconvert as not all", "addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish a message data", "5000 myUsername = \"admin\" myPassword = \"<PASSWORD>\" client = mqtt.Client(serverUrl,", "0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input7\",", "IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish a message", "16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH = 13", "the DBIRTH newValue6 = metric.int_value print (\"CMD message for output/Device", "= 74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK =", "sys.stderr.write(\" Unable to create NvStreamMux \\n\") # Use nvinfer to", "(\"CMD message for output/Device Input3 - New Value: {}\".format(newValue3)) #", "Object1 global Object2 global Object3 global Object4 global Object5 global", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\",", "Create gstreamer elements # Create Pipeline element that will form", "= 43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS =", "# Use nvinfer to run inferencing on camera's output, #", "following conditions: # # The above copyright notice and this", "= obj_counter[newValue9] Object10 = obj_counter[newValue10] # Now set the offsets", "PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE", "{}\".format(newValue10)) # Create the DDATA payload - Use the alias", "Control/Next Server\" or metric.alias == AliasMap.Next_Server: # 'Node Control/Next Server'", "conditions: # # The above copyright notice and this permission", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) #", "or metric.alias == AliasMap.Device_Input9: # This is a metric we", "0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\",", "# Source element for reading from the file print(\"Creating Source", "- Use the alias because this isn't the DBIRTH payload", "Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv: sys.stderr.write(\" Unable to create nvvidconv", "create nvvidconv \\n\") # Create OSD to draw on the", "Device_frame_numberx = 3 Device_num_rectsx = 4 Device_Metric0 = 5 Device_Metric1", "# This is a metric we declared in our DBIRTH", "and associated documentation files (the \"Software\"), # to deal in", "newValue2) # Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "message Input 10 #publishBirth() elif metric.name == \"output/Device Input10\" or", "PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0,", "example\") elif metric.name == \"Node Control/Rebirth\" or metric.alias == AliasMap.Rebirth:", "New Value: {}\".format(newValue10)) # Create the DDATA payload - Use", "PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0,", "AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload,", "sys.stderr.write(\" Unable to create pgie \\n\") # Use convertor to", "Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3)", "full NBIRTH and DBIRTH again. MQTT Engine will send this", "result code \"+str(rc)) sys.exit() global myGroupId global myNodeName # Subscribing", "== AliasMap.Device_Input7: # This is a metric we declared in", "MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx )", "Adding videoconvert -> nvvideoconvert as not all # raw formats", "DBIRTH newValue3 = metric.int_value print (\"CMD message for output/Device Input3", "a device/client application to reboot # This can be used", "for output/Device Metric4 - New Value: {}\".format(newValue)) # Create the", "Object6 = obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9", "DBIRTH newValue7 = metric.int_value print (\"CMD message for output/Device Input7", "of MQTT servers # to connect to. print (\"'Node Control/Next", "pyds.NvDsFrameMeta # The casting is done by pyds.NvDsFrameMeta.cast() # The", "how we declated it in the DBIRTH newValue6 = metric.int_value", "# Publish a message data byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" +", "sparkplug.getDeviceBirthPayload() # Add some device metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx,", "pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) # create", "form a connection of other elements print(\"Creating Pipeline \\n \")", "blue, alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) #", "BIRTH certificates ###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### #", "# Retrieve batch metadata from the gst_buffer # Note that", "PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0,", "= obj_counter[newValue10] # Now set the offsets where the string", "probe to get informed of the meta data generated, we", "addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3,", "DBIRTH newValue = metric.string_value print (\"CMD message for output/Device Metric4", "67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE = 64", "unsupported - which is the common # raw format for", "New Value: {}\".format(newValue1)) # Create the DDATA payload - Use", "a # copy of this software and associated documentation files", "be included in # all copies or substantial portions of", "Input3\" or metric.alias == AliasMap.Device_Input3: # This is a metric", "sys.stderr.write(\" Unable to create Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\")", "18 Device_Input8 = 19 Device_Input9 = 20 Device_Input10 = 21", "metric.int_value print (\"CMD message for output/Device Input1 - New Value:", "client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\" + myNodeName + \"/\" +", "get source pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd)", "##################################################################### ###################################################################### ###################################################################### # Publish the BIRTH certificates ###################################################################### def", "76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK = 73", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16,", "(\"CMD message for output/Device Metric2 - New Value: {}\".format(newValue)) #", "\"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16,", "metric.int_value print (\"CMD message for output/Device Input5 - New Value:", "osdsinkpad: sys.stderr.write(\" Unable to get sink pad of nvosd \\n\")", "= msg.topic.split(\"/\") global newValue1 global newValue2 global newValue3 global newValue4", "addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8,", "output/Device Metric3 - New Value: %r\" % newValue) # Create", "or metric.alias == AliasMap.Device_Metric4: # This is a metric we", "newValue2 = metric.int_value print (\"CMD message for output/Device Input2 -", "the garbage collector. # Reading the display_text field here will", "newValue2 = 0 newValue3 = 0 newValue4 = 0 newValue5", "+ \"/\" + myDeviceName, byteArray, 0, False) #global newValue4 #publishBirth()", "to # disconnect from the current MQTT server and connect", "counter with 0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0,", "= on_connect client.on_message = on_message client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString())", "were a real output we'd write to the output and", "# # Permission is hereby granted, free of charge, to", "capability negotiation # shall be intelligent enough to reduce compute", "print (\"CMD message for output/Device Input3 - New Value: {}\".format(newValue3))", "the # Software is furnished to do so, subject to", "subject to the following conditions: # # The above copyright", "pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie: sys.stderr.write(\" Unable to", "the Device BIRTH certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId", "NCMD used to tell the device/client application to resend #", "create Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src:", "wait for inbound or outbound events for _ in range(1):", "we declated it in the DBIRTH newValue1 = metric.int_value print", "+ myNodeName + \"/\" + myDeviceName, byteArray, 0, False) #", "Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\" Unable to create v4l2src", "how we declated it in the DBIRTH newValue5 = metric.int_value", "value. If this were a real output we'd write to", "metadata from the gst_buffer # Note that pyds.gst_buffer_get_nvds_batch_meta() expects the", "keeps ownership of the underlying memory # in the C", "AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload,", "except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx =", "info.get_buffer() if not gst_buffer: print(\"Unable to get GstBuffer \") return", "Note that l_frame.data needs a cast to pyds.NvDsFrameMeta # The", "element, since by that time, the buffer would have #", "# Create Pipeline element that will form a connection of", "global Object9 global Object10 #Intiallizing object counter with 0. obj_counter", "myDeviceName, byteArray, 0, False) # Publish a message Input 2", "\"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS = 1 frame_numberx", "callback for when the client receives a CONNACK response from", "Control/Reboot' is an NCMD used to tell a device/client application", "documentation files (the \"Software\"), # to deal in the Software", "PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer = info.get_buffer()", "# Publish the DBIRTH certificate ###################################################################### def publishDeviceBirth(): print (\"Publishing", "modify, merge, publish, distribute, sublicense, # and/or sell copies of", "== \"Node Control/Next Server\" or metric.alias == AliasMap.Next_Server: # 'Node", "current MQTT server and connect to the next MQTT server", "intelligent enough to reduce compute by # videoconvert doing passthrough", "set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0) # Text background", "FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL", "know this is an Int16 because of how we declated", "get display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next", "# nvvideoconvert to convert incoming raw buffers to NVMM Mem", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16,", "PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE", "meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\",", "Input9 - New Value: {}\".format(newValue9)) # Create the DDATA payload", "Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0)", "Gst.Pipeline() if not pipeline: sys.stderr.write(\" Unable to create Pipeline \\n\")", "Unable to create pgie \\n\") # Use convertor to convert", "\"output/Device Input2\" or metric.alias == AliasMap.Device_Input2: # This is a", "8 #publishBirth() elif metric.name == \"output/Device Input8\" or metric.alias ==", "Add some device metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx", "import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as mqtt import", "or metric.alias == AliasMap.Device_Input2: # This is a metric we", "frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj", "certificate ###################################################################### def publishNodeBirth(): print (\"Publishing Node Birth\") # Create", "metric.alias == AliasMap.Device_Metric2: # This is a metric we declared", "(\"CMD message for output/Device Input1 - New Value: {}\".format(newValue1)) #", "IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER", "reserved. # # Permission is hereby granted, free of charge,", "\"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\", \"Broccli\",", "myDeviceName, byteArray, 0, False) # Publish a message Input 5", "that will form a connection of other elements print(\"Creating Pipeline", "PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG", "PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0,", "addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\",", "Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4)", "MetricDataType.Int16, newValue1) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "= mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS = 1 frame_numberx = 0", "elif metric.name == \"Node Control/Rebirth\" or metric.alias == AliasMap.Rebirth: #", "that pyds.gst_buffer_get_nvds_batch_meta() expects the # C address of gst_buffer as", "Check input arguments if len(args) != 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\"", "= metric.int_value print (\"CMD message for output/Device Input1 - New", "restriction, including without limitation # the rights to use, copy,", "to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) # Using pyds.get_string() to", "# Create the DDATA payload - Use the alias because", "code so downstream plugins can still access it. Otherwise #", "that need a full application reset via a soft reboot.", "79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS = 76", "\"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\",", "declated it in the DBIRTH newValue = metric.boolean_value print (\"CMD", "AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload,", "alias because this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload,", "NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR", "formats are supported by nvvideoconvert; # Say YUYV is unsupported", "addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish a message data", "== myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics:", "metric.alias == AliasMap.Next_Server: # 'Node Control/Next Server' is an NCMD", "# Publish a message Input 8 #publishBirth() elif metric.name ==", "MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish", "have a camera with raw format supported in # nvvideoconvert,", "45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK = 42", "not implemented in this example\") elif metric.name == \"Node Control/Rebirth\"", "Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False)", "get informed of the meta data generated, we add probe", "userdata, flags, rc): if rc == 0: print(\"Connected with result", "myPassword = \"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS =", "done by pyds.NvDsFrameMeta.cast() # The casting also keeps ownership of", "need a full application reset via a soft reboot. #", "AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload,", "#publishBirth() elif metric.name == \"output/Device Metric4\" or metric.alias == AliasMap.Device_Metric4:", "framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size',", "= sparkplug.getNodeBirthPayload() # Set up the Node Controls addMetric(payload, \"Node", "is an NCMD used to tell a device/client application to", "Object7 = 0 Object8 = 0 Object9 = 0 Object10", "import * import pyds # Application Variables serverUrl = \"localhost\"", "0 counter2 = 0 Object1 = 0 Object2 = 0", "= 5000 myUsername = \"admin\" myPassword = \"<PASSWORD>\" client =", "Int16 because of how we declated it in the DBIRTH", "def publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### # Publish the NBIRTH", "#global newValue4 #publishBirth() elif metric.name == \"output/Device Metric4\" or metric.alias", "l_frame=l_frame.next except StopIteration: break return Gst.PadProbeReturn.OK ###################################################################### def main(args): #", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String,", "Font , font-color and font-size py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size =", "set(red, green, blue, alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0,", "confirm this) # videoconvert to make sure a superset of", "# Sit and wait for inbound or outbound events for", "the node death payload deathPayload = sparkplug.getNodeDeathPayload() # Start of", "the MQTT client connection client.on_connect = on_connect client.on_message = on_message", "DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF", "sys.stderr.write(\" Unable to get sink pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER,", "vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc: sys.stderr.write(\" Unable to", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2)", "pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie) pgie.link(nvvidconv) nvvidconv.link(nvosd) if is_aarch64():", "streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\" Unable", "# its original NBIRTH and DBIRTH messages. publishBirth() elif metric.name", "is used for clients that have a pool of MQTT", "\"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball", "PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG", "to connect with result code \"+str(rc)) sys.exit() global myGroupId global", "to get the sink pad of streammux \\n\") srcpad =", "- New Value: {}\".format(newValue4)) # Create the DDATA payload -", "StopIteration: break obj_counter[obj_meta.class_id] += 1 try: l_obj=l_obj.next except StopIteration: break", "this software and associated documentation files (the \"Software\"), # to", "message for output/Device Metric3 - New Value: %r\" % newValue)", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish a", "== AliasMap.Device_Input3: # This is a metric we declared in", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) #", "list of available servers. This is used for clients that", "C address of gst_buffer as input, which is obtained with", "py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset = 12 # Font , font-color", "Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0)", "Unable to create nvosd \\n\") # Finally render the osd", "Device_Input5 = 16 Device_Input6 = 17 Device_Input7 = 18 Device_Input8", "green, blue, alpha); set to White py_nvosd_text_params.font_params.font_color.set(1.0, 1.0, 1.0, 1.0)", "= 0 newValue4 = 0 newValue5 = 0 newValue6 =", "New Value: {}\".format(newValue5)) # Create the DDATA payload - Use", "message Input 6 #publishBirth() elif metric.name == \"output/Device Input6\" or", "Unable to get the sink pad of streammux \\n\") srcpad", "elif metric.name == \"Node Control/Reboot\" or metric.alias == AliasMap.Reboot: #", "Server' is an NCMD used to tell the device/client application", "for output/Device Metric3 - New Value: %r\" % newValue) #", "import bus_call from sparkplug_b import * import pyds # Application", "= 32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE =", "= 10 py_nvosd_text_params.y_offset = 12 # Font , font-color and", "addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6,", "\"Node Control/Reboot\" or metric.alias == AliasMap.Reboot: # 'Node Control/Reboot' is", "\"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16,", "Using pyds.get_string() to get display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta,", "'Node Control/Rebirth' is an NCMD used to tell the device/client", "output/Device Input6 - New Value: {}\".format(newValue6)) # Create the DDATA", "it when this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1", "MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload,", "###################################################################### ###################################################################### # The callback for when a PUBLISH message", "PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD", "41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET = 38", "34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD = 31", "This is a metric we declared in our DBIRTH message", "\\n\") # Use convertor to convert from NV12 to RGBA", "This is used for clients that have a pool of", "== AliasMap.Reboot: # 'Node Control/Reboot' is an NCMD used to", "publish a DDATA with the new output # value. If", "23 Device_Output3 = 24 Device_Output4 = 25 Device_Output5 = 26", "newValue6 = 0 newValue7 = 0 newValue8 = 0 newValue9", "= Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc: sys.stderr.write(\" Unable to create", "PUBLISH message is received from the server. ###################################################################### def on_message(client,", "an Boolean because of how we declated it in the", "in the DBIRTH newValue2 = metric.int_value print (\"CMD message for", "source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000)", "73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER = 70", "Mem (NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc:", "PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE=", "12 Device_Input2 = 13 Device_Input3 = 14 Device_Input4 = 15", "config file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie: sys.stderr.write(\"", "0, False) # Publish a message Input 4 #publishBirth() elif", "\"DCMD\") and tokens[3] == myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for", "newValue) # Create the DDATA payload - use the alias", "0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\",", "output/Device Input5 - New Value: {}\".format(newValue5)) # Create the DDATA", "ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN", "Input6\" or metric.alias == AliasMap.Device_Input6: # This is a metric", "to the output we must publish a DDATA with the", "data to the inputs addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16,", "\"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16,", "0, False) else: print (\"Unknown command: \" + metric.name) else:", "Say YUYV is unsupported - which is the common #", "68 PGIE_CLASS_ID_CELL_PHONE = 67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE = 65", "= 0 newValue9 = 0 newValue10 = 0 class AliasMap:", "(\"CMD message for output/Device Input9 - New Value: {}\".format(newValue9)) #", "IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #", "\"Hot dog\",\"Carrot\", \"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\",", "in the DBIRTH newValue = metric.int_value print (\"CMD message for", "get the sink pad of streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\")", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7)", "PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN", "= 71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE =", "################################################################################ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.", "import time import time, threading import random import string import", "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish", "{}\".format(newValue1)) # Create the DDATA payload - Use the alias", "# application if it receives an NDATA or DDATA with", "Object8 = 0 Object9 = 0 Object10 = 0 newValue1", "this case, we fake a full reboot with a republishing", "a soft reboot. # In this case, we fake a", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "GObject, Gst from common.is_aarch_64 import is_aarch64 from common.bus_call import bus_call", "= 11 Device_Input1 = 12 Device_Input2 = 13 Device_Input3 =", "substantial portions of the Software. # # THE SOFTWARE IS", "will claim it when this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels", "# videoconvert to make sure a superset of raw formats", "def publishNodeBirth(): print (\"Publishing Node Birth\") # Create the node", "get sink pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0) ######################################################################", "1883, 60) WAIT_SECONDS = 1 frame_numberx = 0 num_rectsx =", "merge, publish, distribute, sublicense, # and/or sell copies of the", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,", "message Input 3 #publishBirth() elif metric.name == \"output/Device Input3\" or", "is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) # create an event loop", "Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8)", "7 #publishBirth() elif metric.name == \"output/Device Input7\" or metric.alias ==", "AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "data payload = sparkplug.getDdataPayload() # Add some random data to", "when a PUBLISH message is received from the server. ######################################################################", "declared in our DBIRTH message and we're emulating an output.", "dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\",", "the DBIRTH newValue4 = metric.int_value print (\"CMD message for output/Device", "PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE", "PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP = 41 PGIE_CLASS_ID_WINE_GLASS = 40 PGIE_CLASS_ID_BOTTLE", "client receives a CONNACK response from the server. ###################################################################### def", "in on_connect() means that if we lose the connection and", "the output and then read it back # before publishing", "SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,", "Value: {}\".format(newValue7)) # Create the DDATA payload - Use the", "Devices\" myNodeName = \"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod = 5000", "background color py_nvosd_text_params.set_bg_clr = 1 # set(red, green, blue, alpha);", "Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv)", "== AliasMap.Device_Metric4: # This is a metric we declared in", "still access it. Otherwise # the garbage collector will claim", "0 class AliasMap: Next_Server = 0 Rebirth = 1 Reboot", "Object4 = 0 Object5 = 0 Object6 = 0 Object7", "Input 8 #publishBirth() elif metric.name == \"output/Device Input8\" or metric.alias", "of how we declated it in the DBIRTH newValue =", "as input, which is obtained with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer))", "DBIRTH # messages. publishBirth() elif metric.name == \"output/Device Metric2\" or", "because of how we declated it in the DBIRTH newValue1", "metric.int_value print (\"CMD message for output/Device Input10 - New Value:", "permit persons to whom the # Software is furnished to", "get GstBuffer \") return # Retrieve batch metadata from the", "a full reboot with a republishing of the NBIRTH and", "\"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\", \"Umbrella\", \"Backpack\",\"Giraffe\",", "addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4,", "Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0)", "copyright notice and this permission notice shall be included in", "= 57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT =", "main(args): # Check input arguments if len(args) != 2: sys.stderr.write(\"usage:", "AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload,", "how we declated it in the DBIRTH newValue = metric.string_value", "then subscriptions will be renewed. client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\"", "DDATA payload - Use the alias because this isn't the", "NvStreamMux \\n\") # Use nvinfer to run inferencing on camera's", "addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish a message data", "not None: try: # Note that l_frame.data needs a cast", "= 0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\",", "# Adding videoconvert -> nvvideoconvert as not all # raw", "byteArray, 0, False) # Publish a message Input 9 #publishBirth()", "# Say YUYV is unsupported - which is the common", "\"Person\"] ###################################################################### # The callback for when the client receives", "###################################################################### def on_connect(client, userdata, flags, rc): if rc == 0:", "superset of raw formats are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\")", "because of how we declated it in the DBIRTH newValue10", "# Publish the node birth certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\"", "DDATA with the new output # value. If this were", "<v4l2-device-path>\\n\" % args[0]) sys.exit(1) # Standard GStreamer initialization GObject.threads_init() Gst.init(None)", "will form a connection of other elements print(\"Creating Pipeline \\n", "are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc: sys.stderr.write(\"", "tokens[1] == myGroupId and (tokens[2] == \"NCMD\" or tokens[2] ==", "\"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame Number\",", "False) # Publish a message Input 1 #publishBirth() elif metric.name", "- New Value: {}\".format(newValue5)) # Create the DDATA payload -", "command...\") print (\"Done publishing\") ##################################################################### ###################################################################### ###################################################################### # Publish the", "for output/Device Input1 - New Value: {}\".format(newValue1)) # Create the", "declated it in the DBIRTH newValue8 = metric.int_value print (\"CMD", "nvvideoconvert to convert incoming raw buffers to NVMM Mem (NvBufSurface", "the alias because this isn't the DBIRTH payload = sparkplug.getDdataPayload()", "So, on incoming 'writes' to the output we must publish", "StopIteration: break return Gst.PadProbeReturn.OK ###################################################################### def main(args): # Check input", "to create Pipeline \\n\") # Source element for reading from", "an event loop and feed gstreamer bus mesages to it", "loop = GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call,", "metric.name == \"output/Device Input7\" or metric.alias == AliasMap.Device_Input7: # This", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "= 15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER =", "by nvvideoconvert; # Say YUYV is unsupported - which is", "13 Device_Input3 = 14 Device_Input4 = 15 Device_Input5 = 16", "metric.name == \"output/Device Input2\" or metric.alias == AliasMap.Device_Input2: # This", "# C address of gst_buffer as input, which is obtained", "Device BIRTH certificate totalByteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId +", "= 20 Device_Input10 = 21 Device_Output1 = 22 Device_Output2 =", "OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE.", "MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9) addMetric(payload, \"input/Device", "70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE = 67", "pyds module allocates a buffer for the string, and the", "print(\"Failed to connect with result code \"+str(rc)) sys.exit() global myGroupId", "caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\" Unable to get source pad", "display_meta.num_labels = 1 py_nvosd_text_params = display_meta.text_params[0] # Setting display text", "limitation # the rights to use, copy, modify, merge, publish,", "Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\" Unable to create Nvvideoconvert", "class AliasMap: Next_Server = 0 Rebirth = 1 Reboot =", "- New Value: {}\".format(newValue9)) # Create the DDATA payload -", "myDeviceName, byteArray, 0, False) # Publish a message Input 9", "= 25 Device_Output5 = 26 Device_Output6 = 27 Device_Output7 =", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "newValue8 global newValue9 global newValue10 if tokens[0] == \"spBv1.0\" and", "\"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16,", "StopIteration: break # Acquiring a display meta object. The memory", "for output/Device Input8 - New Value: {}\".format(newValue8)) # Create the", "a message Input 4 #publishBirth() elif metric.name == \"output/Device Input4\"", "bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\" + myNodeName + \"/\"", "+ myGroupId + \"/DCMD/\" + myNodeName + \"/#\") ###################################################################### ######################################################################", "blue, alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) #", "GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call, loop) #", "nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv: sys.stderr.write(\" Unable", "initial data with the Device BIRTH certificate totalByteArray = bytearray(payload.SerializeToString())", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish a message", "\"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device Metric2\",", "newValue10 if tokens[0] == \"spBv1.0\" and tokens[1] == myGroupId and", "EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish a", "while l_obj is not None: try: # Casting l_obj.data to", "DBIRTH newValue6 = metric.int_value print (\"CMD message for output/Device Input6", "messages. publishBirth() elif metric.name == \"output/Device Metric2\" or metric.alias ==", "Publish a message Input 6 #publishBirth() elif metric.name == \"output/Device", "== \"output/Device Input5\" or metric.alias == AliasMap.Device_Input5: # This is", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "tokens[2] == \"DCMD\") and tokens[3] == myNodeName: inboundPayload = sparkplug_b_pb2.Payload()", "payload - Use the alias because this isn't the DBIRTH", "0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\",", "message for output/Device Input8 - New Value: {}\".format(newValue8)) # Create", "send all known metrics in # its original NBIRTH and", "informed of the meta data generated, we add probe to", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) #", "myNodeName + \"/\" + myDeviceName, byteArray, 0, False) else: print", "AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device", "metric.name == \"Node Control/Next Server\" or metric.alias == AliasMap.Next_Server: #", "0, False) client.connect(serverUrl, 1883, 60) # Publish the birth certificates", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish a", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean,", "metric.int_value print (\"CMD message for output/Device Input6 - New Value:", "Publish the BIRTH certificates ###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth() ######################################################################", "it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num", "15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH = 13 PGIE_CLASS_ID_PARKING_METER = 12", "None: try: # Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration:", "sys.stderr.write(\" Unable to get source pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad)", "birth payload payload = sparkplug.getNodeBirthPayload() # Set up the Node", "on screen # Note that the pyds module allocates a", "AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish a message data byteArray =", "== \"output/Device Input3\" or metric.alias == AliasMap.Device_Input3: # This is", "message for output/Device Input9 - New Value: {}\".format(newValue9)) # Create", "PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0, PGIE_CLASS_ID_SKATEBOARD:0, PGIE_CLASS_ID_BASEBALL_GLOVE:0, PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0,", "a DDATA with the new output # value. If this", "the initial data with the Device BIRTH certificate totalByteArray =", "OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION", "pyds.NvDsFrameMeta.cast() # The casting also keeps ownership of the underlying", "metric.name == \"Node Control/Reboot\" or metric.alias == AliasMap.Reboot: # 'Node", "PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0,", "with a metric that was not published in the #", "Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not pgie: sys.stderr.write(\" Unable to create pgie", "640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") #", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue)", "PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0,", "camera's output, # behaviour of inferencing is set through config", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2,", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish", "MetricDataType.String, newValue) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "metric.name == \"output/Device Metric3\" or metric.alias == AliasMap.Device_Metric3: # This", "enough to reduce compute by # videoconvert doing passthrough (TODO", "up the MQTT client connection client.on_connect = on_connect client.on_message =", "pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink)", "= 40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD =", "\"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16,", "return # Retrieve batch metadata from the gst_buffer # Note", "bus mesages to it loop = GObject.MainLoop() bus = pipeline.get_bus()", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) #", "+ myDeviceName, byteArray, 0, False) # Sit and wait for", "# reconnect then subscriptions will be renewed. client.subscribe(\"spBv1.0/\" + myGroupId", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16,", "0 Object2 = 0 Object3 = 0 Object4 = 0", "tell a device/client application to reboot # This can be", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0)", "this) # videoconvert to make sure a superset of raw", "= 77 PGIE_CLASS_ID_SCISSORS = 76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK =", "{}\".format(newValue7)) # Create the DDATA payload - Use the alias", "# In this case, we fake a full reboot with", "6 Device_Metric2 = 7 Device_Metric3 = 8 Device_Metric4 = 9", "\"spBv1.0\" and tokens[1] == myGroupId and (tokens[2] == \"NCMD\" or", "or metric.alias == AliasMap.Device_Input10: # This is a metric we", "0) addMetric(payload, \"output/Device Input5\", AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\",", "\"NCMD\" or tokens[2] == \"DCMD\") and tokens[3] == myNodeName: inboundPayload", "\"Broccli\", \"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\",", "usb cams # In case we have a camera with", "PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT", "# 'Node Control/Reboot' is an NCMD used to tell a", "0 newValue10 = 0 class AliasMap: Next_Server = 0 Rebirth", "Node Controls addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload,", "\"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16,", "raw format supported in # nvvideoconvert, GStreamer plugins' capability negotiation", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5, MetricDataType.Int16, newValue5) # Publish a", "\"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16,", "= \"Serif\" py_nvosd_text_params.font_params.font_size = 10 # set(red, green, blue, alpha);", "display_text field here will return the C address of the", "PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4,", "break return Gst.PadProbeReturn.OK ###################################################################### def main(args): # Check input arguments", "full reboot with a republishing of the NBIRTH and DBIRTH", "the sink pad of the osd element, since by that", "= 0 Object2 = 0 Object3 = 0 Object4 =", "serverUrl = \"localhost\" myGroupId = \"Sparkplug B Devices\" myNodeName =", "byteArray, 0, False) # Publish a message Input 6 #publishBirth()", "meta data generated, we add probe to # the sink", "used for clients that have a pool of MQTT servers", "NBIRTH and DBIRTH again. MQTT Engine will send this NCMD", "= 26 PGIE_CLASS_ID_UMBRELLA = 25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE =", "we declated it in the DBIRTH newValue3 = metric.int_value print", "time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING)", "global myGroupId global myNodeName # Subscribing in on_connect() means that", "sys.exit(1) # Standard GStreamer initialization GObject.threads_init() Gst.init(None) # Create gstreamer", "the DBIRTH newValue10 = metric.int_value print (\"CMD message for output/Device", "PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE", "PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0, PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0,", "= metric.int_value print (\"CMD message for output/Device Input2 - New", "# create an event loop and feed gstreamer bus mesages", "72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN = 69", "\"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16,", "of how we declated it in the DBIRTH newValue5 =", "global Object3 global Object4 global Object5 global Object6 global Object7", "1.0) # Text background color py_nvosd_text_params.set_bg_clr = 1 # set(red,", "print (\"CMD message for output/Device Metric4 - New Value: {}\".format(newValue))", "DDATA message. # We know this is an Boolean because", "\"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16,", "addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish a message data", "AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload,", "Device_Input7 = 18 Device_Input8 = 19 Device_Input9 = 20 Device_Input10", "to get display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try:", "== \"output/Device Metric3\" or metric.alias == AliasMap.Device_Metric3: # This is", "by the garbage collector. # Reading the display_text field here", "OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT", "streammux.set_property('height', 480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set", "a message Input 2 #publishBirth() elif metric.name == \"output/Device Input2\"", "elements print(\"Creating Pipeline \\n \") pipeline = Gst.Pipeline() if not", "Set up the Node Controls addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server,", "Publish a message Input 10 #publishBirth() elif metric.name == \"output/Device", "PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT", "OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF", "declated it in the DBIRTH newValue9 = metric.int_value print (\"CMD", "\"input/Device Metric0\", AliasMap.Device_Metric0, MetricDataType.String, \"hello device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1,", "MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device", "False) #global newValue4 #publishBirth() elif metric.name == \"output/Device Metric4\" or", "Input 2 #publishBirth() elif metric.name == \"output/Device Input2\" or metric.alias", "30 Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER =", "= 62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59", "AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16, 0) addMetric(payload,", "= 0 Object10 = 0 newValue1 = 0 newValue2 =", "0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\",", "nvvideoconvert, GStreamer plugins' capability negotiation # shall be intelligent enough", "AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish a message data byteArray =", "# set(red, green, blue, alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0,", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16,", "# We know this is an Int16 because of how", "38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35", "56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA = 53", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish a message", "node birth payload payload = sparkplug.getNodeBirthPayload() # Set up the", "\"Stream-muxer\") if not streammux: sys.stderr.write(\" Unable to create NvStreamMux \\n\")", "= 0 Rebirth = 1 Reboot = 2 Device_frame_numberx =", "Object9 global Object10 #Intiallizing object counter with 0. obj_counter =", "52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE = 49", "tell the device/client application to resend # its full NBIRTH", "not sinkpad: sys.stderr.write(\" Unable to get the sink pad of", "# The casting is done by pyds.NvDsFrameMeta.cast() # The casting", "if is_aarch64(): pipeline.add(transform) # we link the elements together #", "server and connect to the next MQTT server in the", "videoconvert -> nvvideoconvert as not all # raw formats are", "metric.name == \"output/Device Input8\" or metric.alias == AliasMap.Device_Input8: # This", "the # list of available servers. This is used for", "the DDATA payload - use the alias because this isn't", "output if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\")", "nvvideoconvert -> nvosd -> video-renderer print(\"Linking elements in the Pipeline", "loop) # Lets add probe to get informed of the", "True) addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload,", "False) # Publish a message Input 7 #publishBirth() elif metric.name", "how we declated it in the DBIRTH newValue1 = metric.int_value", "AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") #", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) # Publish a", "74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK = 71", "casting is done by pyds.NvDsFrameMeta.cast() # The casting also keeps", "addMetric(payload, \"input/Device Output6\", AliasMap.Device_Output6, MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7,", "0 Object1 = 0 Object2 = 0 Object3 = 0", "MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device", "if metric.name == \"Node Control/Next Server\" or metric.alias == AliasMap.Next_Server:", "casting also keeps ownership of the underlying memory # in", "input, which is obtained with hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame", "emulating an output. # So, on incoming 'writes' to the", "-> nvvideoconvert as not all # raw formats are supported", "Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux: sys.stderr.write(\" Unable to create NvStreamMux", "elements to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux)", "MQTT servers # to connect to. print (\"'Node Control/Next Server'", "client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\" + myNodeName, deathByteArray, 0, False)", "Device_Output5 = 26 Device_Output6 = 27 Device_Output7 = 28 Device_Output8", "Permission is hereby granted, free of charge, to any person", "60) # Publish the birth certificates publishBirth() def foo(): #", "Object2) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\",", "addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot, MetricDataType.Boolean, False) # Publish the node", "PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE", "create Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc:", "if we lose the connection and # reconnect then subscriptions", "it in the DBIRTH newValue5 = metric.int_value print (\"CMD message", "set through config file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if not", "\"output/Device Input8\" or metric.alias == AliasMap.Device_Input8: # This is a", "global newValue6 global newValue7 global newValue8 global newValue9 global newValue10", "elif metric.name == \"output/Device Metric4\" or metric.alias == AliasMap.Device_Metric4: #", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3,", "buffer for the string, and the # memory will not", "connection of other elements print(\"Creating Pipeline \\n \") pipeline =", "+ \"/DBIRTH/\" + myNodeName + \"/\" + myDeviceName, totalByteArray, 0,", "= 10 # set(red, green, blue, alpha); set to White", "PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR", "def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx global Object1 global Object2", "PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR", "= 31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE =", "1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\",", "garbage collector will leave # it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish a", "on camera's output, # behaviour of inferencing is set through", "Set up the MQTT client connection client.on_connect = on_connect client.on_message", "output we must publish a DDATA with the new output", "sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink: sys.stderr.write(\" Unable to", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4)", "\"start\") # Publish the initial data with the Device BIRTH", "Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1)", "#publishBirth() elif metric.name == \"output/Device Input10\" or metric.alias == AliasMap.Device_Input10:", "+ \"/\" + myDeviceName, byteArray, 0, False) else: print (\"Unknown", "USE OR OTHER # DEALINGS IN THE SOFTWARE. ################################################################################ import", "how we declated it in the DBIRTH newValue9 = metric.int_value", "0) addMetric(payload, \"output/Device Input4\", AliasMap.Device_Input4, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input5\",", "sublicense, # and/or sell copies of the Software, and to", "WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT", "PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0, PGIE_CLASS_ID_TENNIS_RACKET:0, PGIE_CLASS_ID_SURFBOARD:0,", "claim it when this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels =", "pad of the osd element, since by that time, the", "generated, we add probe to # the sink pad of", "mesages to it loop = GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch()", "= 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE =", "25 PGIE_CLASS_ID_BACKPACK = 24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA = 22", "pyds # Application Variables serverUrl = \"localhost\" myGroupId = \"Sparkplug", "= 1 Reboot = 2 Device_frame_numberx = 3 Device_num_rectsx =", "the DBIRTH newValue9 = metric.int_value print (\"CMD message for output/Device", "server. ###################################################################### def on_connect(client, userdata, flags, rc): if rc ==", "= metric.int_value print (\"CMD message for output/Device Input10 - New", "WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING", "callback for when a PUBLISH message is received from the", "by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if not nvvidconv: sys.stderr.write(\"", "addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Reboot\", AliasMap.Reboot,", "nvvideoconvert; # Say YUYV is unsupported - which is the", "address of the # allocated string. Use pyds.get_string() to get", "###################################################################### # The callback for when the client receives a", "Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False)", "not nvvidconv: sys.stderr.write(\" Unable to create nvvidconv \\n\") # Create", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish a message", "AliasMap.Device_Input5, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input6\", AliasMap.Device_Input6, MetricDataType.Int16, 0) addMetric(payload,", "+ myNodeName + \"/\" + myDeviceName, byteArray, 0, False) #global", "print(\"Connected with result code \"+str(rc)) else: print(\"Failed to connect with", "this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta) display_meta.num_labels = 1 py_nvosd_text_params =", "py_nvosd_text_params.font_params.font_size = 10 # set(red, green, blue, alpha); set to", "PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN", "\"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16,", "metric.name == \"output/Device Input4\" or metric.alias == AliasMap.Device_Input4: # This", "used to tell a device/client application to reboot # This", "NVIDIA CORPORATION. All rights reserved. # # Permission is hereby", "= \"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883, 60) WAIT_SECONDS = 1", "it back # before publishing a DDATA message. # We", "Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0)", "display_meta) try: l_frame=l_frame.next except StopIteration: break return Gst.PadProbeReturn.OK ###################################################################### def", "Input7\" or metric.alias == AliasMap.Device_Input7: # This is a metric", "downstream plugins can still access it. Otherwise # the garbage", "Lets add probe to get informed of the meta data", "a message Input 7 #publishBirth() elif metric.name == \"output/Device Input7\"", "OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH", "global Object8 global Object9 global Object10 #Intiallizing object counter with", "\"output/Device Input5\" or metric.alias == AliasMap.Device_Input5: # This is a", "44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP = 41", "Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not vidconvsrc: sys.stderr.write(\" Unable to create videoconvert", "False) # Publish a message Input 4 #publishBirth() elif metric.name", "# Get the payload payload = sparkplug.getDeviceBirthPayload() # Add some", "Object9 = obj_counter[newValue9] Object10 = obj_counter[newValue10] # Now set the", "MetricDataType.Int16, newValue7) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "publishNodeBirth(): print (\"Publishing Node Birth\") # Create the node birth", "Device_counter1 = 10 Device_counter2 = 11 Device_Input1 = 12 Device_Input2", "== \"output/Device Metric4\" or metric.alias == AliasMap.Device_Metric4: # This is", "py_nvosd_text_params.font_params.font_name = \"Serif\" py_nvosd_text_params.font_params.font_size = 10 # set(red, green, blue,", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) #", "if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\") sink", "publishing\") ##################################################################### ###################################################################### ###################################################################### # Publish the BIRTH certificates ######################################################################", "sys.stderr.write(\" Unable to create Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\")", "for inbound or outbound events for _ in range(1): time.sleep(1)", "will not be claimed by the garbage collector. # Reading", "sys.stderr.write(\" Unable to create capsfilter \\n\") # Create nvstreammux instance", "PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0,", "MQTT Engine will send this NCMD to a device/client #", "AliasMap.Next_Server: # 'Node Control/Next Server' is an NCMD used to", "10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK = 7", "= 5 PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE =", "Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0)", "addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1,", "byteArray, 0, False) else: print (\"Unknown command: \" + metric.name)", "PGIE_CLASS_ID_BOAT = 8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS", "AliasMap: Next_Server = 0 Rebirth = 1 Reboot = 2", "create videoconvert \\n\") # nvvideoconvert to convert incoming raw buffers", "publish some new data payload = sparkplug.getDdataPayload() # Add some", "newValue1 global newValue2 global newValue3 global newValue4 global newValue5 global", "PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA", "+ \"/\" + myDeviceName, byteArray, 0, False) # Sit and", "metric.name == \"Node Control/Rebirth\" or metric.alias == AliasMap.Rebirth: # 'Node", "videoconvert doing passthrough (TODO we need to confirm this) #", "###################################################################### def main(args): # Check input arguments if len(args) !=", "some new data payload = sparkplug.getDdataPayload() # Add some random", "metric.alias == AliasMap.Device_Input3: # This is a metric we declared", "for output/Device Input3 - New Value: {}\".format(newValue3)) # Create the", "Object9 = 0 Object10 = 0 newValue1 = 0 newValue2", "incoming 'writes' to the output we must publish a DDATA", "Device_Output8 = 29 Device_Output9 = 30 Device_Output10 = 31 MAX_DISPLAY_LEN=64", "EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE", "common.is_aarch_64 import is_aarch64 from common.bus_call import bus_call from sparkplug_b import", "addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish a message data", "18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG = 16 PGIE_CLASS_ID_CAT = 15", "shown on screen # Note that the pyds module allocates", "we have a camera with raw format supported in #", "= 28 Device_Output8 = 29 Device_Output9 = 30 Device_Output10 =", "client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\" + myNodeName + \"/#\") ######################################################################", "hereby granted, free of charge, to any person obtaining a", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16,", "###################################################################### def publishDeviceBirth(): print (\"Publishing Device Birth\") # Get the", "or DDATA with a metric that was not published in", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE", "== AliasMap.Device_Input5: # This is a metric we declared in", "srcpad: sys.stderr.write(\" Unable to get source pad of caps_vidconvsrc \\n\")", "DBIRTH newValue9 = metric.int_value print (\"CMD message for output/Device Input9", "58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE = 55", "# all copies or substantial portions of the Software. #", "myDeviceName, byteArray, 0, False) # Publish a message Input 4", "== \"output/Device Input9\" or metric.alias == AliasMap.Device_Input9: # This is", "myDeviceName, byteArray, 0, False) # Sit and wait for inbound", "% args[0]) sys.exit(1) # Standard GStreamer initialization GObject.threads_init() Gst.init(None) #", "read it back # before publishing a DDATA message. #", "batch_meta.frame_meta_list while l_frame is not None: try: # Note that", "MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device Metric2\", AliasMap.Device_Metric2, MetricDataType.Int16, 0) addMetric(payload,", "AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean, False) addMetric(payload,", "of streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not srcpad: sys.stderr.write(\"", "leave # it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break", "a message Input 5 #publishBirth() elif metric.name == \"output/Device Input5\"", "50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH = 48 PGIE_CLASS_ID_APPLE = 47", "program - Set up the MQTT client connection client.on_connect =", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish a message", "+ \"/\" + myDeviceName, byteArray, 0, False) #publishBirth() elif metric.name", "PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0,", "AliasMap.Device_Input1: # This is a metric we declared in our", "FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR", "Number of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 =", "63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED", "pgie \\n\") # Use convertor to convert from NV12 to", "message Input 8 #publishBirth() elif metric.name == \"output/Device Input8\" or", "metric.alias == AliasMap.Device_Input4: # This is a metric we declared", "== AliasMap.Device_Metric3: # This is a metric we declared in", "\"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\" Unable to create capsfilter \\n\")", "Value: {}\".format(newValue3)) # Create the DDATA payload - Use the", "PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON", "Object10 = 0 newValue1 = 0 newValue2 = 0 newValue3", "33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS = 30", "Value: {}\".format(newValue5)) # Create the DDATA payload - Use the", "try: # Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break", "0, False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx", "= on_message client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId", "the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",", "byteArray, 0, False) # Sit and wait for inbound or", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish a message", "Input8\" or metric.alias == AliasMap.Device_Input8: # This is a metric", "# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR", "#publishBirth() elif metric.name == \"output/Device Input9\" or metric.alias == AliasMap.Device_Input9:", "DDATA payload - use the alias because this isn't the", "# Publish a message Input 5 #publishBirth() elif metric.name ==", "if not vidconvsrc: sys.stderr.write(\" Unable to create videoconvert \\n\") #", "= 55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG =", "\"Backpack\",\"Giraffe\", \"Zebra\", \"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\",", "how we declated it in the DBIRTH newValue = metric.int_value", "all copies or substantial portions of the Software. # #", "In this case, we fake a full reboot with a", "- New Value: {}\".format(newValue7)) # Create the DDATA payload -", "metric.int_value print (\"CMD message for output/Device Input7 - New Value:", "application must send all known metrics in # its original", "in the DBIRTH newValue7 = metric.int_value print (\"CMD message for", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7, MetricDataType.Int16, newValue7) # Publish", "print(\"Creating Source \\n \") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2, MetricDataType.Int16, newValue) # Publish", "many logi usb cams # In case we have a", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric2,", "Software is furnished to do so, subject to the following", "num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3", "Publish a message Input 7 #publishBirth() elif metric.name == \"output/Device", "l_obj=l_obj.next except StopIteration: break # Acquiring a display meta object.", "PGIE_CLASS_ID_AEROPLANE = 4 PGIE_CLASS_ID_MOTORBIKE = 3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE", "application to # disconnect from the current MQTT server and", "print (\"CMD message for output/Device Input1 - New Value: {}\".format(newValue1))", "input arguments if len(args) != 2: sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" %", "1 #publishBirth() elif metric.name == \"output/Device Input1\" or metric.alias ==", "allocated string. Use pyds.get_string() to get the string content. py_nvosd_text_params.display_text", "= \"localhost\" myGroupId = \"Sparkplug B Devices\" myNodeName = \"NVIDIA\"", "# print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except StopIteration: break return", "bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\" + myNodeName, deathByteArray, 0,", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload, \"output/Device", "= 0 newValue10 = 0 class AliasMap: Next_Server = 0", "not source: sys.stderr.write(\" Unable to create Source \\n\") caps_v4l2src =", "0 Object3 = 0 Object4 = 0 Object5 = 0", "# The callback for when the client receives a CONNACK", "(\"CMD message for output/Device Input10 - New Value: {}\".format(newValue10)) #", "access it. Otherwise # the garbage collector will claim it", "(\"Unknown command: \" + metric.name) else: print (\"Unknown command...\") print", "71 PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE = 68", "Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish a message data byteArray", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish a", "buffers to NVMM Mem (NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\")", "Input4 - New Value: {}\".format(newValue4)) # Create the DDATA payload", "to do so, subject to the following conditions: # #", "AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True) addMetric(payload,", "inferencing is set through config file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\")", "userdata, msg): print(\"Message arrived: \" + msg.topic) tokens = msg.topic.split(\"/\")", "New Value: {}\".format(newValue7)) # Create the DDATA payload - Use", "\"Bicycle\", \"Person\"] ###################################################################### # The callback for when the client", "in the DBIRTH newValue8 = metric.int_value print (\"CMD message for", "will return the C address of the # allocated string.", "make sure a superset of raw formats are supported vidconvsrc", "# messages. publishBirth() elif metric.name == \"output/Device Metric2\" or metric.alias", "= Gst.Pipeline() if not pipeline: sys.stderr.write(\" Unable to create Pipeline", "isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input2, MetricDataType.Int16,", "= obj_counter[newValue6] Object7 = obj_counter[newValue7] Object8 = obj_counter[newValue8] Object9 =", "to permit persons to whom the # Software is furnished", "Create the node birth payload payload = sparkplug.getNodeBirthPayload() # Set", "We know this is an Int16 because of how we", "pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform)", "MetricDataType.Int16, newValue4) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "print (\"CMD message for output/Device Input6 - New Value: {}\".format(newValue6))", "53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT = 51 PGIE_CLASS_ID_BROCCOLI = 50", "gi gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst from common.is_aarch_64", "# Add some random data to the inputs addMetric(payload, \"input/number", "newValue6 global newValue7 global newValue8 global newValue9 global newValue10 if", "receives a CONNACK response from the server. ###################################################################### def on_connect(client,", "\"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\",", "back # before publishing a DDATA message. # We know", "= sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input6, MetricDataType.Int16, newValue6) # Publish a", "and # reconnect then subscriptions will be renewed. client.subscribe(\"spBv1.0/\" +", "0, False) # Publish a message Input 2 #publishBirth() elif", "from common.bus_call import bus_call from sparkplug_b import * import pyds", "Metric2 - New Value: {}\".format(newValue)) # Create the DDATA payload", "PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0,", "where the string should appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset =", "Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Metric3\", AliasMap.Device_Metric3, MetricDataType.Boolean, True)", "AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish a message data byteArray =", "sys.stderr.write(\" Unable to create nvosd \\n\") # Finally render the", "metric.string_value print (\"CMD message for output/Device Metric4 - New Value:", "draw on the converted RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\")", "GStreamer initialization GObject.threads_init() Gst.init(None) # Create gstreamer elements # Create", "and feed gstreamer bus mesages to it loop = GObject.MainLoop()", "birth certificates publishBirth() def foo(): # Periodically publish some new", "{}\".format(newValue2)) # Create the DDATA payload - Use the alias", "metric.alias == AliasMap.Device_Metric4: # This is a metric we declared", "so the Python garbage collector will leave # it alone.", "The memory ownership remains in # the C code so", "myGroupId and (tokens[2] == \"NCMD\" or tokens[2] == \"DCMD\") and", "= 45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK =", "Value: {}\".format(newValue8)) # Create the DDATA payload - Use the", "PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0,", "(TODO we need to confirm this) # videoconvert to make", "nvosd -> video-renderer print(\"Linking elements in the Pipeline \\n\") source.link(caps_v4l2src)", "as mqtt import sparkplug_b as sparkplug import time import time,", "addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\", AliasMap.Device_Output8,", "output/Device Input8 - New Value: {}\".format(newValue8)) # Create the DDATA", "obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4 = obj_counter[newValue4]", "19 Device_Input9 = 20 Device_Input10 = 21 Device_Output1 = 22", "0 newValue4 = 0 newValue5 = 0 newValue6 = 0", "\"/DBIRTH/\" + myNodeName + \"/\" + myDeviceName, totalByteArray, 0, False)", "with the new output # value. If this were a", "output/Device Input1 - New Value: {}\".format(newValue1)) # Create the DDATA", "PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0, PGIE_CLASS_ID_BANANA:0, PGIE_CLASS_ID_BOWL:0, PGIE_CLASS_ID_SPOON:0, PGIE_CLASS_ID_KNIFE:0, PGIE_CLASS_ID_FORK:0, PGIE_CLASS_ID_CUP:0, PGIE_CLASS_ID_WINE_GLASS:0, PGIE_CLASS_ID_BOTTLE:0,", "C code so downstream plugins can still access it. Otherwise", "= 66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP =", "byteArray, 0, False) # Publish a message Input 4 #publishBirth()", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9)", "#Intiallizing object counter with 0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0,", "the string, and the # memory will not be claimed", "sink.set_property('sync', False) print(\"Adding elements to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc)", "-> mux -> # nvinfer -> nvvideoconvert -> nvosd ->", "for reading from the file print(\"Creating Source \\n \") source", "= Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\")", "Publish the birth certificates publishBirth() def foo(): # Periodically publish", "PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0,", "of the osd element, since by that time, the buffer", "the payload payload = sparkplug.getDeviceBirthPayload() # Add some device metrics", "PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0,", "480) streammux.set_property('batch-size', 1) streammux.set_property('batched-push-timeout', 4000000) pgie.set_property('config-file-path', \"config_infer_primary_yoloV3.txt\") # Set sync", "threading import random import string import gi gi.require_version('Gst', '1.0') from", "addMetric(payload, \"output/Device Input7\", AliasMap.Device_Input7, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input8\", AliasMap.Device_Input8,", "0 newValue5 = 0 newValue6 = 0 newValue7 = 0", "= 29 PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG =", "PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE", "None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) # Publish a message data byteArray", "0) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output8\",", "new output # value. If this were a real output", "False) print(\"Adding elements to Pipeline \\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc)", "certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\" +", "DBIRTH certificate ###################################################################### def publishDeviceBirth(): print (\"Publishing Device Birth\") #", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4,", "for _ in range(1): time.sleep(1) client.loop() threading.Timer(WAIT_SECONDS, foo).start() foo() ######################################################################", "# allocated string. Use pyds.get_string() to get the string content.", "False) # Publish a message Input 6 #publishBirth() elif metric.name", "0 Object6 = 0 Object7 = 0 Object8 = 0", "#publishBirth() elif metric.name == \"output/Device Input8\" or metric.alias == AliasMap.Device_Input8:", "pipeline.add(nvvidconv) pipeline.add(nvosd) pipeline.add(sink) if is_aarch64(): pipeline.add(transform) # we link the", "its full NBIRTH and DBIRTH again. MQTT Engine will send", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish a message", "WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS", "also keeps ownership of the underlying memory # in the", "'Node Control/Next Server' is an NCMD used to tell the", "hash(gst_buffer) batch_meta = pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while l_frame is", "= pyds.gst_buffer_get_nvds_batch_meta(hash(gst_buffer)) l_frame = batch_meta.frame_meta_list while l_frame is not None:", "Gst.init(None) # Create gstreamer elements # Create Pipeline element that", "60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA = 57", "- New Value: %r\" % newValue) # Create the DDATA", "the DBIRTH certificate ###################################################################### def publishDeviceBirth(): print (\"Publishing Device Birth\")", "\"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\",", "= Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd: sys.stderr.write(\" Unable to create", "= 24 Device_Output4 = 25 Device_Output5 = 26 Device_Output6 =", "metric.alias == AliasMap.Device_Input10: # This is a metric we declared", "0 newValue9 = 0 newValue10 = 0 class AliasMap: Next_Server", "= { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0, PGIE_CLASS_ID_SCISSORS:0, PGIE_CLASS_ID_VASE:0, PGIE_CLASS_ID_CLOCK:0, PGIE_CLASS_ID_BOOK:0, PGIE_CLASS_ID_REFRIGERATOR:0,", "23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT = 20", "how we declated it in the DBIRTH newValue = metric.boolean_value", "# Standard GStreamer initialization GObject.threads_init() Gst.init(None) # Create gstreamer elements", "+ myDeviceName, byteArray, 0, False) # Publish a message Input", "PGIE_CLASS_ID_POTTEDPLANT = 58 PGIE_CLASS_ID_SOFA = 57 PGIE_CLASS_ID_CHAIR = 56 PGIE_CLASS_ID_CAKE", "time, the buffer would have # had got all the", "and/or sell copies of the Software, and to permit persons", "source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source: sys.stderr.write(\" Unable to", "###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx global Object1", "# Publish a message Input 1 #publishBirth() elif metric.name ==", "import sparkplug_b as sparkplug import time import time, threading import", "PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR = 77 PGIE_CLASS_ID_SCISSORS", "a metric we declared in our DBIRTH message and we're", "buffer would have # had got all the metadata. osdsinkpad", "PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0,", "= frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while l_obj is not", "addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish a message data", "address of gst_buffer as input, which is obtained with hash(gst_buffer)", "\\n\") pipeline.add(source) pipeline.add(caps_v4l2src) pipeline.add(vidconvsrc) pipeline.add(nvvidconvsrc) pipeline.add(caps_vidconvsrc) pipeline.add(streammux) pipeline.add(pgie) pipeline.add(nvvidconv) pipeline.add(nvosd)", "8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS = 5", "a DDATA message. # We know this is an Boolean", "Input6 - New Value: {}\".format(newValue6)) # Create the DDATA payload", "metric.name == \"output/Device Input3\" or metric.alias == AliasMap.Device_Input3: # This", "None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish a message data byteArray", "how we declated it in the DBIRTH newValue4 = metric.int_value", "death payload deathPayload = sparkplug.getNodeDeathPayload() # Start of main program", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish", "a PUBLISH message is received from the server. ###################################################################### def", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10)", "################################################################################ import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import paho.mqtt.client as mqtt", "copy of this software and associated documentation files (the \"Software\"),", "BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS", "the DBIRTH newValue8 = metric.int_value print (\"CMD message for output/Device", "We know this is an Boolean because of how we", "metric we declared in our DBIRTH message and we're emulating", "pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL) if", "1 frame_numberx = 0 num_rectsx = 0 counter1 = 0", "pgie: sys.stderr.write(\" Unable to create pgie \\n\") # Use convertor", "Object4 global Object5 global Object6 global Object7 global Object8 global", "behaviour of inferencing is set through config file pgie =", "= 67 PGIE_CLASS_ID_KEYBOARD = 66 PGIE_CLASS_ID_REMOTE = 65 PGIE_CLASS_ID_MOUSE =", "(\"Publishing Device Birth\") # Get the payload payload = sparkplug.getDeviceBirthPayload()", "\"output/Device Input8\", AliasMap.Device_Input8, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input9\", AliasMap.Device_Input9, MetricDataType.Int16,", "Birth\") # Get the payload payload = sparkplug.getDeviceBirthPayload() # Add", "C code, so the Python garbage collector will leave #", "2 Device_frame_numberx = 3 Device_num_rectsx = 4 Device_Metric0 = 5", "= 56 PGIE_CLASS_ID_CAKE = 55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA =", "sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"]", "PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW", "from the server. ###################################################################### def on_connect(client, userdata, flags, rc): if", "payload = sparkplug.getDdataPayload() # Add some random data to the", "31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE = 29 PGIE_CLASS_ID_SUITCASE = 28", "of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx,", "+ \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\" + myNodeName +", "to tell the device/client application to # disconnect from the", "print (\"Publishing Node Birth\") # Create the node birth payload", "PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0, PGIE_CLASS_ID_BED:0, PGIE_CLASS_ID_POTTEDPLANT:0, PGIE_CLASS_ID_SOFA:0,", "reduce compute by # videoconvert doing passthrough (TODO we need", "AliasMap.Device_Metric2: # This is a metric we declared in our", "the DBIRTH newValue = metric.int_value print (\"CMD message for output/Device", "a full application reset via a soft reboot. # In", "totalByteArray, 0, False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global", "False) # Publish the node birth certificate byteArray = bytearray(payload.SerializeToString())", "mqtt import sparkplug_b as sparkplug import time import time, threading", "the buffer would have # had got all the metadata.", "servers. This is used for clients that have a pool", "py_nvosd_text_params = display_meta.text_params[0] # Setting display text to be shown", "publishing a DDATA message. # We know this is an", "Python garbage collector will leave # it alone. frame_meta =", "54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG = 52 PGIE_CLASS_ID_CARROT = 51", "or metric.alias == AliasMap.Device_Input1: # This is a metric we", "\\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink: sys.stderr.write(\" Unable", "the Node Controls addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False)", "will be renewed. client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\" + myNodeName", "how we declated it in the DBIRTH newValue3 = metric.int_value", "reset via a soft reboot. # In this case, we", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3)", "Start of main program - Set up the MQTT client", "software and associated documentation files (the \"Software\"), # to deal", "= 7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE =", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input5,", "obtaining a # copy of this software and associated documentation", "PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0", "streammux = Gst.ElementFactory.make(\"nvstreammux\", \"Stream-muxer\") if not streammux: sys.stderr.write(\" Unable to", "= sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics: if metric.name ==", "counter1 = 0 counter2 = 0 Object1 = 0 Object2", "# Publish the initial data with the Device BIRTH certificate", "elif metric.name == \"output/Device Input9\" or metric.alias == AliasMap.Device_Input9: #", "MetricDataType.Int16, newValue10) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "###################################################################### # Create the node death payload deathPayload = sparkplug.getNodeDeathPayload()", "the # original NBIRTH or DBIRTH. This is why the", "# it alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num", "Output9\", AliasMap.Device_Output9, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, 0)", "output. # So, on incoming 'writes' to the output we", "this isn't the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input7,", "MetricDataType.Boolean, newValue) # Publish a message data byteArray = bytearray(payload.SerializeToString())", "newValue8 = metric.int_value print (\"CMD message for output/Device Input8 -", "MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR = 77", "green, blue, alpha); set to Black py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0)", "= 0 counter2 = 0 Object1 = 0 Object2 =", "some device metrics addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx )", "= 8 PGIE_CLASS_ID_TRUCK = 7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS =", "\"output/Device Input4\" or metric.alias == AliasMap.Device_Input4: # This is a", "False) # Publish a message Input 3 #publishBirth() elif metric.name", "17 Device_Input7 = 18 Device_Input8 = 19 Device_Input9 = 20", "-> video-renderer print(\"Linking elements in the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc)", "original NBIRTH or DBIRTH. This is why the application must", "RGBA as required by nvosd nvvidconv = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor\") if", "payload payload = sparkplug.getDeviceBirthPayload() # Add some device metrics addMetric(payload,", "osd element, since by that time, the buffer would have", "MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device", "which is the common # raw format for many logi", "Unable to get sink pad of nvosd \\n\") osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe,", "PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 } num_rects=0 gst_buffer =", "not osdsinkpad: sys.stderr.write(\" Unable to get sink pad of nvosd", "\"Orange\",\"Sandwich\",\"Apple\", \"Banana\", \"Bowl\",\"Spoon\", \"Knife\", \"Fork\",\"Cup\",\"Wine Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\",", "Next_Server = 0 Rebirth = 1 Reboot = 2 Device_frame_numberx", "bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\" + myNodeName + \"/\"", "connection and # reconnect then subscriptions will be renewed. client.subscribe(\"spBv1.0/\"", "to reduce compute by # videoconvert doing passthrough (TODO we", "PGIE_CLASS_ID_REFRIGERATOR:0, PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0,", "display text to be shown on screen # Note that", "[\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell", "PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0,", "Device_Output2 = 23 Device_Output3 = 24 Device_Output4 = 25 Device_Output5", "to. print (\"'Node Control/Next Server' is not implemented in this", "message for output/Device Input3 - New Value: {}\".format(newValue3)) # Create", "have a pool of MQTT servers # to connect to.", "print (\"Unknown command: \" + metric.name) else: print (\"Unknown command...\")", "# Application Variables serverUrl = \"localhost\" myGroupId = \"Sparkplug B", "py_nvosd_text_params.text_bg_clr.set(0.0, 0.0, 0.0, 1.0) # Using pyds.get_string() to get display_text", "= 70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE =", "on incoming 'writes' to the output we must publish a", "inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics: if metric.name", "reboot. # In this case, we fake a full reboot", "declated it in the DBIRTH newValue1 = metric.int_value print (\"CMD", "= false to avoid late frame drops at the display-sink", "EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\", \"nvvideo-renderer\") if not sink: sys.stderr.write(\"", "message. # We know this is an Boolean because of", "with raw format supported in # nvvideoconvert, GStreamer plugins' capability", "def publishDeviceBirth(): print (\"Publishing Device Birth\") # Get the payload", "global Object1 global Object2 global Object3 global Object4 global Object5", "Unable to create Pipeline \\n\") # Source element for reading", "gstreamer elements # Create Pipeline element that will form a", "num_rectsx ) addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx ) addMetric(payload,\"input/Device", "or metric.alias == AliasMap.Device_Input7: # This is a metric we", "a device/client # application if it receives an NDATA or", "up the Node Controls addMetric(payload, \"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean,", "NVMM Mem (NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not", "PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0, PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0,", "racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\", \"Frisbee\", \"Suitcase\",\"Tie\",\"Handbag\",", "Glass\", \"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\",", "global newValue1 global newValue2 global newValue3 global newValue4 global newValue5", "application reset via a soft reboot. # In this case,", "{}\".format(newValue8)) # Create the DDATA payload - Use the alias", "nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\" Unable to", "persons to whom the # Software is furnished to do", "0, False) # Publish a message Input 8 #publishBirth() elif", "True) addMetric(payload, \"output/Device Metric4\", AliasMap.Device_Metric4, MetricDataType.String, \"start\") # Publish the", "+ myDeviceName, totalByteArray, 0, False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global", "when the client receives a CONNACK response from the server.", "#publishBirth() elif metric.name == \"output/Device Input7\" or metric.alias == AliasMap.Device_Input7:", "MetricDataType.Int16, Object4) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, Object5) addMetric(payload, \"input/Device", "to create NvStreamMux \\n\") # Use nvinfer to run inferencing", "# raw format for many logi usb cams # In", "metric.alias == AliasMap.Rebirth: # 'Node Control/Rebirth' is an NCMD used", "output/Device Input2 - New Value: {}\".format(newValue2)) # Create the DDATA", "Publish a message Input 1 #publishBirth() elif metric.name == \"output/Device", "if not gst_buffer: print(\"Unable to get GstBuffer \") return #", "MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN", "13 PGIE_CLASS_ID_PARKING_METER = 12 PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10", "AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame Number\", AliasMap.Device_frame_numberx, MetricDataType.Int16, frame_numberx", "create pgie \\n\") # Use convertor to convert from NV12", "= bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/DBIRTH/\" + myNodeName +", "Unable to get source pad of caps_vidconvsrc \\n\") srcpad.link(sinkpad) streammux.link(pgie)", "newValue9 = 0 newValue10 = 0 class AliasMap: Next_Server =", "myNodeName # Subscribing in on_connect() means that if we lose", "Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2, MetricDataType.Int16, 0)", "if not nvvidconvsrc: sys.stderr.write(\" Unable to create Nvvideoconvert \\n\") caps_vidconvsrc", "cams # In case we have a camera with raw", "to get informed of the meta data generated, we add", "myNodeName, deathByteArray, 0, False) client.connect(serverUrl, 1883, 60) # Publish the", "= 47 PGIE_CLASS_ID_BANANA = 46 PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON =", "by # videoconvert doing passthrough (TODO we need to confirm", "\"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\" Unable to create Nvvideoconvert \\n\")", "BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,", "= 33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS =", "Device_Output3 = 24 Device_Output4 = 25 Device_Output5 = 26 Device_Output6", "= 0 newValue6 = 0 newValue7 = 0 newValue8 =", "7 PGIE_CLASS_ID_TRAIN = 6 PGIE_CLASS_ID_BUS = 5 PGIE_CLASS_ID_AEROPLANE = 4", "Pipeline \\n\") # Source element for reading from the file", "24 Device_Output4 = 25 Device_Output5 = 26 Device_Output6 = 27", "== AliasMap.Device_Metric2: # This is a metric we declared in", "AliasMap.Device_Input2, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input3\", AliasMap.Device_Input3, MetricDataType.Int16, 0) addMetric(payload,", "caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\"", "Publish a message Input 9 #publishBirth() elif metric.name == \"output/Device", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1) #", "converted RGBA buffer nvosd = Gst.ElementFactory.make(\"nvdsosd\", \"onscreendisplay\") if not nvosd:", "output/Device Input4 - New Value: {}\".format(newValue4)) # Create the DDATA", "addMetric(payload, \"input/number of objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"input/Frame", "pipeline.add(transform) # we link the elements together # v4l2src ->", "pgie_classes_str= [\"Toothbrush\", \"Hair dryer\", \"Teddy bear\",\"Scissors\",\"Vase\", \"Clock\", \"Book\",\"Refrigerator\", \"Sink\", \"Toaster\",\"Oven\",\"Microwave\",", "in the DBIRTH newValue6 = metric.int_value print (\"CMD message for", "Birth\") # Create the node birth payload payload = sparkplug.getNodeBirthPayload()", "= GObject.MainLoop() bus = pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call, loop)", "\"input/Device Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16,", "certificates publishBirth() def foo(): # Periodically publish some new data", "PGIE_CLASS_ID_BEAR = 21 PGIE_CLASS_ID_ELEPHANT = 20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP", "This can be used for devices that need a full", "28 Device_Output8 = 29 Device_Output9 = 30 Device_Output10 = 31", "is done by pyds.NvDsFrameMeta.cast() # The casting also keeps ownership", "reboot with a republishing of the NBIRTH and DBIRTH #", "pad of streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not srcpad:", "color py_nvosd_text_params.set_bg_clr = 1 # set(red, green, blue, alpha); set", "we lose the connection and # reconnect then subscriptions will", "# Reading the display_text field here will return the C", "the birth certificates publishBirth() def foo(): # Periodically publish some", "not all # raw formats are supported by nvvideoconvert; #", "# We know this is an Boolean because of how", "payload deathPayload = sparkplug.getNodeDeathPayload() # Start of main program -", "# memory will not be claimed by the garbage collector.", "caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1]) streammux.set_property('width', 640) streammux.set_property('height', 480) streammux.set_property('batch-size', 1)", "new data payload = sparkplug.getDdataPayload() # Add some random data", "do so, subject to the following conditions: # # The", "metric.alias == AliasMap.Device_Input8: # This is a metric we declared", "from the current MQTT server and connect to the next", "0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\",", "IN THE SOFTWARE. ################################################################################ import sys sys.path.append('../') sys.path.insert(0, \"../../../client_libraries/python/\") import", "byteArray, 0, False) #publishBirth() elif metric.name == \"output/Device Metric3\" or", "myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId + \"/DCMD/\" + myNodeName", "used to tell the device/client application to resend # its", "False) # Publish a message Input 5 #publishBirth() elif metric.name", "nvosd: sys.stderr.write(\" Unable to create nvosd \\n\") # Finally render", "source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if not sinkpad:", "== \"output/Device Input10\" or metric.alias == AliasMap.Device_Input10: # This is", "shall be included in # all copies or substantial portions", "AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload,", "KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO", "= 76 PGIE_CLASS_ID_VASE = 75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK =", "Reboot = 2 Device_frame_numberx = 3 Device_num_rectsx = 4 Device_Metric0", "+ \"/NCMD/\" + myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId +", "Input 1 #publishBirth() elif metric.name == \"output/Device Input1\" or metric.alias", "OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES", "\"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\", \"Areoplane\", \"Motorbike\",\"Car\", \"Bicycle\", \"Person\"] ######################################################################", "obj_counter[newValue3] Object4 = obj_counter[newValue4] Object5 = obj_counter[newValue5] Object6 = obj_counter[newValue6]", "device/client application to # disconnect from the current MQTT server", "nvvidconvsrc: sys.stderr.write(\" Unable to create Nvvideoconvert \\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\",", "Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth, MetricDataType.Boolean,", "the Software without restriction, including without limitation # the rights", "AliasMap.Device_Input9: # This is a metric we declared in our", "\"output/Device Metric2\" or metric.alias == AliasMap.Device_Metric2: # This is a", "not be claimed by the garbage collector. # Reading the", "Input5 - New Value: {}\".format(newValue5)) # Create the DDATA payload", "display_meta.text_params[0] # Setting display text to be shown on screen", "= 7 Device_Metric3 = 8 Device_Metric4 = 9 Device_counter1 =", "metric.name) else: print (\"Unknown command...\") print (\"Done publishing\") ##################################################################### ######################################################################", "collector will claim it when this probe function exits. display_meta=pyds.nvds_acquire_display_meta_from_pool(batch_meta)", "obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3 = obj_counter[newValue3]", "Device_Input10 = 21 Device_Output1 = 22 Device_Output2 = 23 Device_Output3", "if not nvvidconv: sys.stderr.write(\" Unable to create nvvidconv \\n\") #", "40 PGIE_CLASS_ID_BOTTLE = 39 PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD = 37", "\"/\" + myDeviceName, byteArray, 0, False) #publishBirth() elif metric.name ==", "MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5, MetricDataType.Int16, 0) addMetric(payload, \"input/Device", "client.connect(serverUrl, 1883, 60) # Publish the birth certificates publishBirth() def", "\"Node Control/Next Server\", AliasMap.Next_Server, MetricDataType.Boolean, False) addMetric(payload, \"Node Control/Rebirth\", AliasMap.Rebirth,", "the node birth certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId", "shall be intelligent enough to reduce compute by # videoconvert", "PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE = 35 PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE", "= 16 Device_Input6 = 17 Device_Input7 = 18 Device_Input8 =", "negotiation # shall be intelligent enough to reduce compute by", "connect with result code \"+str(rc)) sys.exit() global myGroupId global myNodeName", "\"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\",", "PGIE_CLASS_ID_SINK:0, PGIE_CLASS_ID_TOASTER:0, PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0,", "None: try: # Note that l_frame.data needs a cast to", "of available servers. This is used for clients that have", "to tell a device/client application to reboot # This can", "to pyds.NvDsFrameMeta # The casting is done by pyds.NvDsFrameMeta.cast() #", "is not implemented in this example\") elif metric.name == \"Node", "\"/DCMD/\" + myNodeName + \"/#\") ###################################################################### ###################################################################### # The callback", "+ myGroupId + \"/NCMD/\" + myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" +", "\"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16,", "== \"output/Device Input6\" or metric.alias == AliasMap.Device_Input6: # This is", "addMetric(payload, \"input/Number of Objects\", AliasMap.Device_num_rectsx, MetricDataType.Int16, num_rectsx ) addMetric(payload, \"output/Device", "# Setting display text to be shown on screen #", "the connection and # reconnect then subscriptions will be renewed.", "the display_text field here will return the C address of", "addMetric(payload, \"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish a message", "metric.name == \"output/Device Metric4\" or metric.alias == AliasMap.Device_Metric4: # This", "\"Bottle\", \"Tennis racket\",\"Surfboard\", \"Skateboard\", \"Baseball glove\",\"Baseball bat\",\"Kite\", \"Sports ball\", \"Snowboard\",\"Skis\",", "is why the application must send all known metrics in", "SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE", "should appear py_nvosd_text_params.x_offset = 10 py_nvosd_text_params.y_offset = 12 # Font", "\" + msg.topic) tokens = msg.topic.split(\"/\") global newValue1 global newValue2", "object counter with 0. obj_counter = { PGIE_CLASS_ID_TOOTHBRUSH:0, PGIE_CLASS_ID_HAIR_DRYER:0, PGIE_CLASS_ID_TEDDY_BEAR:0,", "and tokens[1] == myGroupId and (tokens[2] == \"NCMD\" or tokens[2]", "output/Device Metric4 - New Value: {}\".format(newValue)) # Create the DDATA", "Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE]) Object1 = obj_counter[newValue1] Object2", "we declated it in the DBIRTH newValue6 = metric.int_value print", "\"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\", \"Chair\",\"Cake\",\"Donut\", \"Pizza\", \"Hot dog\",\"Carrot\",", "string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta) try: l_frame=l_frame.next except StopIteration: break", "# videoconvert doing passthrough (TODO we need to confirm this)", "to be shown on screen # Note that the pyds", "metric.alias == AliasMap.Device_Input1: # This is a metric we declared", "= 0 newValue1 = 0 newValue2 = 0 newValue3 =", "%s \" %args[1]) caps_v4l2src.set_property('caps', Gst.Caps.from_string(\"video/x-raw, framerate=30/1\")) caps_vidconvsrc.set_property('caps', Gst.Caps.from_string(\"video/x-raw(memory:NVMM)\")) source.set_property('device', args[1])", "of how we declated it in the DBIRTH newValue9 =", "client.publish(\"spBv1.0/\" + myGroupId + \"/DDATA/\" + myNodeName + \"/\" +", "PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0,", "\\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if not caps_v4l2src: sys.stderr.write(\" Unable", "# Create gstreamer elements # Create Pipeline element that will", "\\n\") caps_vidconvsrc = Gst.ElementFactory.make(\"capsfilter\", \"nvmm_caps\") if not caps_vidconvsrc: sys.stderr.write(\" Unable", "osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx global Object1 global Object2 global", "PGIE_CLASS_ID_STOP_SIGN = 11 PGIE_CLASS_ID_FIRE_HYDRANT = 10 PGIE_CLASS_ID_TRAFFIC_LIGHT = 9 PGIE_CLASS_ID_BOAT", "== \"output/Device Input7\" or metric.alias == AliasMap.Device_Input7: # This is", "raw formats are supported vidconvsrc = Gst.ElementFactory.make(\"videoconvert\", \"convertor_src1\") if not", "\") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source: sys.stderr.write(\" Unable", "try: l_frame=l_frame.next except StopIteration: break return Gst.PadProbeReturn.OK ###################################################################### def main(args):", "is_aarch64(): pipeline.add(transform) # we link the elements together # v4l2src", "myGroupId + \"/DCMD/\" + myNodeName + \"/#\") ###################################################################### ###################################################################### #", "obj_counter[newValue10] # Now set the offsets where the string should", "client connection client.on_connect = on_connect client.on_message = on_message client.username_pw_set(myUsername, myPassword)", "None, AliasMap.Device_Input10, MetricDataType.Int16, newValue10) # Publish a message data byteArray", "so downstream plugins can still access it. Otherwise # the", "nvosd.link(sink) # create an event loop and feed gstreamer bus", "a pool of MQTT servers # to connect to. print", "a camera with raw format supported in # nvvideoconvert, GStreamer", "Device_num_rectsx = 4 Device_Metric0 = 5 Device_Metric1 = 6 Device_Metric2", "= 21 Device_Output1 = 22 Device_Output2 = 23 Device_Output3 =", "or metric.alias == AliasMap.Device_Input5: # This is a metric we", "- New Value: {}\".format(newValue10)) # Create the DDATA payload -", "byteArray, 0, False) # Publish a message Input 3 #publishBirth()", "addMetric(payload, \"output/Device Input1\", AliasMap.Device_Input1, MetricDataType.Int16, 0) addMetric(payload, \"output/Device Input2\", AliasMap.Device_Input2,", "Control/Next Server' is an NCMD used to tell the device/client", "PGIE_CLASS_ID_BASEBALL_BAT:0, PGIE_CLASS_ID_KITE:0, PGIE_CLASS_ID_SPORTS_BALL:0, PGIE_CLASS_ID_SNOWBOARD:0, PGIE_CLASS_ID_SKIS:0, PGIE_CLASS_ID_FRISBEE:0, PGIE_CLASS_ID_SUITCASE:0, PGIE_CLASS_ID_TIE:0, PGIE_CLASS_ID_HANDBAG:0, PGIE_CLASS_ID_UMBRELLA:0,", "0, False) # Publish a message Input 5 #publishBirth() elif", "print(\"Linking elements in the Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc)", "global Object7 global Object8 global Object9 global Object10 #Intiallizing object", "64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET = 61", "WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND", "is set through config file pgie = Gst.ElementFactory.make(\"nvinfer\", \"primary-inference\") if", "= 5 Device_Metric1 = 6 Device_Metric2 = 7 Device_Metric3 =", "\"Sink\", \"Toaster\",\"Oven\",\"Microwave\", \"Cell phone\", \"Keyboard\",\"Remote\", \"Mouse\", \"Laptop\",\"Tvmonitor\",\"Toilet\", \"Diningtable\", \"Bed\",\"Pottedplant\", \"Sofa\",", "the elements together # v4l2src -> nvvideoconvert -> mux ->", "MetricDataType.Int16, Object6) addMetric(payload, \"input/Device Output7\", AliasMap.Device_Output7, MetricDataType.Int16, Object7) addMetric(payload, \"input/Device", "Pipeline \\n\") source.link(caps_v4l2src) caps_v4l2src.link(vidconvsrc) vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if", "foo).start() foo() ###################################################################### print(\"Starting pipeline \\n\") pipeline.set_state(Gst.State.PLAYING) try: loop.run() except:", "Gst from common.is_aarch_64 import is_aarch64 from common.bus_call import bus_call from", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input9, MetricDataType.Int16, newValue9) # Publish", "global frame_numberx global num_rectsx global Object1 global Object2 global Object3", "myNodeName = \"NVIDIA\" myDeviceName = \"XavierNX\" publishPeriod = 5000 myUsername", "alone. frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects", "False) # Publish a message Input 2 #publishBirth() elif metric.name", "IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,", "with result code \"+str(rc)) sys.exit() global myGroupId global myNodeName #", "PGIE_CLASS_ID_BOWL = 45 PGIE_CLASS_ID_SPOON = 44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK", "= bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\" + myNodeName, deathByteArray,", "sparkplug_b as sparkplug import time import time, threading import random", "Boolean because of how we declated it in the DBIRTH", "= 63 PGIE_CLASS_ID_TVMONITOR = 62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60", "PGIE_CLASS_ID_TENNIS_RACKET = 38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE", "false to avoid late frame drops at the display-sink sink.set_property('sync',", "DDATA with a metric that was not published in the", "= batch_meta.frame_meta_list while l_frame is not None: try: # Note", "PGIE_CLASS_ID_TOASTER = 70 PGIE_CLASS_ID_OVEN = 69 PGIE_CLASS_ID_MICROWAVE = 68 PGIE_CLASS_ID_CELL_PHONE", "the DBIRTH newValue = metric.string_value print (\"CMD message for output/Device", "0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2,", "flags, rc): if rc == 0: print(\"Connected with result code", "PGIE_CLASS_ID_BACKPACK:0, PGIE_CLASS_ID_GIRAFFE:0, PGIE_CLASS_ID_ZEBRA:0, PGIE_CLASS_ID_BEAR:0, PGIE_CLASS_ID_ELEPHANT:0, PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0,", "25 Device_Output5 = 26 Device_Output6 = 27 Device_Output7 = 28", "it in the DBIRTH newValue = metric.int_value print (\"CMD message", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) #", "be renewed. client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\" + myNodeName +", "an Int16 because of how we declated it in the", "0) addMetric(payload, \"output/Device Input10\", AliasMap.Device_Input10, MetricDataType.Int16, 0) addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1,", "pyds.get_string() to get display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text)) #pyds.nvds_add_display_meta_to_frame(frame_meta, display_meta)", "(\"CMD message for output/Device Input7 - New Value: {}\".format(newValue7)) #", "not gst_buffer: print(\"Unable to get GstBuffer \") return # Retrieve", "it in the DBIRTH newValue7 = metric.int_value print (\"CMD message", "message Input 5 #publishBirth() elif metric.name == \"output/Device Input5\" or", "= 51 PGIE_CLASS_ID_BROCCOLI = 50 PGIE_CLASS_ID_ORANGE = 49 PGIE_CLASS_ID_SANDWICH =", "resend # its full NBIRTH and DBIRTH again. MQTT Engine", "of how we declated it in the DBIRTH newValue8 =", "frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects = frame_meta.num_obj_meta num_rectsx = frame_meta.num_obj_meta l_obj=frame_meta.obj_meta_list while", "Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source: sys.stderr.write(\" Unable to create Source", "copies or substantial portions of the Software. # # THE", "logi usb cams # In case we have a camera", "# Create the DDATA payload - use the alias because", "PGIE_CLASS_ID_OVEN:0, PGIE_CLASS_ID_MICROWAVE:0, PGIE_CLASS_ID_CELL_PHONE:0, PGIE_CLASS_ID_KEYBOARD:0, PGIE_CLASS_ID_REMOTE:0, PGIE_CLASS_ID_MOUSE:0, PGIE_CLASS_ID_LAPTOP:0, PGIE_CLASS_ID_TVMONITOR:0, PGIE_CLASS_ID_TOILET:0, PGIE_CLASS_ID_DININGTABLE:0,", "sink pad of streammux \\n\") srcpad = caps_vidconvsrc.get_static_pad(\"src\") if not", "newValue7 = 0 newValue8 = 0 newValue9 = 0 newValue10", "+ myDeviceName, byteArray, 0, False) #global newValue4 #publishBirth() elif metric.name", "this NCMD to a device/client # application if it receives", "gst_buffer = info.get_buffer() if not gst_buffer: print(\"Unable to get GstBuffer", "Create the node death payload deathPayload = sparkplug.getNodeDeathPayload() # Start", "a metric that was not published in the # original", "+ \"/NBIRTH/\" + myNodeName, byteArray, 0, False) ###################################################################### ###################################################################### #", "AliasMap.Reboot: # 'Node Control/Reboot' is an NCMD used to tell", "= streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\" Unable to get the", "it in the DBIRTH newValue10 = metric.int_value print (\"CMD message", "rc == 0: print(\"Connected with result code \"+str(rc)) else: print(\"Failed", "+ myNodeName + \"/\" + myDeviceName, byteArray, 0, False) else:", "certificates ###################################################################### def publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### # Publish", "publishBirth(): publishNodeBirth() publishDeviceBirth() ###################################################################### ###################################################################### # Publish the NBIRTH certificate", "== \"Node Control/Reboot\" or metric.alias == AliasMap.Reboot: # 'Node Control/Reboot'", "AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish a message data byteArray =", "ownership remains in # the C code so downstream plugins", "55 PGIE_CLASS_ID_DONUT = 54 PGIE_CLASS_ID_PIZZA = 53 PGIE_CLASS_ID_HOT_DOG = 52", "= 0 Object3 = 0 Object4 = 0 Object5 =", "= 20 PGIE_CLASS_ID_COW = 19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE =", "sys.stderr.write(\"usage: %s <v4l2-device-path>\\n\" % args[0]) sys.exit(1) # Standard GStreamer initialization", "GstBuffer \") return # Retrieve batch metadata from the gst_buffer", "main program - Set up the MQTT client connection client.on_connect", "vidconvsrc.link(nvvidconvsrc) nvvidconvsrc.link(caps_vidconvsrc) sinkpad = streammux.get_request_pad(\"sink_0\") if not sinkpad: sys.stderr.write(\" Unable", "command: \" + metric.name) else: print (\"Unknown command...\") print (\"Done", "#!/usr/bin/env python3 ################################################################################ # Copyright (c) 2020, NVIDIA CORPORATION. All", "OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT", "2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON = 0 pgie_classes_str= [\"Toothbrush\", \"Hair", "# Using pyds.get_string() to get display_text as string # print(pyds.get_string(py_nvosd_text_params.display_text))", "New Value: {}\".format(newValue6)) # Create the DDATA payload - Use", "False) ###################################################################### ###################################################################### def osd_sink_pad_buffer_probe(pad,info,u_data): global frame_numberx global num_rectsx global", "renewed. client.subscribe(\"spBv1.0/\" + myGroupId + \"/NCMD/\" + myNodeName + \"/#\")", "client.on_connect = on_connect client.on_message = on_message client.username_pw_set(myUsername, myPassword) deathByteArray =", "= metric.int_value print (\"CMD message for output/Device Input3 - New", "(NvBufSurface API) nvvidconvsrc = Gst.ElementFactory.make(\"nvvideoconvert\", \"convertor_src2\") if not nvvidconvsrc: sys.stderr.write(\"", "avoid late frame drops at the display-sink sink.set_property('sync', False) print(\"Adding", "PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR = 72 PGIE_CLASS_ID_SINK = 71 PGIE_CLASS_ID_TOASTER", "Output2\", AliasMap.Device_Output2, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, 0)", "sys.stderr.write(\" Unable to create v4l2src capsfilter \\n\") print(\"Creating Video Converter", "(tokens[2] == \"NCMD\" or tokens[2] == \"DCMD\") and tokens[3] ==", "Unable to create Source \\n\") caps_v4l2src = Gst.ElementFactory.make(\"capsfilter\", \"v4l2src_caps\") if", "byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\" + myNodeName,", "PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE", "myNodeName: inboundPayload = sparkplug_b_pb2.Payload() inboundPayload.ParseFromString(msg.payload) for metric in inboundPayload.metrics: if", "Input8 - New Value: {}\".format(newValue8)) # Create the DDATA payload", "= \"admin\" myPassword = \"<PASSWORD>\" client = mqtt.Client(serverUrl, 1883, 60)", "62 PGIE_CLASS_ID_TOILET = 61 PGIE_CLASS_ID_DININGTABLE= 60 PGIE_CLASS_ID_BED = 59 PGIE_CLASS_ID_POTTEDPLANT", "we're emulating an output. # So, on incoming 'writes' to", "= 0 Object5 = 0 Object6 = 0 Object7 =", "create nvosd \\n\") # Finally render the osd output if", "the server. ###################################################################### def on_message(client, userdata, msg): print(\"Message arrived: \"", "\"Frame Number={} Number of Objects={} Bird_count={} Person_count={}\".format(frame_number, num_rects, obj_counter[PGIE_CLASS_ID_CUP], obj_counter[PGIE_CLASS_ID_BOTTLE])", "# list of available servers. This is used for clients", "doing passthrough (TODO we need to confirm this) # videoconvert", "= 24 PGIE_CLASS_ID_GIRAFFE = 23 PGIE_CLASS_ID_ZEBRA = 22 PGIE_CLASS_ID_BEAR =", "payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric4, MetricDataType.String, newValue) # Publish", "0: print(\"Connected with result code \"+str(rc)) else: print(\"Failed to connect", "= 34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD =", "myGroupId + \"/NCMD/\" + myNodeName + \"/#\") client.subscribe(\"spBv1.0/\" + myGroupId", "PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0, PGIE_CLASS_ID_AEROPLANE:0, PGIE_CLASS_ID_MOTORBIKE:0, PGIE_CLASS_ID_VEHICLE:0, PGIE_CLASS_ID_BICYCLE:0, PGIE_CLASS_ID_PERSON:0 }", "False) ###################################################################### ###################################################################### # Publish the DBIRTH certificate ###################################################################### def", "DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Metric3, MetricDataType.Boolean, newValue) #", "\"localhost\" myGroupId = \"Sparkplug B Devices\" myNodeName = \"NVIDIA\" myDeviceName", "= 44 PGIE_CLASS_ID_KNIFE = 43 PGIE_CLASS_ID_FORK = 42 PGIE_CLASS_ID_CUP =", "= metric.int_value print (\"CMD message for output/Device Input9 - New", "element that will form a connection of other elements print(\"Creating", "addMetric(payload, None, AliasMap.Device_Input4, MetricDataType.Int16, newValue4) # Publish a message data", ") addMetric(payload,\"input/Device Output1\", AliasMap.Device_Output1, MetricDataType.Int16, Object1) addMetric(payload, \"input/Device Output2\", AliasMap.Device_Output2,", "frame_numberx = 0 num_rectsx = 0 counter1 = 0 counter2", "servers # to connect to. print (\"'Node Control/Next Server' is", "response from the server. ###################################################################### def on_connect(client, userdata, flags, rc):", "frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data) except StopIteration: break frame_number=frame_meta.frame_num frame_numberx=frame_meta.frame_num num_rects =", "Control/Reboot\" or metric.alias == AliasMap.Reboot: # 'Node Control/Reboot' is an", "myGroupId + \"/DBIRTH/\" + myNodeName + \"/\" + myDeviceName, totalByteArray,", "try: loop.run() except: pass #cleanup print(\"Exiting app\\n\") pipeline.set_state(Gst.State.NULL) if __name__", "used for devices that need a full application reset via", "# Publish the NBIRTH certificate ###################################################################### def publishNodeBirth(): print (\"Publishing", "# Acquiring a display meta object. The memory ownership remains", "addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number of Objects\",", "= \"XavierNX\" publishPeriod = 5000 myUsername = \"admin\" myPassword =", "== \"output/Device Input8\" or metric.alias == AliasMap.Device_Input8: # This is", "myDeviceName, byteArray, 0, False) # Publish a message Input 7", "NBIRTH certificate ###################################################################### def publishNodeBirth(): print (\"Publishing Node Birth\") #", "32 PGIE_CLASS_ID_SNOWBOARD = 31 PGIE_CLASS_ID_SKIS = 30 PGIE_CLASS_ID_FRISBEE = 29", "birth certificate byteArray = bytearray(payload.SerializeToString()) client.publish(\"spBv1.0/\" + myGroupId + \"/NBIRTH/\"", "PGIE_CLASS_ID_COW:0, PGIE_CLASS_ID_SHEEP:0, PGIE_CLASS_ID_HORSE:0, PGIE_CLASS_ID_DOG:0, PGIE_CLASS_ID_CAT:0, PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0,", "\"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic light\", \"Boat\", \"Truck\",\"Train\",\"Bus\",", "not srcpad: sys.stderr.write(\" Unable to get source pad of caps_vidconvsrc", "is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\") sink =", "newValue3 = 0 newValue4 = 0 newValue5 = 0 newValue6", "global num_rectsx global Object1 global Object2 global Object3 global Object4", "elif metric.name == \"output/Device Input2\" or metric.alias == AliasMap.Device_Input2: #", "create Pipeline \\n\") # Source element for reading from the", "= 29 Device_Output9 = 30 Device_Output10 = 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH", "\"input/Device Output10\", AliasMap.Device_Output10, MetricDataType.Int16, Object10) # Publish a message data", "the DBIRTH newValue3 = metric.int_value print (\"CMD message for output/Device", "client.username_pw_set(myUsername, myPassword) deathByteArray = bytearray(deathPayload.SerializeToString()) client.will_set(\"spBv1.0/\" + myGroupId + \"/NDEATH/\"", "in the DBIRTH newValue1 = metric.int_value print (\"CMD message for", "= 0 Object7 = 0 Object8 = 0 Object9 =", "= 31 MAX_DISPLAY_LEN=64 PGIE_CLASS_ID_TOOTHBRUSH = 79 PGIE_CLASS_ID_HAIR_DRYER = 78 PGIE_CLASS_ID_TEDDY_BEAR", "device\") addMetric(payload, \"input/Device Metric1\", AliasMap.Device_Metric1, MetricDataType.Boolean, True) addMetric(payload, \"input/Number of", "metric.name == \"output/Device Metric2\" or metric.alias == AliasMap.Device_Metric2: # This", "nvvidconv.link(nvosd) if is_aarch64(): nvosd.link(transform) transform.link(sink) else: nvosd.link(sink) # create an", "Publish a message Input 3 #publishBirth() elif metric.name == \"output/Device", "+ \"/DCMD/\" + myNodeName + \"/#\") ###################################################################### ###################################################################### # The", "= 3 PGIE_CLASS_ID_VEHICLE = 2 PGIE_CLASS_ID_BICYCLE = 1 PGIE_CLASS_ID_PERSON =", "render the osd output if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\")", "of how we declated it in the DBIRTH newValue7 =", "PGIE_CLASS_ID_BIRD:0, PGIE_CLASS_ID_BENCH:0, PGIE_CLASS_ID_PARKING_METER:0, PGIE_CLASS_ID_STOP_SIGN:0, PGIE_CLASS_ID_FIRE_HYDRANT:0, PGIE_CLASS_ID_TRAFFIC_LIGHT:0, PGIE_CLASS_ID_BOAT:0, PGIE_CLASS_ID_TRUCK:0, PGIE_CLASS_ID_TRAIN:0, PGIE_CLASS_ID_BUS:0,", "= 38 PGIE_CLASS_ID_SURFBOARD = 37 PGIE_CLASS_ID_SKATEBOARD = 36 PGIE_CLASS_ID_BASEBALL_GLOVE =", "PGIE_CLASS_ID_SUITCASE = 28 PGIE_CLASS_ID_TIE = 27 PGIE_CLASS_ID_HANDBAG = 26 PGIE_CLASS_ID_UMBRELLA", "Source \\n \") source = Gst.ElementFactory.make(\"v4l2src\", \"usb-cam-source\") if not source:", "to use, copy, modify, merge, publish, distribute, sublicense, # and/or", "= 65 PGIE_CLASS_ID_MOUSE = 64 PGIE_CLASS_ID_LAPTOP = 63 PGIE_CLASS_ID_TVMONITOR =", "we declated it in the DBIRTH newValue = metric.boolean_value print", "= obj_counter[newValue1] Object2 = obj_counter[newValue2] Object3 = obj_counter[newValue3] Object4 =", "transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink \\n\") sink = Gst.ElementFactory.make(\"nveglglessink\",", "addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output5\", AliasMap.Device_Output5,", "Value: {}\".format(newValue9)) # Create the DDATA payload - Use the", "Object3 global Object4 global Object5 global Object6 global Object7 global", "# DEALINGS IN THE SOFTWARE. ################################################################################ import sys sys.path.append('../') sys.path.insert(0,", "\"Bear\",\"Elephant\",\"Cow\", \"Sheep\", \"Horse\",\"Dog\", \"Cat\", \"Bird\",\"Bench\",\"Parking meter\", \"Stop sign\", \"Fire hydrant\",\"Traffic", "{}\".format(newValue9)) # Create the DDATA payload - Use the alias", "to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id] += 1 try:", "#publishBirth() elif metric.name == \"output/Device Input2\" or metric.alias == AliasMap.Device_Input2:", "sys.stderr.write(\" Unable to get the sink pad of streammux \\n\")", "sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input8, MetricDataType.Int16, newValue8) # Publish a message", "PGIE_CLASS_ID_BASEBALL_BAT = 34 PGIE_CLASS_ID_KITE = 33 PGIE_CLASS_ID_SPORTS_BALL = 32 PGIE_CLASS_ID_SNOWBOARD", "\"input/Device Output3\", AliasMap.Device_Output3, MetricDataType.Int16, Object3) addMetric(payload, \"input/Device Output4\", AliasMap.Device_Output4, MetricDataType.Int16,", "= pipeline.get_bus() bus.add_signal_watch() bus.connect (\"message\", bus_call, loop) # Lets add", "metric.int_value print (\"CMD message for output/Device Metric2 - New Value:", "None, AliasMap.Device_Input2, MetricDataType.Int16, newValue2) # Publish a message data byteArray", "newValue4 = 0 newValue5 = 0 newValue6 = 0 newValue7", "probe to # the sink pad of the osd element,", "= 16 PGIE_CLASS_ID_CAT = 15 PGIE_CLASS_ID_BIRD = 14 PGIE_CLASS_ID_BENCH =", "metric.int_value print (\"CMD message for output/Device Input2 - New Value:", "newValue5 = metric.int_value print (\"CMD message for output/Device Input5 -", "Create the DDATA payload - Use the alias because this", "in the DBIRTH newValue10 = metric.int_value print (\"CMD message for", "global newValue7 global newValue8 global newValue9 global newValue10 if tokens[0]", "DBIRTH newValue4 = metric.int_value print (\"CMD message for output/Device Input4", "The above copyright notice and this permission notice shall be", "= 19 PGIE_CLASS_ID_SHEEP = 18 PGIE_CLASS_ID_HORSE = 17 PGIE_CLASS_ID_DOG =", "not published in the # original NBIRTH or DBIRTH. This", "{}\".format(newValue6)) # Create the DDATA payload - Use the alias", "\"input/Device Output8\", AliasMap.Device_Output8, MetricDataType.Int16, 0) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16,", "in the Software without restriction, including without limitation # the", "lose the connection and # reconnect then subscriptions will be", "print (\"CMD message for output/Device Input4 - New Value: {}\".format(newValue4))", "the DBIRTH payload = sparkplug.getDdataPayload() addMetric(payload, None, AliasMap.Device_Input1, MetricDataType.Int16, newValue1)", "Casting l_obj.data to pyds.NvDsObjectMeta obj_meta=pyds.NvDsObjectMeta.cast(l_obj.data) except StopIteration: break obj_counter[obj_meta.class_id] +=", "because of how we declated it in the DBIRTH newValue7", "for output/Device Input10 - New Value: {}\".format(newValue10)) # Create the", "PGIE_CLASS_ID_CHAIR:0, PGIE_CLASS_ID_CAKE:0, PGIE_CLASS_ID_DONUT:0, PGIE_CLASS_ID_PIZZA:0, PGIE_CLASS_ID_HOT_DOG:0, PGIE_CLASS_ID_CARROT:0, PGIE_CLASS_ID_BROCCOLI:0, PGIE_CLASS_ID_ORANGE:0, PGIE_CLASS_ID_SANDWICH:0, PGIE_CLASS_ID_APPLE:0,", "75 PGIE_CLASS_ID_CLOCK = 74 PGIE_CLASS_ID_BOOK = 73 PGIE_CLASS_ID_REFRIGERATOR = 72", "print (\"CMD message for output/Device Input5 - New Value: {}\".format(newValue5))", "= 0 newValue5 = 0 newValue6 = 0 newValue7 =", "\"+str(rc)) sys.exit() global myGroupId global myNodeName # Subscribing in on_connect()", "without limitation # the rights to use, copy, modify, merge,", "byteArray, 0, False) #global newValue4 #publishBirth() elif metric.name == \"output/Device", "write to the output and then read it back #", "payload payload = sparkplug.getNodeBirthPayload() # Set up the Node Controls", "memory ownership remains in # the C code so downstream", "Output8\", AliasMap.Device_Output8, MetricDataType.Int16, Object8) addMetric(payload, \"input/Device Output9\", AliasMap.Device_Output9, MetricDataType.Int16, Object9)", "osd output if is_aarch64(): transform = Gst.ElementFactory.make(\"nvegltransform\", \"nvegl-transform\") print(\"Creating EGLSink", "\"convertor\") if not nvvidconv: sys.stderr.write(\" Unable to create nvvidconv \\n\")", "output/Device Input9 - New Value: {}\".format(newValue9)) # Create the DDATA", "27 Device_Output7 = 28 Device_Output8 = 29 Device_Output9 = 30", "Create the DDATA payload - use the alias because this", "None, AliasMap.Device_Input3, MetricDataType.Int16, newValue3) # Publish a message data byteArray", "New Value: %r\" % newValue) # Create the DDATA payload", "The callback for when the client receives a CONNACK response", "supported in # nvvideoconvert, GStreamer plugins' capability negotiation # shall" ]
[ "AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. #", "DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES", "(ZPL). A copy of the ZPL should accompany this distribution.", "A copy of the ZPL should accompany this distribution. #", "provisions of the Zope Public License, # Version 2.1 (ZPL).", "def get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir = os.path.split(value)[0] if package_dir", "All Rights Reserved. # # This software is subject to", "IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR", "import os import sys def get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir", "A PARTICULAR PURPOSE. # \"\"\" Generic test cases for pyams_i18n", "THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL", "test cases for pyams_i18n doctests \"\"\" __docformat__ = 'restructuredtext' import", "is subject to the provisions of the Zope Public License,", "FITNESS # FOR A PARTICULAR PURPOSE. # \"\"\" Generic test", "should accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS", "Copyright (c) 2015-2019 <NAME> <tflorac AT ulthar.net> # All Rights", "to the provisions of the Zope Public License, # Version", "AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING,", "the provisions of the Zope Public License, # Version 2.1", "copy of the ZPL should accompany this distribution. # THIS", "__docformat__ = 'restructuredtext' import os import sys def get_package_dir(value): \"\"\"Get", "'restructuredtext' import os import sys def get_package_dir(value): \"\"\"Get package directory\"\"\"", "OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A", "\"\"\" Generic test cases for pyams_i18n doctests \"\"\" __docformat__ =", "\"\"\"Get package directory\"\"\" package_dir = os.path.split(value)[0] if package_dir not in", "BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE,", "Reserved. # # This software is subject to the provisions", "os import sys def get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir =", "\"\"\" __docformat__ = 'restructuredtext' import os import sys def get_package_dir(value):", "WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED", "distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY", "of the ZPL should accompany this distribution. # THIS SOFTWARE", "IS\" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES", "IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO,", "AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE", "(c) 2015-2019 <NAME> <tflorac AT ulthar.net> # All Rights Reserved.", "subject to the provisions of the Zope Public License, #", "# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS #", "package_dir = os.path.split(value)[0] if package_dir not in sys.path: sys.path.append(package_dir) return", "PURPOSE. # \"\"\" Generic test cases for pyams_i18n doctests \"\"\"", "FOR A PARTICULAR PURPOSE. # \"\"\" Generic test cases for", "pyams_i18n doctests \"\"\" __docformat__ = 'restructuredtext' import os import sys", "cases for pyams_i18n doctests \"\"\" __docformat__ = 'restructuredtext' import os", "# # This software is subject to the provisions of", "PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED", "= os.path.split(value)[0] if package_dir not in sys.path: sys.path.append(package_dir) return package_dir", "ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #", "# This software is subject to the provisions of the", "accompany this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\"", "ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT", "THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND", "Generic test cases for pyams_i18n doctests \"\"\" __docformat__ = 'restructuredtext'", "<tflorac AT ulthar.net> # All Rights Reserved. # # This", "this distribution. # THIS SOFTWARE IS PROVIDED \"AS IS\" AND", "Rights Reserved. # # This software is subject to the", "LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST", "package directory\"\"\" package_dir = os.path.split(value)[0] if package_dir not in sys.path:", "sys def get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir = os.path.split(value)[0] if", "MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE.", "doctests \"\"\" __docformat__ = 'restructuredtext' import os import sys def", "\"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED #", "INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # \"\"\"", "SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS", "ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED,", "of the Zope Public License, # Version 2.1 (ZPL). A", "# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE", "TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR", "# # Copyright (c) 2015-2019 <NAME> <tflorac AT ulthar.net> #", "Public License, # Version 2.1 (ZPL). A copy of the", "AT ulthar.net> # All Rights Reserved. # # This software", "2.1 (ZPL). A copy of the ZPL should accompany this", "PARTICULAR PURPOSE. # \"\"\" Generic test cases for pyams_i18n doctests", "This software is subject to the provisions of the Zope", "software is subject to the provisions of the Zope Public", "ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED", "get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir = os.path.split(value)[0] if package_dir not", "the ZPL should accompany this distribution. # THIS SOFTWARE IS", "2015-2019 <NAME> <tflorac AT ulthar.net> # All Rights Reserved. #", "AND FITNESS # FOR A PARTICULAR PURPOSE. # \"\"\" Generic", "INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF", "# Version 2.1 (ZPL). A copy of the ZPL should", "# FOR A PARTICULAR PURPOSE. # \"\"\" Generic test cases", "NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY,", "# All Rights Reserved. # # This software is subject", "directory\"\"\" package_dir = os.path.split(value)[0] if package_dir not in sys.path: sys.path.append(package_dir)", "ulthar.net> # All Rights Reserved. # # This software is", "Zope Public License, # Version 2.1 (ZPL). A copy of", "OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED", "for pyams_i18n doctests \"\"\" __docformat__ = 'restructuredtext' import os import", "= 'restructuredtext' import os import sys def get_package_dir(value): \"\"\"Get package", "TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT,", "<filename>src/pyams_i18n/tests/__init__.py # # Copyright (c) 2015-2019 <NAME> <tflorac AT ulthar.net>", "Version 2.1 (ZPL). A copy of the ZPL should accompany", "EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT", "import sys def get_package_dir(value): \"\"\"Get package directory\"\"\" package_dir = os.path.split(value)[0]", "<NAME> <tflorac AT ulthar.net> # All Rights Reserved. # #", "License, # Version 2.1 (ZPL). A copy of the ZPL", "# \"\"\" Generic test cases for pyams_i18n doctests \"\"\" __docformat__", "the Zope Public License, # Version 2.1 (ZPL). A copy", "# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND", "WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR", "IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS", "# Copyright (c) 2015-2019 <NAME> <tflorac AT ulthar.net> # All" ]
[ "custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _): expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1", "num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _):", "expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint,", "@pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2,", "= expert1(batch) loss = output0.sum() loss.backward() loss = output1.sum() loss.backward()", "batch = torch.randn(batch_size, hid_dim) output0 = expert0(batch) output1 = expert1(batch)", "test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH,", "= torch.randn(batch_size, hid_dim) output0 = expert0(batch) output1 = expert1(batch) loss", "background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as", "RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1, 4): batch = torch.randn(batch_size,", "= os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\",", "os import pytest import torch from hivemind import RemoteExpert from", "( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size, 3 *", "server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1, 4):", "background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with", ") as (server_endpoint, _): expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1 =", "hivemind import RemoteExpert from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__),", "expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint) for batch_size", "= output0.sum() loss.backward() loss = output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16):", "RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1, 4): batch = (", "output0 = expert0(batch) output1 = expert1(batch) loss = output0.sum() loss.backward()", ") output0 = expert0(*batch) output1 = expert1(*batch) loss = output0.sum()", "pytest import torch from hivemind import RemoteExpert from hivemind.moe.server import", "= ( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size, 3", "output1 = expert1(*batch) loss = output0.sum() loss.backward() loss = output1.sum()", "expert1(batch) loss = output0.sum() loss.backward() loss = output1.sum() loss.backward() @pytest.mark.forked", "loss.backward() loss = output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server(", "4): batch = torch.randn(batch_size, hid_dim) output0 = expert0(batch) output1 =", "background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as", "for batch_size in (1, 4): batch = torch.randn(batch_size, hid_dim) output0", "(server_endpoint, _): expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint)", "4): batch = ( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 * hid_dim),", "def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True,", "from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked", "2 * hid_dim), torch.randn(batch_size, 3 * hid_dim), ) output0 =", "for batch_size in (1, 4): batch = ( torch.randn(batch_size, hid_dim),", "output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\",", "server_endpoint) for batch_size in (1, 4): batch = torch.randn(batch_size, hid_dim)", "(1, 4): batch = ( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 *", "torch.randn(batch_size, hid_dim) output0 = expert0(batch) output1 = expert1(batch) loss =", "loss = output0.sum() loss.backward() loss = output1.sum() loss.backward() @pytest.mark.forked def", "\"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim,", "import pytest import torch from hivemind import RemoteExpert from hivemind.moe.server", "hid_dim), ) output0 = expert0(*batch) output1 = expert1(*batch) loss =", "hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def", "hid_dim), torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size, 3 * hid_dim), )", "loss = output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\",", "= RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1, 4): batch =", "output1 = expert1(batch) loss = output0.sum() loss.backward() loss = output1.sum()", "num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _): expert0 = RemoteExpert(\"expert.0\",", "= RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint) for batch_size in", "batch_size in (1, 4): batch = ( torch.randn(batch_size, hid_dim), torch.randn(batch_size,", "output0.sum() loss.backward() loss = output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with", "in (1, 4): batch = ( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2", "hid_dim), torch.randn(batch_size, 3 * hid_dim), ) output0 = expert0(*batch) output1", "server_endpoint) for batch_size in (1, 4): batch = ( torch.randn(batch_size,", "expert0(*batch) output1 = expert1(*batch) loss = output0.sum() loss.backward() loss =", "= expert0(*batch) output1 = expert1(*batch) loss = output0.sum() loss.backward() loss", "with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, )", "= expert1(*batch) loss = output0.sum() loss.backward() loss = output1.sum() loss.backward()", "as (server_endpoint, _): expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\",", "expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint,", "torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size, 3 * hid_dim), ) output0", "batch_size in (1, 4): batch = torch.randn(batch_size, hid_dim) output0 =", "import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16):", "* hid_dim), torch.randn(batch_size, 3 * hid_dim), ) output0 = expert0(*batch)", "\"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\",", "with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, )", "import os import pytest import torch from hivemind import RemoteExpert", "loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim,", "test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH,", "import torch from hivemind import RemoteExpert from hivemind.moe.server import background_server", "batch = ( torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size,", "def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True,", "@pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2, device=\"cpu\", hidden_dim=hid_dim, num_handlers=2,", "os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server( expert_cls=\"perceptron\", num_experts=2,", "device=\"cpu\", hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _): expert0", "from hivemind import RemoteExpert from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH =", "(1, 4): batch = torch.randn(batch_size, hid_dim) output0 = expert0(batch) output1", "expert0(batch) output1 = expert1(batch) loss = output0.sum() loss.backward() loss =", "RemoteExpert from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\")", "= expert0(batch) output1 = expert1(batch) loss = output0.sum() loss.backward() loss", "torch.randn(batch_size, 3 * hid_dim), ) output0 = expert0(*batch) output1 =", "_): expert0 = RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint) for", "no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _): expert0 = RemoteExpert(\"expert.0\", server_endpoint)", "expert1 = RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1, 4): batch", "hidden_dim=hid_dim, num_handlers=2, no_dht=True, custom_module_path=CUSTOM_EXPERTS_PATH, ) as (server_endpoint, _): expert0 =", "in (1, 4): batch = torch.randn(batch_size, hid_dim) output0 = expert0(batch)", "* hid_dim), ) output0 = expert0(*batch) output1 = expert1(*batch) loss", "import RemoteExpert from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\",", "3 * hid_dim), ) output0 = expert0(*batch) output1 = expert1(*batch)", "= output1.sum() loss.backward() @pytest.mark.forked def test_multihead_expert(hid_dim=16): with background_server( expert_cls=\"multihead\", num_experts=2,", "torch.randn(batch_size, hid_dim), torch.randn(batch_size, 2 * hid_dim), torch.randn(batch_size, 3 * hid_dim),", "RemoteExpert(\"expert.0\", server_endpoint) expert1 = RemoteExpert(\"expert.1\", server_endpoint) for batch_size in (1,", "output0 = expert0(*batch) output1 = expert1(*batch) loss = output0.sum() loss.backward()", "hid_dim) output0 = expert0(batch) output1 = expert1(batch) loss = output0.sum()", "torch from hivemind import RemoteExpert from hivemind.moe.server import background_server CUSTOM_EXPERTS_PATH", "CUSTOM_EXPERTS_PATH = os.path.join(os.path.dirname(__file__), \"test_utils\", \"custom_networks.py\") @pytest.mark.forked def test_custom_expert(hid_dim=16): with background_server(" ]
[ "ar = (spread_ho/spread_oc)*100 return ar ar = AR(klines) print(\"策略开始启动\") while", "klines = api.get_kline_serial(SYMBOL, 60*60*24, N) quote = api.get_quote(SYMBOL) target_pos =", "< 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50 < ar", "SYMBOL = \"SHFE.au1912\" N = 15 api = TqApi() klines", "策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk", "注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqAccount, TqApi, TargetPosTask", "def AR(kline1): spread_ho = sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc = sum(kline1.open[:-1]", "0: # 如果ar大于110并且小于150,开多仓 if 110 < ar < 150: print(\"价值动量超过110,小于150,做多\")", "https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqAccount, TqApi,", "kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if spread_oc == 0: spread_oc =", "''' 价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 '''", "spread_oc = quote.price_tick ar = (spread_ho/spread_oc)*100 return ar ar =", "ar < 90) or (position.pos_short > 0 and ar >", "= sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] - kline1.low[:-1]) #", "target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0 and ar <", "= api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho = sum(kline1.high[:-1] -", "# 如果ar大于50,小于90,开空仓 elif 50 < ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100)", "api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines) print(\"价格动量是:\",", "coding: utf-8 -*- __author__ = \"Ringo\" ''' 价格动量 策略 (难度:初级)", "60*60*24, N) quote = api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL) position", "= (spread_ho/spread_oc)*100 return ar ar = AR(klines) print(\"策略开始启动\") while True:", "# 如果ar大于110并且小于150,开多仓 if 110 < ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100)", "生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines) print(\"价格动量是:\", ar) #", "position.pos_long == 0 and position.pos_short == 0: # 如果ar大于110并且小于150,开多仓 if", "import TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N", "spread_ho = sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] - kline1.low[:-1])", "参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqAccount,", "= TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1):", "0 and position.pos_short == 0: # 如果ar大于110并且小于150,开多仓 if 110 <", "TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N =", "api.is_changing(quote, \"last_price\"): # 开仓策略 if position.pos_long == 0 and position.pos_short", "print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0 and ar", "from tqsdk import TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL =", "N = 15 api = TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24,", "(position.pos_long > 0 and ar < 90) or (position.pos_short >", "= \"SHFE.au1912\" N = 15 api = TqApi() klines =", "= \"Ringo\" ''' 价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范,", "ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50 <", "elif (position.pos_long > 0 and ar < 90) or (position.pos_short", "- kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值", "spread_oc = sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if spread_oc", "# -*- coding: utf-8 -*- __author__ = \"Ringo\" ''' 价格动量", "(spread_ho/spread_oc)*100 return ar ar = AR(klines) print(\"策略开始启动\") while True: api.wait_update()", "(难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import", "每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): # 开仓策略 if position.pos_long == 0", "TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24, N) quote = api.get_quote(SYMBOL) target_pos", "spread_oc 为0时,设置为最小价格跳动值 if spread_oc == 0: spread_oc = quote.price_tick ar", "该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqAccount, TqApi, TargetPosTask #", "and ar < 90) or (position.pos_short > 0 and ar", "return ar ar = AR(klines) print(\"策略开始启动\") while True: api.wait_update() #", "50 < ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif", "api = TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24, N) quote =", "N) quote = api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL) position =", "if api.is_changing(quote, \"last_price\"): # 开仓策略 if position.pos_long == 0 and", "sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if spread_oc == 0:", "= api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) #", "TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N = 15", "ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): # 开仓策略 if position.pos_long", "elif 50 < ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损", "print(\"策略开始启动\") while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar", "if 110 < ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓", "TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N = 15 api", "# 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0 and ar < 90)", "#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = \"Ringo\"", "-*- __author__ = \"Ringo\" ''' 价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/", "target_pos = TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def", "-*- coding: utf-8 -*- __author__ = \"Ringo\" ''' 价格动量 策略", "\"Ringo\" ''' 价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改", "quote.price_tick ar = (spread_ho/spread_oc)*100 return ar ar = AR(klines) print(\"策略开始启动\")", "AR(klines) print(\"策略开始启动\") while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"):", "print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): # 开仓策略 if", "__author__ = \"Ringo\" ''' 价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注:", "价格动量 策略 (难度:初级) 参考: https://www.shinnytech.com/blog/momentum-strategy/ 注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改 ''' from", "TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho", "quote = api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL)", "and position.pos_short == 0: # 如果ar大于110并且小于150,开多仓 if 110 < ar", "110 < ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif", "kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if", "sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc", "= api.get_kline_serial(SYMBOL, 60*60*24, N) quote = api.get_quote(SYMBOL) target_pos = TargetPosTask(api,", "SYMBOL) position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho =", "''' from tqsdk import TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL", "== 0: # 如果ar大于110并且小于150,开多仓 if 110 < ar < 150:", "# 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N = 15 api =", "python # -*- coding: utf-8 -*- __author__ = \"Ringo\" '''", "如果ar大于110并且小于150,开多仓 if 110 < ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) #", "print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50 < ar < 90:", "if position.pos_long == 0 and position.pos_short == 0: # 如果ar大于110并且小于150,开多仓", "== 0 and position.pos_short == 0: # 如果ar大于110并且小于150,开多仓 if 110", "if spread_oc == 0: spread_oc = quote.price_tick ar = (spread_ho/spread_oc)*100", "= AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): #", "> 0 and ar < 90) or (position.pos_short > 0", "150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50 < ar <", "# 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines) print(\"价格动量是:\", ar)", "== 0: spread_oc = quote.price_tick ar = (spread_ho/spread_oc)*100 return ar", "api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar", "\"last_price\"): # 开仓策略 if position.pos_long == 0 and position.pos_short ==", "< 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0", "90) or (position.pos_short > 0 and ar > 110): print(\"止损平仓\")", "if api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断", "api.get_kline_serial(SYMBOL, 60*60*24, N) quote = api.get_quote(SYMBOL) target_pos = TargetPosTask(api, SYMBOL)", "\"SHFE.au1912\" N = 15 api = TqApi() klines = api.get_kline_serial(SYMBOL,", "= TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24, N) quote = api.get_quote(SYMBOL)", "< ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long", "90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0 and", "编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho = sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc =", "0: spread_oc = quote.price_tick ar = (spread_ho/spread_oc)*100 return ar ar", "设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\" N = 15 api = TqApi()", "True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines)", "为0时,设置为最小价格跳动值 if spread_oc == 0: spread_oc = quote.price_tick ar =", "开仓策略 if position.pos_long == 0 and position.pos_short == 0: #", "ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) # 止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long >", "# spread_oc 为0时,设置为最小价格跳动值 if spread_oc == 0: spread_oc = quote.price_tick", "api.is_changing(klines.iloc[-1], \"datetime\"): ar = AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if", "止损策略,多头下当前ar值小于90则平仓止损,空头下当前ar值大于110则平仓止损 elif (position.pos_long > 0 and ar < 90) or", "\"datetime\"): ar = AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote,", "< 90) or (position.pos_short > 0 and ar > 110):", "15 api = TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24, N) quote", "# 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho = sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc", "# 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): # 开仓策略 if position.pos_long ==", "ar ar = AR(klines) print(\"策略开始启动\") while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar", "spread_oc == 0: spread_oc = quote.price_tick ar = (spread_ho/spread_oc)*100 return", "= 15 api = TqApi() klines = api.get_kline_serial(SYMBOL, 60*60*24, N)", "= AR(klines) print(\"策略开始启动\") while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1],", "position.pos_short == 0: # 如果ar大于110并且小于150,开多仓 if 110 < ar <", "0 and ar < 90) or (position.pos_short > 0 and", "ar = AR(klines) print(\"策略开始启动\") while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if", "AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"): # 开仓策略", "ar = AR(klines) print(\"价格动量是:\", ar) # 每次最新价发生变动时,重新进行判断 if api.is_changing(quote, \"last_price\"):", "实盘时请根据自己的策略/经验进行修改 ''' from tqsdk import TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量", "position = api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho = sum(kline1.high[:-1]", "如果ar大于50,小于90,开空仓 elif 50 < ar < 90: print(\"价值动量大于50,小于90,做空\") target_pos.set_target_volume(-100) #", "tqsdk import TqAccount, TqApi, TargetPosTask # 设置指定合约,获取N条K线计算价格动量 SYMBOL = \"SHFE.au1912\"", "AR(kline1): spread_ho = sum(kline1.high[:-1] - kline1.open[:-1]) spread_oc = sum(kline1.open[:-1] -", "- kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if spread_oc == 0: spread_oc", "while True: api.wait_update() # 生成新K线时,重新计算价格动量值ar if api.is_changing(klines.iloc[-1], \"datetime\"): ar =", "utf-8 -*- __author__ = \"Ringo\" ''' 价格动量 策略 (难度:初级) 参考:", "target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50 < ar < 90: print(\"价值动量大于50,小于90,做空\")", "< ar < 150: print(\"价值动量超过110,小于150,做多\") target_pos.set_target_volume(100) # 如果ar大于50,小于90,开空仓 elif 50", "= quote.price_tick ar = (spread_ho/spread_oc)*100 return ar ar = AR(klines)", "# 开仓策略 if position.pos_long == 0 and position.pos_short == 0:", "api.get_position(SYMBOL) # 编写价格动量函数AR,以前N-1日K线计算价格动量ar def AR(kline1): spread_ho = sum(kline1.high[:-1] - kline1.open[:-1])", "or (position.pos_short > 0 and ar > 110): print(\"止损平仓\") target_pos.set_target_volume(0)", "= sum(kline1.open[:-1] - kline1.low[:-1]) # spread_oc 为0时,设置为最小价格跳动值 if spread_oc ==" ]
[ "comparison) best_result: NumPy array result that minimizes mean absolute error", "= cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left,", "& preserve_paper arguments. Mean absolute error (MAE) is computed for", "return transfer def auto_color_transfer(source, target): \"\"\"Pick color_transfer result truest to", "comparison = _bool_matrix_border(comparison) return best_result, comparison def chi2_distance(hist_a, hist_b, eps=1e-10):", "aMean, aStd, bMean, bStd def _min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform", "Images\" paper by <NAME> al., 2001. Parameters: ------- source: NumPy", "aStdSrc, bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar,", "clip: Should components of L*a*b* image be scaled by np.clip", "/ 2), 190) top_false_loc = (5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper',", "190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255),", "arr: NumPy array to be scaled to [new_min, new_max] range", "RGB color # space, being sure to utilize the 8-bit", "cv2.calcHist([hsv_candidate], [0, 1, 2], None, [8, 8, 8], [0, 256,", "image brightness truer to the input. Scaling will adjust image", "text for clip arg options to top border top_title_loc =", "(aStdSrc / aStdTar) * a b = (bStdSrc / bStdTar)", "target image using the mean and standard deviations of the", "intensities to [0, 255] if they fall # outside this", "the mean and standard deviation of each channel (l, a,", "deviations using reciprocal of paper proposed factor l = (lStdSrc", "------- arr: NumPy array to be scaled to [new_min, new_max]", "2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2)", "source: NumPy array OpenCV image in BGR color space (the", "# import the necessary packages import numpy as np import", "compute color statistics for the source and target images (lMeanSrc,", "brightness truer to the input. Scaling will adjust image brightness", "mn < new_range[0] or mx > new_range[1]: # perform min-max", "(mx - mn) + new_range[0] else: # return array if", "combinations of color_transfer options \"\"\" # get mean HSV stats", "L*a*b* components will scaled using the reciprocal of the scaling", "= cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1, 2], None,", "'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True',", "from the source to the target image using the mean", "aesthetically pleasing results. If False then L*a*b* components will scaled", "to utilize the 8-bit unsigned integer data # type transfer", "if already in range scaled = arr return scaled def", "mean HSV stats from candidate image for comparison hsv_candidate =", "size border_size = 200 # put black border on top", "/ aStdSrc) * a b = (bStdTar / bStdSrc) *", "that can be caused by clipping. preserve_paper: Should color transfer", "BGR color space (the source image) target: NumPy array OpenCV", "image_stats(target) # subtract the means from the target image (l,", "fall # outside this range l = _scale_array(l, clip=clip) a", "well as a montage of all candidate results. Parameters: -------", "0]), min([arr.max(), 255])] Returns: ------- NumPy array that has been", "90) # add text for preserve paper arg options to", "the color statistics return lMean, lStd, aMean, aStd, bMean, bStd", "OpenCV image in BGR color space (the target image) clip:", "aStd) = (a.mean(), a.std()) (bMean, bStd) = (b.mean(), b.std()) #", "comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border annotations showing values", "0.5 * np.sum(((hist_a - hist_b) ** 2) / (hist_a +", "= (aStdTar / aStdSrc) * a b = (bStdTar /", "as well as a montage of all candidate results. Parameters:", "# space, being sure to utilize the 8-bit unsigned integer", "= (lStdTar / lStdSrc) * l a = (aStdTar /", "calc chi square dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) # propose", "image in BGR color space (the target image) Returns: -------", "np.clip(arr, 0, 255) else: scale_range = (max([arr.min(), 0]), min([arr.max(), 255]))", "to work well as border size border_size = 200 #", "in the source mean l += lMeanSrc a += aMeanSrc", "NumPy array that has been scaled to be in [0,", "Parameters: ------- source: NumPy array OpenCV image in BGR color", "easily compare the different results of the auto_color_transfer \"\"\" #", "scale by the standard deviations using paper proposed factor l", "proposed factor l = (lStdTar / lStdSrc) * l a", "compared to source image in HSV color space comparison: NumPy", "dtype='uint8').reshape(border_size, w) left = np.zeros((h + border_size) * border_size, dtype='uint8').reshape(h", "= candidate[:] candidates.append(candidate) # build 2 by 2 image matrix", "+ new_range[0] else: # return array if already in range", "\"\"\" # get mean HSV stats from source image for", "respectively \"\"\" # compute the mean and standard deviation of", "else: scale_range = (max([arr.min(), 0]), min([arr.max(), 255])) scaled = _min_max_scale(arr,", "smallest mae if chi2_dist < best_dist: best_result = candidate[:] candidates.append(candidate)", "a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the color", "* b else: # scale by the standard deviations using", "numpy as np import cv2 import imutils def color_transfer(source, target,", "paper proposed factor l = (lStdTar / lStdSrc) * l", "BGR color space (the target image) clip: Should components of", "source mean l += lMeanSrc a += aMeanSrc b +=", "of each result and the source image. The best_result that", "hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0, 1, 2],", "# add text for preserve paper arg options to left", "to the target image using the mean and standard deviations", "2), 190) top_false_loc = (5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc,", "255] range \"\"\" if clip: scaled = np.clip(arr, 0, 255)", "floats to be 32-bit, so use that instead of 64-bit)", "(lStdSrc / lStdTar) * l a = (aStdSrc / aStdTar)", "hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1, 2], None, [8, 8, 8],", "2], None, [8, 8, 8], [0, 256, 0, 256, 0,", "(l, a, b) = cv2.split(image) (lMean, lStd) = (l.mean(), l.std())", "array result that minimizes mean absolute error between compared to", "scale_range = (max([arr.min(), 0]), min([arr.max(), 255])) scaled = _min_max_scale(arr, new_range=scale_range)", "transfer: NumPy array OpenCV image (w, h, 3) NumPy array", "as border size border_size = 200 # put black border", "to [0, 255] range clip: should array be scaled by", "* border_size, dtype='uint8').reshape(border_size, w) left = np.zeros((h + border_size) *", "for each output comparison = _bool_matrix_border(comparison) return best_result, comparison def", "paper by <NAME> al., 2001. Parameters: ------- source: NumPy array", "from options of this iteration candidate = color_transfer(source, target, clip,", "mx > new_range[1]: # perform min-max scaling scaled = (new_range[1]", "options for toggling color transfer bools = [True, False] candidates", "256]) # iterate through all 4 options for toggling color", "cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the color transferred image return transfer", "that minimizes the MAE is returned as well as a", "and the source image. The best_result that minimizes the MAE", "(border_size, 75) top_true_loc = (border_size, 190) top_false_loc = (int(border_size +", "/ bStdTar) * b # add in the source mean", "toggling color transfer bools = [True, False] candidates = []", "top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc,", "range scaled = arr return scaled def _scale_array(arr, clip=True): \"\"\"", "iterate through all 4 options for toggling color transfer bools", "scaled to range [max([arr.min(), 0]), min([arr.max(), 255])] Returns: ------- NumPy", "-= lMeanTar a -= aMeanTar b -= bMeanTar if preserve_paper:", "(bStdSrc / bStdTar) * b # add in the source", "= (aStdSrc / aStdTar) * a b = (bStdSrc /", "255, 255), 2) # rotate 90 degrees for writing text", "or scaling. Parameters: ------- arr: array to be trimmed to", "each output comparison = _bool_matrix_border(comparison) return best_result, comparison def chi2_distance(hist_a,", "* a b = (bStdSrc / bStdTar) * b #", "well as border size border_size = 200 # put black", "scaling factor proposed in the paper. This method seems to", "2, (255, 255, 255), 2) # rotate 90 degrees for", "scaled to be in [0, 255] range \"\"\" if clip:", "if False then input array will be min-max scaled to", "the \"Color Transfer between Images\" paper by <NAME> al., 2001.", "orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def image_stats(image): \"\"\"", "array Returns: ------- NumPy array that has been scaled to", "= 200 # put black border on top and left", "preserve paper arg options to left border top_title_loc = (5,", "Applies color_transfer with all possible combinations of the clip &", "combinations of the clip & preserve_paper arguments. Mean absolute error", "components will scaled using the reciprocal of the scaling factor", "all candidate results. Parameters: ------- source: NumPy array OpenCV image", "in bools: # create candidate image from options of this", "def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting for comparison of color_transfer options", "the channels together and convert back to the RGB color", "(int(border_size + w / 2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX,", "cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0, 1, 2], None, [8, 8,", "-= aMeanTar b -= bMeanTar if preserve_paper: # scale by", "adjust image brightness to avoid washed out portions in the", "------- transfer: NumPy array OpenCV image (w, h, 3) NumPy", "new smallest mae if chi2_dist < best_dist: best_result = candidate[:]", "and max mn = arr.min() mx = arr.max() # check", "clipping or scaling. Parameters: ------- arr: array to be trimmed", "target image (l, a, b) = cv2.split(target) l -= lMeanTar", "return lMean, lStd, aMean, aStd, bMean, bStd def _min_max_scale(arr, new_range=(0,", "of 64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\")", "L*ab* color space, being # sure to utilizing the floating", "to a NumPy array Parameters: ------- arr: NumPy array to", "the target image using the mean and standard deviations of", "clip arg options to top border top_title_loc = (border_size, 75)", "from candidate image for comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand", "possible combinations of the clip & preserve_paper arguments. Mean absolute", "OpenCV image in L*a*b* color space Returns: ------- Tuple of", "(lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target) # subtract", "(w, h, 3) NumPy array (uint8) \"\"\" # convert the", "image be scaled by np.clip before converting back to BGR", "to [0, 255] if they fall # outside this range", "get mean HSV stats from candidate image for comparison hsv_candidate", "will scaled using the reciprocal of the scaling factor proposed", "Returns: ------- NumPy array that has been scaled to be", "Clipping will keep target image brightness truer to the input.", "clip=clip) b = _scale_array(b, clip=clip) # merge the channels together", "HSV color space comparison: NumPy array image showing the results", "candidates for comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border", "to source image color Applies color_transfer with all possible combinations", "not always produce aesthetically pleasing results. If False then L*a*b*", "[0, 1, 2], None, [8, 8, 8], [0, 256, 0,", "# add text for clip arg options to top border", "for the L*, a*, and b* channels, respectively \"\"\" #", "= (new_range[1] - new_range[0]) * (arr - mn) / (mx", "images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar,", "clip=clip) a = _scale_array(a, clip=clip) b = _scale_array(b, clip=clip) #", "200 seems to work well as border size border_size =", "+ int(h / 2), 190) top_false_loc = (5, 190) cv2.putText(bordered_comparison_image,", "[0, 255] if they fall # outside this range l", "color_transfer with all possible combinations of the clip & preserve_paper", "has been scaled to be in [0, 255] range \"\"\"", "# return array if already in range scaled = arr", "text to left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) # add", "= cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the color transferred image return", "data type (note: OpenCV # expects floats to be 32-bit,", "a b = (bStdSrc / bStdTar) * b # add", "top = np.zeros(w * border_size, dtype='uint8').reshape(border_size, w) left = np.zeros((h", "factor l = (lStdSrc / lStdTar) * l a =", "channels of each result and the source image. The best_result", "already in range scaled = arr return scaled def _scale_array(arr,", "through all 4 options for toggling color transfer bools =", "# get mean HSV stats from source image for comparison", "range of transformed array Returns: ------- NumPy array that has", "space, being sure to utilize the 8-bit unsigned integer data", "new_range[0]) * (arr - mn) / (mx - mn) +", "2, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2,", "(255, 255, 255), 2) # rotate 90 degrees for writing", "new_range[0] or mx > new_range[1]: # perform min-max scaling scaled", "cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) #", "auto_color_transfer(source, target): \"\"\"Pick color_transfer result truest to source image color", "cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1, 2], None, [8, 8,", "truest result if found new smallest mae if chi2_dist <", "border top_title_loc = (5, 75) top_true_loc = (5 + int(h", "2) / (hist_a + hist_b + eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply", "a.std()) (bMean, bStd) = (b.mean(), b.std()) # return the color", "< new_range[0] or mx > new_range[1]: # perform min-max scaling", "based on to the \"Color Transfer between Images\" paper by", "image in BGR color space (the comparison image produced in", "standard deviations using reciprocal of paper proposed factor l =", "image in correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image", "/ aStdTar) * a b = (bStdSrc / bStdTar) *", "return best_result, comparison def chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5 *", "b) = cv2.split(target) l -= lMeanTar a -= aMeanTar b", "= (border_size, 75) top_true_loc = (border_size, 190) top_false_loc = (int(border_size", "chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new truest result if found new", "to be in [0, 255] range \"\"\" if clip: scaled", "[new_min, new_max] range new_range: tuple of form (min, max) specifying", "\"\"\" # compute the mean and standard deviation of each", "being sure to utilize the 8-bit unsigned integer data #", "------- comparison: NumPy array OpenCV image in BGR color space", "# subtract the means from the target image (l, a,", "merge the channels together and convert back to the RGB", "+ w / 2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3,", "mn = arr.min() mx = arr.max() # check if scaling", "\"\"\" # 200 seems to work well as border size", "(the comparison image produced in auto_color_transfer) Returns: ------- comparison: NumPy", "8-bit unsigned integer data # type transfer = cv2.merge([l, a,", "border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) # add text for preserve", "def color_transfer(source, target, clip=True, preserve_paper=True): \"\"\" Transfers the color distribution", "the source image. The best_result that minimizes the MAE is", "by the standard deviations using paper proposed factor l =", "eps=1e-10): return 0.5 * np.sum(((hist_a - hist_b) ** 2) /", "top_true_loc = (5 + int(h / 2), 190) top_false_loc =", "compute the mean and standard deviation of each channel (l,", "top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image =", "# perform min-max scaling scaled = (new_range[1] - new_range[0]) *", "color transfer that can be caused by clipping. preserve_paper: Should", "= (bStdSrc / bStdTar) * b # add in the", "paper arg options to left border top_title_loc = (5, 75)", "distribution from the source to the target image using the", "border on top and left of input image h, w", "channels together and convert back to the RGB color #", "cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics for the source and", "clip=clip) # merge the channels together and convert back to", "cv2.merge([l, a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the", "left = np.zeros((h + border_size) * border_size, dtype='uint8').reshape(h + border_size,", "Parameters: ------- arr: array to be trimmed to [0, 255]", "2) # rotate -90 degrees to return image in correct", "of all candidates for comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) #", "np import cv2 import imutils def color_transfer(source, target, clip=True, preserve_paper=True):", "array OpenCV image (w, h, 3) NumPy array (uint8) \"\"\"", "standard deviations for the L*, a*, and b* channels, respectively", "min-max scaled appropriately. Clipping will keep target image brightness truer", "# check if scaling needs to be done to be", "for the HSV channels of each result and the source", "to the input. Scaling will adjust image brightness to avoid", "l a = (aStdTar / aStdSrc) * a b =", "the 8-bit unsigned integer data # type transfer = cv2.merge([l,", "image in HSV color space comparison: NumPy array image showing", "appropriately. Clipping will keep target image brightness truer to the", "This method seems to produce more consistently aesthetically pleasing results", "clip=True): \"\"\" Trim NumPy array values to be in [0,", "be scaled by np.clip before converting back to BGR color", "best_dist: best_result = candidate[:] candidates.append(candidate) # build 2 by 2", "comparison image produced in auto_color_transfer) Returns: ------- comparison: NumPy array", "import numpy as np import cv2 import imutils def color_transfer(source,", "the RGB color # space, being sure to utilize the", "MAE is returned as well as a montage of all", "# iterate through all 4 options for toggling color transfer", "all combinations of color_transfer options \"\"\" # get mean HSV", "[0, 255] range \"\"\" if clip: scaled = np.clip(arr, 0,", "space (the comparison image produced in auto_color_transfer) Returns: ------- comparison:", "to be in [new_range[0], new_range[1]] range \"\"\" # get array's", "arr.max() # check if scaling needs to be done to", "(MAE) is computed for the HSV channels of each result", "top_title_loc = (border_size, 75) top_true_loc = (border_size, 190) top_false_loc =", "False then input array will be min-max scaled to range", "comparison: NumPy array OpenCV image in BGR color space with", "return the color transferred image return transfer def auto_color_transfer(source, target):", "to [new_min, new_max] range new_range: tuple of form (min, max)", "mn) / (mx - mn) + new_range[0] else: # return", "lStd, aMean, aStd, bMean, bStd def _min_max_scale(arr, new_range=(0, 255)): \"\"\"", "target images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source)", "(lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar, lStdTar,", "return bordered_comparison_image def image_stats(image): \"\"\" Parameters: ------- image: NumPy array", "# compute color statistics for the source and target images", "table formatting for comparison of color_transfer options Parameters: ------- target:", "L*a*b* color space Returns: ------- Tuple of mean and standard", "> new_range[1]: # perform min-max scaling scaled = (new_range[1] -", "the results of all combinations of color_transfer options \"\"\" #", "= (int(border_size + w / 2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc,", "def _min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform min-max scaling to a", "be in [0, 255] range with option of clipping or", "all 4 options for toggling color transfer bools = [True,", "2 image matrix of all candidates for comparison comparison =", "dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new truest result", "al., 2001. Parameters: ------- source: NumPy array OpenCV image in", "* l a = (aStdSrc / aStdTar) * a b", "the source and target images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc,", "= (lStdSrc / lStdTar) * l a = (aStdSrc /", "top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) # rotate -90", "a NumPy array Parameters: ------- arr: NumPy array to be", "aStdSrc) * a b = (bStdTar / bStdSrc) * b", "should array be scaled by np.clip? if False then input", "import imutils def color_transfer(source, target, clip=True, preserve_paper=True): \"\"\" Transfers the", "cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics for", "/ lStdTar) * l a = (aStdSrc / aStdTar) *", "for comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border annotations", "integer data # type transfer = cv2.merge([l, a, b]) transfer", "= cv2.merge([l, a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return", "border size border_size = 200 # put black border on", "top border top_title_loc = (border_size, 75) top_true_loc = (border_size, 190)", "hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1, 2],", "left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) # add text for", "comparison_image.shape[:2] top = np.zeros(w * border_size, dtype='uint8').reshape(border_size, w) left =", "in HSV color space comparison: NumPy array image showing the", "that minimizes mean absolute error between compared to source image", "Scaling will adjust image brightness to avoid washed out portions", "chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5 * np.sum(((hist_a - hist_b) **", "------- target: NumPy array OpenCV image in BGR color space", "and target images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) =", "imutils.rotate_bound(bordered_comparison_image, 90) # add text for preserve paper arg options", "255] range clip: should array be scaled by np.clip? if", "------- NumPy array that has been scaled to be in", "image h, w = comparison_image.shape[:2] top = np.zeros(w * border_size,", "mn) + new_range[0] else: # return array if already in", "array OpenCV image in BGR color space (the source image)", "a, b) = cv2.split(target) l -= lMeanTar a -= aMeanTar", "computed for the HSV channels of each result and the", "space (the source image) target: NumPy array OpenCV image in", "color space comparison: NumPy array image showing the results of", "max) specifying range of transformed array Returns: ------- NumPy array", "be scaled by np.clip? if False then input array will", "preserve_paper arguments. Mean absolute error (MAE) is computed for the", "= (b.mean(), b.std()) # return the color statistics return lMean,", "values to be in [0, 255] range with option of", "using paper proposed factor l = (lStdTar / lStdSrc) *", "imutils def color_transfer(source, target, clip=True, preserve_paper=True): \"\"\" Transfers the color", "be caused by clipping. preserve_paper: Should color transfer strictly follow", "(aStdTar / aStdSrc) * a b = (bStdTar / bStdSrc)", "# merge the channels together and convert back to the", "= cv2.calcHist([hsv_source], [0, 1, 2], None, [8, 8, 8], [0,", "# rotate -90 degrees to return image in correct orientation", "in [0, 255] range with option of clipping or scaling.", "import the necessary packages import numpy as np import cv2", "from the target image (l, a, b) = cv2.split(target) l", "in BGR color space (the target image) Returns: ------- tuple:", "be scaled to [new_min, new_max] range new_range: tuple of form", "the resulting color transfer that can be caused by clipping.", "new_range=(0, 255)): \"\"\" Perform min-max scaling to a NumPy array", "b # add in the source mean l += lMeanSrc", "to easily compare the different results of the auto_color_transfer \"\"\"", "results Returns: ------- transfer: NumPy array OpenCV image (w, h,", "be 32-bit, so use that instead of 64-bit) source =", "image showing the results of all combinations of color_transfer options", "by the standard deviations using reciprocal of paper proposed factor", "the different results of the auto_color_transfer \"\"\" # 200 seems", "border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image", "= cv2.calcHist([hsv_candidate], [0, 1, 2], None, [8, 8, 8], [0,", "be trimmed to [0, 255] range clip: should array be", "convert the images from the RGB to L*ab* color space,", "propose new truest result if found new smallest mae if", "def _scale_array(arr, clip=True): \"\"\" Trim NumPy array values to be", "pleasing results. If False then L*a*b* components will scaled using", "75) top_true_loc = (5 + int(h / 2), 190) top_false_loc", "scaling. Parameters: ------- arr: array to be trimmed to [0,", "image from options of this iteration candidate = color_transfer(source, target,", "in correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def", "a = _scale_array(a, clip=clip) b = _scale_array(b, clip=clip) # merge", "------- tuple: (best_result, comparison) best_result: NumPy array result that minimizes", "\"Color Transfer between Images\" paper by <NAME> al., 2001. Parameters:", "[0, 256, 0, 256, 0, 256]) # calc chi square", "NumPy array that has been scaled to be in [new_range[0],", "range \"\"\" if clip: scaled = np.clip(arr, 0, 255) else:", "preserve_paper: # scale by the standard deviations using paper proposed", "array's current min and max mn = arr.min() mx =", "been scaled to be in [0, 255] range \"\"\" if", "= imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def image_stats(image): \"\"\" Parameters: -------", "results. If False then L*a*b* components will scaled using the", "color space? If False then components will be min-max scaled", "if preserve_paper: # scale by the standard deviations using paper", "pixel intensities to [0, 255] if they fall # outside", "reciprocal of the scaling factor proposed in the paper. This", "candidate results. Parameters: ------- source: NumPy array OpenCV image in", "cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1, 2], None, [8,", "scaled by np.clip? if False then input array will be", "in BGR color space (the source image) target: NumPy array", "in bools: for preserve_paper in bools: # create candidate image", "input array will be min-max scaled to range [max([arr.min(), 0]),", "auto_color_transfer) Returns: ------- comparison: NumPy array OpenCV image in BGR", "+= lMeanSrc a += aMeanSrc b += bMeanSrc # clip/scale", "= cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0, 1, 2], None,", "statistics for the source and target images (lMeanSrc, lStdSrc, aMeanSrc,", "255, 255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255,", "= cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color", "array OpenCV image in BGR color space (the target image)", "a = (aStdTar / aStdSrc) * a b = (bStdTar", "Should color transfer strictly follow methodology laid out in original", "------- arr: array to be trimmed to [0, 255] range", "to the \"Color Transfer between Images\" paper by <NAME> al.,", "deviations for the L*, a*, and b* channels, respectively \"\"\"", "image in BGR color space (the source image) target: NumPy", "scaled = (new_range[1] - new_range[0]) * (arr - mn) /", "NumPy array result that minimizes mean absolute error between compared", "and standard deviations for the L*, a*, and b* channels,", "lMean, lStd, aMean, aStd, bMean, bStd def _min_max_scale(arr, new_range=(0, 255)):", "mean and standard deviations of the L*a*b* color space. This", "formatting for comparison of color_transfer options Parameters: ------- target: NumPy", "standard deviations of the L*a*b* color space. This implementation is", "OpenCV image in BGR color space (the target image) Returns:", "of all combinations of color_transfer options \"\"\" # get mean", "for preserve_paper in bools: # create candidate image from options", "\"\"\" # convert the images from the RGB to L*ab*", "False] candidates = [] best_result = None best_dist = float('inf')", "cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image))", "to BGR color space? If False then components will be", "in the paper. This method seems to produce more consistently", "of all candidate results. Parameters: ------- source: NumPy array OpenCV", "(the target image) clip: Should components of L*a*b* image be", "space comparison: NumPy array image showing the results of all", "to utilizing the floating point data type (note: OpenCV #", "in new_range if mn < new_range[0] or mx > new_range[1]:", "200 # put black border on top and left of", "minimizes the MAE is returned as well as a montage", "190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)", "source and target images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc)", "is computed for the HSV channels of each result and", "of each channel (l, a, b) = cv2.split(image) (lMean, lStd)", "2001. Parameters: ------- source: NumPy array OpenCV image in BGR", "cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) # rotate 90 degrees", "comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0, 1,", "out in original paper? The method does not always produce", "= color_transfer(source, target, clip, preserve_paper) # get mean HSV stats", "Returns: ------- tuple: (best_result, comparison) best_result: NumPy array result that", "min-max scaled to range [max([arr.min(), 0]), min([arr.max(), 255])] Returns: -------", "from source image for comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src", "np.zeros(w * border_size, dtype='uint8').reshape(border_size, w) left = np.zeros((h + border_size)", "False then L*a*b* components will scaled using the reciprocal of", "arg options to top border top_title_loc = (border_size, 75) top_true_loc", "array that has been scaled to be in [new_range[0], new_range[1]]", "specifying range of transformed array Returns: ------- NumPy array that", "the L*a*b* color space. This implementation is (loosely) based on", "else: # scale by the standard deviations using reciprocal of", "candidate image from options of this iteration candidate = color_transfer(source,", "options of this iteration candidate = color_transfer(source, target, clip, preserve_paper)", "then L*a*b* components will scaled using the reciprocal of the", "'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image,", "scaling scaled = (new_range[1] - new_range[0]) * (arr - mn)", "absolute error (MAE) is computed for the HSV channels of", "range with option of clipping or scaling. Parameters: ------- arr:", "aesthetically pleasing results Returns: ------- transfer: NumPy array OpenCV image", "Returns: ------- Tuple of mean and standard deviations for the", "new_range[1]: # perform min-max scaling scaled = (new_range[1] - new_range[0])", "by np.clip before converting back to BGR color space? If", "+= bMeanSrc # clip/scale the pixel intensities to [0, 255]", "NumPy array OpenCV image in BGR color space (the comparison", "np.hstack((left, bordered_comparison_image)) # add text for clip arg options to", "current min and max mn = arr.min() mx = arr.max()", "cv2 import imutils def color_transfer(source, target, clip=True, preserve_paper=True): \"\"\" Transfers", "import cv2 import imutils def color_transfer(source, target, clip=True, preserve_paper=True): \"\"\"", "scaled to be in [new_range[0], new_range[1]] range \"\"\" # get", "space? If False then components will be min-max scaled appropriately.", "clip=True, preserve_paper=True): \"\"\" Transfers the color distribution from the source", "a += aMeanSrc b += bMeanSrc # clip/scale the pixel", "(255, 255, 255), 2) # rotate -90 degrees to return", "= cv2.split(image) (lMean, lStd) = (l.mean(), l.std()) (aMean, aStd) =", "trimmed to [0, 255] range clip: should array be scaled", "= cv2.split(target) l -= lMeanTar a -= aMeanTar b -=", "image for comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source],", "(a.mean(), a.std()) (bMean, bStd) = (b.mean(), b.std()) # return the", "by np.clip? if False then input array will be min-max", "comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0, 1,", "be done to be in new_range if mn < new_range[0]", "the necessary packages import numpy as np import cv2 import", "mean HSV stats from source image for comparison hsv_source =", "work well as border size border_size = 200 # put", "so use that instead of 64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\")", "to left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) # add text", "def image_stats(image): \"\"\" Parameters: ------- image: NumPy array OpenCV image", "range \"\"\" # get array's current min and max mn", "minimizes mean absolute error between compared to source image in", "Returns: ------- comparison: NumPy array OpenCV image in BGR color", "mx = arr.max() # check if scaling needs to be", "between compared to source image in HSV color space comparison:", "being # sure to utilizing the floating point data type", "return the color statistics return lMean, lStd, aMean, aStd, bMean,", "be min-max scaled appropriately. Clipping will keep target image brightness", "[0, 255] range clip: should array be scaled by np.clip?", "transformed array Returns: ------- NumPy array that has been scaled", "\"\"\" Perform min-max scaling to a NumPy array Parameters: -------", "= float('inf') for clip in bools: for preserve_paper in bools:", "paper proposed factor l = (lStdSrc / lStdTar) * l", "put black border on top and left of input image", "bordered_comparison_image = np.hstack((left, bordered_comparison_image)) # add text for clip arg", "= np.hstack((left, bordered_comparison_image)) # add text for clip arg options", "255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),", "if clip: scaled = np.clip(arr, 0, 255) else: scale_range =", "+ border_size, border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left,", "(bStdTar / bStdSrc) * b else: # scale by the", "color transfer bools = [True, False] candidates = [] best_result", "the source mean l += lMeanSrc a += aMeanSrc b", "arr.min() mx = arr.max() # check if scaling needs to", "------- image: NumPy array OpenCV image in L*a*b* color space", "cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) cv2.putText(bordered_comparison_image,", "different results of the auto_color_transfer \"\"\" # 200 seems to", "L*a*b* image be scaled by np.clip before converting back to", "transfer = cv2.merge([l, a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) #", "components of L*a*b* image be scaled by np.clip before converting", "2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2)", "= (5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255,", "b.std()) # return the color statistics return lMean, lStd, aMean,", "in range scaled = arr return scaled def _scale_array(arr, clip=True):", "auto_color_transfer \"\"\" # 200 seems to work well as border", "_scale_array(l, clip=clip) a = _scale_array(a, clip=clip) b = _scale_array(b, clip=clip)", "then components will be min-max scaled appropriately. Clipping will keep", "source image) target: NumPy array OpenCV image in BGR color", "error (MAE) is computed for the HSV channels of each", "for comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0,", "image (w, h, 3) NumPy array (uint8) \"\"\" # convert", "= [] best_result = None best_dist = float('inf') for clip", "(l, a, b) = cv2.split(target) l -= lMeanTar a -=", "255), 2) # rotate -90 degrees to return image in", "aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target) # subtract the means", "target: NumPy array OpenCV image in BGR color space (the", "factor proposed in the paper. This method seems to produce", "lStdTar) * l a = (aStdSrc / aStdTar) * a", "add in the source mean l += lMeanSrc a +=", "result and the source image. The best_result that minimizes the", "None best_dist = float('inf') for clip in bools: for preserve_paper", "best_result = None best_dist = float('inf') for clip in bools:", "array OpenCV image in BGR color space with borders applied", "color_transfer result truest to source image color Applies color_transfer with", "h, w = comparison_image.shape[:2] top = np.zeros(w * border_size, dtype='uint8').reshape(border_size,", "washed out portions in the resulting color transfer that can", "image_stats(image): \"\"\" Parameters: ------- image: NumPy array OpenCV image in", "# 200 seems to work well as border size border_size", "more consistently aesthetically pleasing results Returns: ------- transfer: NumPy array", "by 2 image matrix of all candidates for comparison comparison", "cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image", "return image in correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return", "float('inf') for clip in bools: for preserve_paper in bools: #", "2, (255, 255, 255), 2) # rotate -90 degrees to", "NumPy array OpenCV image in L*a*b* color space Returns: -------", "that has been scaled to be in [new_range[0], new_range[1]] range", "+ hist_b + eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting for", "can be caused by clipping. preserve_paper: Should color transfer strictly", "top_true_loc = (border_size, 190) top_false_loc = (int(border_size + w /", "to be scaled to [new_min, new_max] range new_range: tuple of", "# rotate 90 degrees for writing text to left border", "color Applies color_transfer with all possible combinations of the clip", "absolute error between compared to source image in HSV color", "b -= bMeanTar if preserve_paper: # scale by the standard", "top_false_loc = (5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3,", "of mean and standard deviations for the L*, a*, and", "space, being # sure to utilizing the floating point data", "cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src = cv2.calcHist([hsv_source], [0, 1, 2], None, [8,", "hist_b + eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting for comparison", "3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2,", "image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target) #", "of transformed array Returns: ------- NumPy array that has been", "preserve_paper: Should color transfer strictly follow methodology laid out in", "iteration candidate = color_transfer(source, target, clip, preserve_paper) # get mean", "data # type transfer = cv2.merge([l, a, b]) transfer =", "a b = (bStdTar / bStdSrc) * b else: #", "color_transfer options Parameters: ------- target: NumPy array OpenCV image in", "borders applied to easily compare the different results of the", "the MAE is returned as well as a montage of", "proposed factor l = (lStdSrc / lStdTar) * l a", "None, [8, 8, 8], [0, 256, 0, 256, 0, 256])", "4 options for toggling color transfer bools = [True, False]", "+ eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting for comparison of", "space Returns: ------- Tuple of mean and standard deviations for", "the auto_color_transfer \"\"\" # 200 seems to work well as", "# get mean HSV stats from candidate image for comparison", "(b.mean(), b.std()) # return the color statistics return lMean, lStd,", "transfer bools = [True, False] candidates = [] best_result =", "if mn < new_range[0] or mx > new_range[1]: # perform", "Trim NumPy array values to be in [0, 255] range", "channels, respectively \"\"\" # compute the mean and standard deviation", "/ lStdSrc) * l a = (aStdTar / aStdSrc) *", "comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image)) # add text for clip", "in BGR color space (the target image) clip: Should components", "source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute", "comparison def chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5 * np.sum(((hist_a -", "w) left = np.zeros((h + border_size) * border_size, dtype='uint8').reshape(h +", "applied to easily compare the different results of the auto_color_transfer", "border_size, dtype='uint8').reshape(border_size, w) left = np.zeros((h + border_size) * border_size,", "* border_size, dtype='uint8').reshape(h + border_size, border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR)", "consistently aesthetically pleasing results Returns: ------- transfer: NumPy array OpenCV", "if scaling needs to be done to be in new_range", "64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") #", "using the mean and standard deviations of the L*a*b* color", "image. The best_result that minimizes the MAE is returned as", "255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255),", "'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) # rotate", "255, 255), 2) # rotate -90 degrees to return image", "for toggling color transfer bools = [True, False] candidates =", "deviations of the L*a*b* color space. This implementation is (loosely)", "in BGR color space with borders applied to easily compare", "transfer def auto_color_transfer(source, target): \"\"\"Pick color_transfer result truest to source", "image color Applies color_transfer with all possible combinations of the", "type (note: OpenCV # expects floats to be 32-bit, so", "OpenCV image in BGR color space (the comparison image produced", "form (min, max) specifying range of transformed array Returns: -------", "array Parameters: ------- arr: NumPy array to be scaled to", "for writing text to left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90)", "Parameters: ------- image: NumPy array OpenCV image in L*a*b* color", "tuple of form (min, max) specifying range of transformed array", "range [max([arr.min(), 0]), min([arr.max(), 255])] Returns: ------- NumPy array that", "left border top_title_loc = (5, 75) top_true_loc = (5 +", "image matrix of all candidates for comparison comparison = np.hstack((np.vstack(candidates[:2]),", "in [new_range[0], new_range[1]] range \"\"\" # get array's current min", "the means from the target image (l, a, b) =", "in [0, 255] range \"\"\" if clip: scaled = np.clip(arr,", "border_size, dtype='uint8').reshape(h + border_size, border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left", "will keep target image brightness truer to the input. Scaling", "degrees to return image in correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image,", "range new_range: tuple of form (min, max) specifying range of", "1, 2], None, [8, 8, 8], [0, 256, 0, 256,", "a -= aMeanTar b -= bMeanTar if preserve_paper: # scale", "the images from the RGB to L*ab* color space, being", "Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True',", "clip/scale the pixel intensities to [0, 255] if they fall", "packages import numpy as np import cv2 import imutils def", "together and convert back to the RGB color # space,", "montage of all candidate results. Parameters: ------- source: NumPy array", "This implementation is (loosely) based on to the \"Color Transfer", "to avoid washed out portions in the resulting color transfer", "color_transfer options \"\"\" # get mean HSV stats from source", "in L*a*b* color space Returns: ------- Tuple of mean and", "array if already in range scaled = arr return scaled", "before converting back to BGR color space? If False then", "scaled def _scale_array(arr, clip=True): \"\"\" Trim NumPy array values to", "candidates.append(candidate) # build 2 by 2 image matrix of all", "error between compared to source image in HSV color space", "option of clipping or scaling. Parameters: ------- arr: array to", "add border annotations showing values of params for each output", "utilize the 8-bit unsigned integer data # type transfer =", "L*a*b* color space. This implementation is (loosely) based on to", "comparison of color_transfer options Parameters: ------- target: NumPy array OpenCV", "to top border top_title_loc = (border_size, 75) top_true_loc = (border_size,", "\"\"\" Trim NumPy array values to be in [0, 255]", "cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics", "bStdTar) = image_stats(target) # subtract the means from the target", "Mean absolute error (MAE) is computed for the HSV channels", "the HSV channels of each result and the source image.", "found new smallest mae if chi2_dist < best_dist: best_result =", "0, 256, 0, 256]) # calc chi square dist chi2_dist", "by clipping. preserve_paper: Should color transfer strictly follow methodology laid", "top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc,", "-90) return bordered_comparison_image def image_stats(image): \"\"\" Parameters: ------- image: NumPy", "w / 2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255,", "cv2.split(image) (lMean, lStd) = (l.mean(), l.std()) (aMean, aStd) = (a.mean(),", "using the reciprocal of the scaling factor proposed in the", "/ (mx - mn) + new_range[0] else: # return array", "they fall # outside this range l = _scale_array(l, clip=clip)", "color space with borders applied to easily compare the different", "'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'False',", "of color_transfer options Parameters: ------- target: NumPy array OpenCV image", "range clip: should array be scaled by np.clip? if False", "w = comparison_image.shape[:2] top = np.zeros(w * border_size, dtype='uint8').reshape(border_size, w)", "255)): \"\"\" Perform min-max scaling to a NumPy array Parameters:", "best_result, comparison def chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5 * np.sum(((hist_a", "/ (hist_a + hist_b + eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table", "correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def image_stats(image):", "NumPy array (uint8) \"\"\" # convert the images from the", "necessary packages import numpy as np import cv2 import imutils", "new_range: tuple of form (min, max) specifying range of transformed", "(5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255,", "statistics return lMean, lStd, aMean, aStd, bMean, bStd def _min_max_scale(arr,", "candidate[:] candidates.append(candidate) # build 2 by 2 image matrix of", "_bool_matrix_border(comparison) return best_result, comparison def chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5", "options Parameters: ------- target: NumPy array OpenCV image in BGR", "space (the target image) clip: Should components of L*a*b* image", "keep target image brightness truer to the input. Scaling will", "the standard deviations using reciprocal of paper proposed factor l", "np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image)) # add text for", "(note: OpenCV # expects floats to be 32-bit, so use", "type transfer = cv2.merge([l, a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR)", "cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image,", "factor l = (lStdTar / lStdSrc) * l a =", "as a montage of all candidate results. Parameters: ------- source:", "If False then components will be min-max scaled appropriately. Clipping", "top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) # rotate 90", "\"\"\" if clip: scaled = np.clip(arr, 0, 255) else: scale_range", "# calc chi square dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) #", "best_result = candidate[:] candidates.append(candidate) # build 2 by 2 image", "result that minimizes mean absolute error between compared to source", "256]) # calc chi square dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand)", "- hist_b) ** 2) / (hist_a + hist_b + eps))", "HSV channels of each result and the source image. The", "if they fall # outside this range l = _scale_array(l,", "channel (l, a, b) = cv2.split(image) (lMean, lStd) = (l.mean(),", "cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image)) #", "aStdTar, bMeanTar, bStdTar) = image_stats(target) # subtract the means from", "NumPy array to be scaled to [new_min, new_max] range new_range:", "new_max] range new_range: tuple of form (min, max) specifying range", "annotations showing values of params for each output comparison =", "clip: scaled = np.clip(arr, 0, 255) else: scale_range = (max([arr.min(),", "each channel (l, a, b) = cv2.split(image) (lMean, lStd) =", "bMeanTar, bStdTar) = image_stats(target) # subtract the means from the", "for comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate], [0,", "of the clip & preserve_paper arguments. Mean absolute error (MAE)", "Tuple of mean and standard deviations for the L*, a*,", "scaled to [new_min, new_max] range new_range: tuple of form (min,", "Transfers the color distribution from the source to the target", "candidates = [] best_result = None best_dist = float('inf') for", "to left border top_title_loc = (5, 75) top_true_loc = (5", "mean and standard deviation of each channel (l, a, b)", "bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image)) # add", "= arr return scaled def _scale_array(arr, clip=True): \"\"\" Trim NumPy", "array (uint8) \"\"\" # convert the images from the RGB", "(arr - mn) / (mx - mn) + new_range[0] else:", "(the source image) target: NumPy array OpenCV image in BGR", "scaled using the reciprocal of the scaling factor proposed in", "the target image (l, a, b) = cv2.split(target) l -=", "# convert the images from the RGB to L*ab* color", "input. Scaling will adjust image brightness to avoid washed out", "color statistics return lMean, lStd, aMean, aStd, bMean, bStd def", "Should components of L*a*b* image be scaled by np.clip before", "# sure to utilizing the floating point data type (note:", "the L*, a*, and b* channels, respectively \"\"\" # compute", "(the target image) Returns: ------- tuple: (best_result, comparison) best_result: NumPy", "0, 255) else: scale_range = (max([arr.min(), 0]), min([arr.max(), 255])) scaled", "result truest to source image color Applies color_transfer with all", "256, 0, 256, 0, 256]) # calc chi square dist", "hsv_hist_cand) # propose new truest result if found new smallest", "+ border_size) * border_size, dtype='uint8').reshape(h + border_size, border_size) top =", "NumPy array image showing the results of all combinations of", "border annotations showing values of params for each output comparison", "to range [max([arr.min(), 0]), min([arr.max(), 255])] Returns: ------- NumPy array", "(lStdTar / lStdSrc) * l a = (aStdTar / aStdSrc)", "components will be min-max scaled appropriately. Clipping will keep target", "< best_dist: best_result = candidate[:] candidates.append(candidate) # build 2 by", "add text for clip arg options to top border top_title_loc", "[8, 8, 8], [0, 256, 0, 256, 0, 256]) #", "be min-max scaled to range [max([arr.min(), 0]), min([arr.max(), 255])] Returns:", "been scaled to be in [new_range[0], new_range[1]] range \"\"\" #", "be in [0, 255] range \"\"\" if clip: scaled =", "l a = (aStdSrc / aStdTar) * a b =", "bStdSrc) = image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) =", "for comparison of color_transfer options Parameters: ------- target: NumPy array", "a = (aStdSrc / aStdTar) * a b = (bStdSrc", "= comparison_image.shape[:2] top = np.zeros(w * border_size, dtype='uint8').reshape(border_size, w) left", "the floating point data type (note: OpenCV # expects floats", "caused by clipping. preserve_paper: Should color transfer strictly follow methodology", "methodology laid out in original paper? The method does not", "the RGB to L*ab* color space, being # sure to", "= None best_dist = float('inf') for clip in bools: for", "image in BGR color space (the target image) clip: Should", "target image) Returns: ------- tuple: (best_result, comparison) best_result: NumPy array", "in auto_color_transfer) Returns: ------- comparison: NumPy array OpenCV image in", "top_title_loc = (5, 75) top_true_loc = (5 + int(h /", "avoid washed out portions in the resulting color transfer that", "out portions in the resulting color transfer that can be", "transfer that can be caused by clipping. preserve_paper: Should color", "aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar,", "b = (bStdTar / bStdSrc) * b else: # scale", "unsigned integer data # type transfer = cv2.merge([l, a, b])", "The best_result that minimizes the MAE is returned as well", "image) Returns: ------- tuple: (best_result, comparison) best_result: NumPy array result", "0, 256, 0, 256]) # iterate through all 4 options", "target, clip, preserve_paper) # get mean HSV stats from candidate", "np.zeros((h + border_size) * border_size, dtype='uint8').reshape(h + border_size, border_size) top", "on to the \"Color Transfer between Images\" paper by <NAME>", "aMeanSrc b += bMeanSrc # clip/scale the pixel intensities to", "bordered_comparison_image)) # add text for clip arg options to top", "brightness to avoid washed out portions in the resulting color", "2 by 2 image matrix of all candidates for comparison", "190) top_false_loc = (int(border_size + w / 2), 190) cv2.putText(bordered_comparison_image,", "resulting color transfer that can be caused by clipping. preserve_paper:", "or mx > new_range[1]: # perform min-max scaling scaled =", "standard deviation of each channel (l, a, b) = cv2.split(image)", "for the source and target images (lMeanSrc, lStdSrc, aMeanSrc, aStdSrc,", "[0, 256, 0, 256, 0, 256]) # iterate through all", "scaled appropriately. Clipping will keep target image brightness truer to", "means from the target image (l, a, b) = cv2.split(target)", "mean and standard deviations for the L*, a*, and b*", "L*, a*, and b* channels, respectively \"\"\" # compute the", "be in new_range if mn < new_range[0] or mx >", "implementation is (loosely) based on to the \"Color Transfer between", "= (l.mean(), l.std()) (aMean, aStd) = (a.mean(), a.std()) (bMean, bStd)", "Parameters: ------- target: NumPy array OpenCV image in BGR color", "of params for each output comparison = _bool_matrix_border(comparison) return best_result,", "and convert back to the RGB color # space, being", "best_result: NumPy array result that minimizes mean absolute error between", "original paper? The method does not always produce aesthetically pleasing", "# compute the mean and standard deviation of each channel", "produce aesthetically pleasing results. If False then L*a*b* components will", "(5, 75) top_true_loc = (5 + int(h / 2), 190)", "32-bit, so use that instead of 64-bit) source = cv2.cvtColor(source,", "in BGR color space (the comparison image produced in auto_color_transfer)", "= cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics for the source", "new_range[0] else: # return array if already in range scaled", "array will be min-max scaled to range [max([arr.min(), 0]), min([arr.max(),", "NumPy array Parameters: ------- arr: NumPy array to be scaled", "on top and left of input image h, w =", "bordered_comparison_image def image_stats(image): \"\"\" Parameters: ------- image: NumPy array OpenCV", "NumPy array OpenCV image in BGR color space (the source", "OpenCV image (w, h, 3) NumPy array (uint8) \"\"\" #", "image return transfer def auto_color_transfer(source, target): \"\"\"Pick color_transfer result truest", "to be trimmed to [0, 255] range clip: should array", "(best_result, comparison) best_result: NumPy array result that minimizes mean absolute", "standard deviations using paper proposed factor l = (lStdTar /", "degrees for writing text to left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image,", "perform min-max scaling scaled = (new_range[1] - new_range[0]) * (arr", "method does not always produce aesthetically pleasing results. If False", "return array if already in range scaled = arr return", "8, 8], [0, 256, 0, 256, 0, 256]) # calc", "from the RGB to L*ab* color space, being # sure", "return 0.5 * np.sum(((hist_a - hist_b) ** 2) / (hist_a", "space. This implementation is (loosely) based on to the \"Color", "target = cv2.cvtColor(target, cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics for the", "cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) # rotate -90 degrees", "top_false_loc = (int(border_size + w / 2), 190) cv2.putText(bordered_comparison_image, 'Clip',", "# add border annotations showing values of params for each", "bools = [True, False] candidates = [] best_result = None", "dtype='uint8').reshape(h + border_size, border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left =", "image brightness to avoid washed out portions in the resulting", "# return the color statistics return lMean, lStd, aMean, aStd,", "The method does not always produce aesthetically pleasing results. If", "left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image)) bordered_comparison_image =", "# type transfer = cv2.merge([l, a, b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"),", "= arr.min() mx = arr.max() # check if scaling needs", "back to the RGB color # space, being sure to", "255) else: scale_range = (max([arr.min(), 0]), min([arr.max(), 255])) scaled =", "[new_range[0], new_range[1]] range \"\"\" # get array's current min and", "to produce more consistently aesthetically pleasing results Returns: ------- transfer:", "= np.vstack((top, comparison_image)) bordered_comparison_image = np.hstack((left, bordered_comparison_image)) # add text", "convert back to the RGB color # space, being sure", "comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border annotations showing", "best_dist = float('inf') for clip in bools: for preserve_paper in", "= _bool_matrix_border(comparison) return best_result, comparison def chi2_distance(hist_a, hist_b, eps=1e-10): return", "# create candidate image from options of this iteration candidate", "_bool_matrix_border(comparison_image): \"\"\"Apply table formatting for comparison of color_transfer options Parameters:", "the scaling factor proposed in the paper. This method seems", "to L*ab* color space, being # sure to utilizing the", "cv2.COLOR_BGR2LAB).astype(\"float32\") # compute color statistics for the source and target", "showing the results of all combinations of color_transfer options \"\"\"", "Perform min-max scaling to a NumPy array Parameters: ------- arr:", "scaling needs to be done to be in new_range if", "* (arr - mn) / (mx - mn) + new_range[0]", "hsv_hist_src = cv2.calcHist([hsv_source], [0, 1, 2], None, [8, 8, 8],", "arg options to left border top_title_loc = (5, 75) top_true_loc", "b]) transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the color transferred", "paper? The method does not always produce aesthetically pleasing results.", "<NAME> al., 2001. Parameters: ------- source: NumPy array OpenCV image", "* l a = (aStdTar / aStdSrc) * a b", "new truest result if found new smallest mae if chi2_dist", "to return image in correct orientation bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90)", "the clip & preserve_paper arguments. Mean absolute error (MAE) is", "between Images\" paper by <NAME> al., 2001. Parameters: ------- source:", "mean absolute error between compared to source image in HSV", "bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) # add text for preserve paper", "bools: # create candidate image from options of this iteration", "else: # return array if already in range scaled =", "lStdSrc) * l a = (aStdTar / aStdSrc) * a", "= np.zeros((h + border_size) * border_size, dtype='uint8').reshape(h + border_size, border_size)", "np.clip? if False then input array will be min-max scaled", "to source image in HSV color space comparison: NumPy array", "method seems to produce more consistently aesthetically pleasing results Returns:", "l += lMeanSrc a += aMeanSrc b += bMeanSrc #", "result if found new smallest mae if chi2_dist < best_dist:", "the standard deviations using paper proposed factor l = (lStdTar", "and standard deviation of each channel (l, a, b) =", "(bMean, bStd) = (b.mean(), b.std()) # return the color statistics", "l -= lMeanTar a -= aMeanTar b -= bMeanTar if", "color space (the comparison image produced in auto_color_transfer) Returns: -------", "transfer = cv2.cvtColor(transfer.astype(\"uint8\"), cv2.COLOR_LAB2BGR) # return the color transferred image", "/ bStdSrc) * b else: # scale by the standard", "256, 0, 256, 0, 256]) # iterate through all 4", "(255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255,", "min-max scaling to a NumPy array Parameters: ------- arr: NumPy", "[True, False] candidates = [] best_result = None best_dist =", "color space (the source image) target: NumPy array OpenCV image", "(5 + int(h / 2), 190) top_false_loc = (5, 190)", "l.std()) (aMean, aStd) = (a.mean(), a.std()) (bMean, bStd) = (b.mean(),", "strictly follow methodology laid out in original paper? The method", "rotate -90 degrees to return image in correct orientation bordered_comparison_image", "outside this range l = _scale_array(l, clip=clip) a = _scale_array(a,", "sure to utilizing the floating point data type (note: OpenCV", "source image in HSV color space comparison: NumPy array image", "and b* channels, respectively \"\"\" # compute the mean and", "to be in [0, 255] range with option of clipping", "in the resulting color transfer that can be caused by", "of input image h, w = comparison_image.shape[:2] top = np.zeros(w", "by <NAME> al., 2001. Parameters: ------- source: NumPy array OpenCV", "def auto_color_transfer(source, target): \"\"\"Pick color_transfer result truest to source image", "arguments. Mean absolute error (MAE) is computed for the HSV", "NumPy array OpenCV image (w, h, 3) NumPy array (uint8)", "3) NumPy array (uint8) \"\"\" # convert the images from", "_min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform min-max scaling to a NumPy", "then input array will be min-max scaled to range [max([arr.min(),", "NumPy array values to be in [0, 255] range with", "done to be in new_range if mn < new_range[0] or", "params for each output comparison = _bool_matrix_border(comparison) return best_result, comparison", "converting back to BGR color space? If False then components", "image produced in auto_color_transfer) Returns: ------- comparison: NumPy array OpenCV", "= np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border annotations showing values of", "compare the different results of the auto_color_transfer \"\"\" # 200", "\"\"\"Apply table formatting for comparison of color_transfer options Parameters: -------", "255, 255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255,", "\"\"\" # get array's current min and max mn =", "writing text to left border bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, 90) #", "source to the target image using the mean and standard", "transfer strictly follow methodology laid out in original paper? The", "l = (lStdSrc / lStdTar) * l a = (aStdSrc", "that has been scaled to be in [0, 255] range", "create candidate image from options of this iteration candidate =", "rotate 90 degrees for writing text to left border bordered_comparison_image", "8], [0, 256, 0, 256, 0, 256]) # iterate through", "range l = _scale_array(l, clip=clip) a = _scale_array(a, clip=clip) b", "arr: array to be trimmed to [0, 255] range clip:", "image (l, a, b) = cv2.split(target) l -= lMeanTar a", "get array's current min and max mn = arr.min() mx", "results. Parameters: ------- source: NumPy array OpenCV image in BGR", "= chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new truest result if found", "and standard deviations of the L*a*b* color space. This implementation", "hist_b) ** 2) / (hist_a + hist_b + eps)) def", "- new_range[0]) * (arr - mn) / (mx - mn)", "\"\"\"Pick color_transfer result truest to source image color Applies color_transfer", "is (loosely) based on to the \"Color Transfer between Images\"", "matrix of all candidates for comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:])))", "the reciprocal of the scaling factor proposed in the paper.", "source image for comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV) hsv_hist_src =", "in original paper? The method does not always produce aesthetically", "lMeanTar a -= aMeanTar b -= bMeanTar if preserve_paper: #", "truest to source image color Applies color_transfer with all possible", "bMeanSrc # clip/scale the pixel intensities to [0, 255] if", "color transfer strictly follow methodology laid out in original paper?", "If False then L*a*b* components will scaled using the reciprocal", "# build 2 by 2 image matrix of all candidates", "(loosely) based on to the \"Color Transfer between Images\" paper", "8, 8], [0, 256, 0, 256, 0, 256]) # iterate", "space with borders applied to easily compare the different results", "expects floats to be 32-bit, so use that instead of", "75) top_true_loc = (border_size, 190) top_false_loc = (int(border_size + w", "= _scale_array(b, clip=clip) # merge the channels together and convert", "cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'False', top_false_loc, cv2.FONT_HERSHEY_SIMPLEX,", "stats from source image for comparison hsv_source = cv2.cvtColor(source, cv2.COLOR_BGR2HSV)", "the pixel intensities to [0, 255] if they fall #", "b += bMeanSrc # clip/scale the pixel intensities to [0,", "a montage of all candidate results. Parameters: ------- source: NumPy", "clip, preserve_paper) # get mean HSV stats from candidate image", "color distribution from the source to the target image using", "------- source: NumPy array OpenCV image in BGR color space", "NumPy array OpenCV image in BGR color space (the target", "floating point data type (note: OpenCV # expects floats to", "produced in auto_color_transfer) Returns: ------- comparison: NumPy array OpenCV image", "0, 256]) # iterate through all 4 options for toggling", "cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top, comparison_image))", "deviations using paper proposed factor l = (lStdTar / lStdSrc)", "scaled = np.clip(arr, 0, 255) else: scale_range = (max([arr.min(), 0]),", "mae if chi2_dist < best_dist: best_result = candidate[:] candidates.append(candidate) #", "left of input image h, w = comparison_image.shape[:2] top =", "border_size, border_size) top = cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR)", "for clip arg options to top border top_title_loc = (border_size,", "= (bStdTar / bStdSrc) * b else: # scale by", "each result and the source image. The best_result that minimizes", "90 degrees for writing text to left border bordered_comparison_image =", "preserve_paper in bools: # create candidate image from options of", "# clip/scale the pixel intensities to [0, 255] if they", "with borders applied to easily compare the different results of", "color space (the target image) clip: Should components of L*a*b*", "color space. This implementation is (loosely) based on to the", "of this iteration candidate = color_transfer(source, target, clip, preserve_paper) #", "HSV stats from candidate image for comparison hsv_candidate = cv2.cvtColor(candidate,", "BGR color space? If False then components will be min-max", "8], [0, 256, 0, 256, 0, 256]) # calc chi", "(hist_a + hist_b + eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting", "= imutils.rotate_bound(bordered_comparison_image, 90) # add text for preserve paper arg", "= (max([arr.min(), 0]), min([arr.max(), 255])) scaled = _min_max_scale(arr, new_range=scale_range) return", "(min, max) specifying range of transformed array Returns: ------- NumPy", "(new_range[1] - new_range[0]) * (arr - mn) / (mx -", "the mean and standard deviations of the L*a*b* color space.", "# propose new truest result if found new smallest mae", "of form (min, max) specifying range of transformed array Returns:", "clip in bools: for preserve_paper in bools: # create candidate", "np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add border annotations showing values of params", "seems to work well as border size border_size = 200", "aMeanTar b -= bMeanTar if preserve_paper: # scale by the", "bMean, bStd def _min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform min-max scaling", "# get array's current min and max mn = arr.min()", "new_range if mn < new_range[0] or mx > new_range[1]: #", "max mn = arr.min() mx = arr.max() # check if", "aStdTar) * a b = (bStdSrc / bStdTar) * b", "(255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX, 2, (255,", "scaled by np.clip before converting back to BGR color space?", "* np.sum(((hist_a - hist_b) ** 2) / (hist_a + hist_b", "bMeanTar if preserve_paper: # scale by the standard deviations using", "target): \"\"\"Pick color_transfer result truest to source image color Applies", "cv2.calcHist([hsv_source], [0, 1, 2], None, [8, 8, 8], [0, 256,", "_scale_array(a, clip=clip) b = _scale_array(b, clip=clip) # merge the channels", "returned as well as a montage of all candidate results.", "if chi2_dist < best_dist: best_result = candidate[:] candidates.append(candidate) # build", "to the RGB color # space, being sure to utilize", "transferred image return transfer def auto_color_transfer(source, target): \"\"\"Pick color_transfer result", "eps)) def _bool_matrix_border(comparison_image): \"\"\"Apply table formatting for comparison of color_transfer", "BGR color space (the comparison image produced in auto_color_transfer) Returns:", "results of the auto_color_transfer \"\"\" # 200 seems to work", "= (5, 75) top_true_loc = (5 + int(h / 2),", "190) top_false_loc = (5, 190) cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX,", "* b # add in the source mean l +=", "b* channels, respectively \"\"\" # compute the mean and standard", "utilizing the floating point data type (note: OpenCV # expects", "with option of clipping or scaling. Parameters: ------- arr: array", "color space Returns: ------- Tuple of mean and standard deviations", "OpenCV image in BGR color space (the source image) target:", "image) target: NumPy array OpenCV image in BGR color space", "follow methodology laid out in original paper? The method does", "OpenCV # expects floats to be 32-bit, so use that", "b) = cv2.split(image) (lMean, lStd) = (l.mean(), l.std()) (aMean, aStd)", "= arr.max() # check if scaling needs to be done", "build 2 by 2 image matrix of all candidates for", "array values to be in [0, 255] range with option", "space (the target image) Returns: ------- tuple: (best_result, comparison) best_result:", "array be scaled by np.clip? if False then input array", "all possible combinations of the clip & preserve_paper arguments. Mean", "black border on top and left of input image h,", "= (a.mean(), a.std()) (bMean, bStd) = (b.mean(), b.std()) # return", "with all possible combinations of the clip & preserve_paper arguments.", "scale by the standard deviations using reciprocal of paper proposed", "back to BGR color space? If False then components will", "b = (bStdSrc / bStdTar) * b # add in", "color statistics for the source and target images (lMeanSrc, lStdSrc,", "[] best_result = None best_dist = float('inf') for clip in", "of L*a*b* image be scaled by np.clip before converting back", "always produce aesthetically pleasing results. If False then L*a*b* components", "candidate image for comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand =", "image in L*a*b* color space Returns: ------- Tuple of mean", "to be in new_range if mn < new_range[0] or mx", "the source to the target image using the mean and", "bStdSrc) * b else: # scale by the standard deviations", "top and left of input image h, w = comparison_image.shape[:2]", "a*, and b* channels, respectively \"\"\" # compute the mean", "preserve_paper) # get mean HSV stats from candidate image for", "of paper proposed factor l = (lStdSrc / lStdTar) *", "has been scaled to be in [new_range[0], new_range[1]] range \"\"\"", "color_transfer(source, target, clip, preserve_paper) # get mean HSV stats from", "min([arr.max(), 255])] Returns: ------- NumPy array that has been scaled", "cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) cv2.putText(bordered_comparison_image, 'True', top_true_loc, cv2.FONT_HERSHEY_SIMPLEX,", "this range l = _scale_array(l, clip=clip) a = _scale_array(a, clip=clip)", "= cv2.cvtColor(top, cv2.COLOR_GRAY2BGR) left = cv2.cvtColor(left, cv2.COLOR_GRAY2BGR) bordered_comparison_image = np.vstack((top,", "needs to be done to be in new_range if mn", "array OpenCV image in BGR color space (the comparison image", "_scale_array(arr, clip=True): \"\"\" Trim NumPy array values to be in", "tuple: (best_result, comparison) best_result: NumPy array result that minimizes mean", "array OpenCV image in L*a*b* color space Returns: ------- Tuple", "/ 2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255,", "(uint8) \"\"\" # convert the images from the RGB to", "will be min-max scaled appropriately. Clipping will keep target image", "clipping. preserve_paper: Should color transfer strictly follow methodology laid out", "= image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target)", "= (5 + int(h / 2), 190) top_false_loc = (5,", "seems to produce more consistently aesthetically pleasing results Returns: -------", "images from the RGB to L*ab* color space, being #", "color space, being # sure to utilizing the floating point", "image in BGR color space with borders applied to easily", "** 2) / (hist_a + hist_b + eps)) def _bool_matrix_border(comparison_image):", "portions in the resulting color transfer that can be caused", "border_size) * border_size, dtype='uint8').reshape(h + border_size, border_size) top = cv2.cvtColor(top,", "clip: should array be scaled by np.clip? if False then", "of clipping or scaling. Parameters: ------- arr: array to be", "preserve_paper=True): \"\"\" Transfers the color distribution from the source to", "(aMean, aStd) = (a.mean(), a.std()) (bMean, bStd) = (b.mean(), b.std())", "_scale_array(b, clip=clip) # merge the channels together and convert back", "(max([arr.min(), 0]), min([arr.max(), 255])) scaled = _min_max_scale(arr, new_range=scale_range) return scaled", "of color_transfer options \"\"\" # get mean HSV stats from", "chi square dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new", "np.clip before converting back to BGR color space? If False", "255] if they fall # outside this range l =", "to be 32-bit, so use that instead of 64-bit) source", "mean l += lMeanSrc a += aMeanSrc b += bMeanSrc", "proposed in the paper. This method seems to produce more", "input image h, w = comparison_image.shape[:2] top = np.zeros(w *", "(lMean, lStd) = (l.mean(), l.std()) (aMean, aStd) = (a.mean(), a.std())", "RGB to L*ab* color space, being # sure to utilizing", "stats from candidate image for comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV)", "\"\"\" Transfers the color distribution from the source to the", "\"\"\" Parameters: ------- image: NumPy array OpenCV image in L*a*b*", "# return the color transferred image return transfer def auto_color_transfer(source,", "aStd, bMean, bStd def _min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform min-max", "- mn) + new_range[0] else: # return array if already", "bStd) = (b.mean(), b.std()) # return the color statistics return", "for preserve paper arg options to left border top_title_loc =", "cv2.COLOR_LAB2BGR) # return the color transferred image return transfer def", "will be min-max scaled to range [max([arr.min(), 0]), min([arr.max(), 255])]", "= _scale_array(l, clip=clip) a = _scale_array(a, clip=clip) b = _scale_array(b,", "cv2.split(target) l -= lMeanTar a -= aMeanTar b -= bMeanTar", "options \"\"\" # get mean HSV stats from source image", "int(h / 2), 190) top_false_loc = (5, 190) cv2.putText(bordered_comparison_image, 'Preserve", "[0, 255] range with option of clipping or scaling. Parameters:", "<reponame>AdamSpannbauer/color_transfer<gh_stars>0 # import the necessary packages import numpy as np", "# scale by the standard deviations using paper proposed factor", "+= aMeanSrc b += bMeanSrc # clip/scale the pixel intensities", "arr return scaled def _scale_array(arr, clip=True): \"\"\" Trim NumPy array", "source image. The best_result that minimizes the MAE is returned", "def chi2_distance(hist_a, hist_b, eps=1e-10): return 0.5 * np.sum(((hist_a - hist_b)", "will adjust image brightness to avoid washed out portions in", "array image showing the results of all combinations of color_transfer", "------- Tuple of mean and standard deviations for the L*,", "array to be scaled to [new_min, new_max] range new_range: tuple", "bools: for preserve_paper in bools: # create candidate image from", "the color distribution from the source to the target image", "l = _scale_array(l, clip=clip) a = _scale_array(a, clip=clip) b =", "Transfer between Images\" paper by <NAME> al., 2001. Parameters: -------", "imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def image_stats(image): \"\"\" Parameters: ------- image:", "chi2_dist < best_dist: best_result = candidate[:] candidates.append(candidate) # build 2", "instead of 64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target = cv2.cvtColor(target,", "# add in the source mean l += lMeanSrc a", "False then components will be min-max scaled appropriately. Clipping will", "# scale by the standard deviations using reciprocal of paper", "for clip in bools: for preserve_paper in bools: # create", "this iteration candidate = color_transfer(source, target, clip, preserve_paper) # get", "if found new smallest mae if chi2_dist < best_dist: best_result", "HSV stats from source image for comparison hsv_source = cv2.cvtColor(source,", "use that instead of 64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target", "image) clip: Should components of L*a*b* image be scaled by", "clip & preserve_paper arguments. Mean absolute error (MAE) is computed", "does not always produce aesthetically pleasing results. If False then", "lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar, lStdTar, aMeanTar,", "source image color Applies color_transfer with all possible combinations of", "comparison: NumPy array image showing the results of all combinations", "paper. This method seems to produce more consistently aesthetically pleasing", "pleasing results Returns: ------- transfer: NumPy array OpenCV image (w,", "b = _scale_array(b, clip=clip) # merge the channels together and", "of the L*a*b* color space. This implementation is (loosely) based", "hist_b, eps=1e-10): return 0.5 * np.sum(((hist_a - hist_b) ** 2)", "options to left border top_title_loc = (5, 75) top_true_loc =", "[max([arr.min(), 0]), min([arr.max(), 255])] Returns: ------- NumPy array that has", "(border_size, 190) top_false_loc = (int(border_size + w / 2), 190)", "min and max mn = arr.min() mx = arr.max() #", "square dist chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new truest", "= np.clip(arr, 0, 255) else: scale_range = (max([arr.min(), 0]), min([arr.max(),", "255), 2) # rotate 90 degrees for writing text to", "target image brightness truer to the input. Scaling will adjust", "b else: # scale by the standard deviations using reciprocal", "= _scale_array(a, clip=clip) b = _scale_array(b, clip=clip) # merge the", "the color transferred image return transfer def auto_color_transfer(source, target): \"\"\"Pick", "using reciprocal of paper proposed factor l = (lStdSrc /", "min-max scaling scaled = (new_range[1] - new_range[0]) * (arr -", "return scaled def _scale_array(arr, clip=True): \"\"\" Trim NumPy array values", "color_transfer(source, target, clip=True, preserve_paper=True): \"\"\" Transfers the color distribution from", "NumPy array OpenCV image in BGR color space with borders", "bordered_comparison_image = imutils.rotate_bound(bordered_comparison_image, -90) return bordered_comparison_image def image_stats(image): \"\"\" Parameters:", "results of all combinations of color_transfer options \"\"\" # get", "showing values of params for each output comparison = _bool_matrix_border(comparison)", "lMeanSrc a += aMeanSrc b += bMeanSrc # clip/scale the", "candidate = color_transfer(source, target, clip, preserve_paper) # get mean HSV", "chi2_dist = chi2_distance(hsv_hist_src, hsv_hist_cand) # propose new truest result if", "= image_stats(target) # subtract the means from the target image", "l = (lStdTar / lStdSrc) * l a = (aStdTar", "# expects floats to be 32-bit, so use that instead", "image for comparison hsv_candidate = cv2.cvtColor(candidate, cv2.COLOR_BGR2HSV) hsv_hist_cand = cv2.calcHist([hsv_candidate],", "sure to utilize the 8-bit unsigned integer data # type", "and left of input image h, w = comparison_image.shape[:2] top", "BGR color space with borders applied to easily compare the", "BGR color space (the target image) Returns: ------- tuple: (best_result,", "2) # rotate 90 degrees for writing text to left", "OpenCV image in BGR color space with borders applied to", "deviation of each channel (l, a, b) = cv2.split(image) (lMean,", "image using the mean and standard deviations of the L*a*b*", "bStd def _min_max_scale(arr, new_range=(0, 255)): \"\"\" Perform min-max scaling to", "reciprocal of paper proposed factor l = (lStdSrc / lStdTar)", "new_range[1]] range \"\"\" # get array's current min and max", "* a b = (bStdTar / bStdSrc) * b else:", "of the auto_color_transfer \"\"\" # 200 seems to work well", "of the scaling factor proposed in the paper. This method", "lStd) = (l.mean(), l.std()) (aMean, aStd) = (a.mean(), a.std()) (bMean,", "laid out in original paper? The method does not always", "h, 3) NumPy array (uint8) \"\"\" # convert the images", "256, 0, 256]) # calc chi square dist chi2_dist =", "is returned as well as a montage of all candidate", "(l.mean(), l.std()) (aMean, aStd) = (a.mean(), a.std()) (bMean, bStd) =", "the input. Scaling will adjust image brightness to avoid washed", "values of params for each output comparison = _bool_matrix_border(comparison) return", "best_result that minimizes the MAE is returned as well as", "np.sum(((hist_a - hist_b) ** 2) / (hist_a + hist_b +", "= (border_size, 190) top_false_loc = (int(border_size + w / 2),", "as np import cv2 import imutils def color_transfer(source, target, clip=True,", "scaling to a NumPy array Parameters: ------- arr: NumPy array", "-90 degrees to return image in correct orientation bordered_comparison_image =", "- mn) / (mx - mn) + new_range[0] else: #", "lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target) # subtract the", "array that has been scaled to be in [0, 255]", "scaled = arr return scaled def _scale_array(arr, clip=True): \"\"\" Trim", "cv2.putText(bordered_comparison_image, 'Preserve Paper', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)", "255] range with option of clipping or scaling. Parameters: -------", "border_size = 200 # put black border on top and", "truer to the input. Scaling will adjust image brightness to", "target image) clip: Should components of L*a*b* image be scaled", "# outside this range l = _scale_array(l, clip=clip) a =", "-= bMeanTar if preserve_paper: # scale by the standard deviations", "array to be trimmed to [0, 255] range clip: should", "get mean HSV stats from source image for comparison hsv_source", "a, b) = cv2.split(image) (lMean, lStd) = (l.mean(), l.std()) (aMean,", "target, clip=True, preserve_paper=True): \"\"\" Transfers the color distribution from the", "subtract the means from the target image (l, a, b)", "that instead of 64-bit) source = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(\"float32\") target =", "color transferred image return transfer def auto_color_transfer(source, target): \"\"\"Pick color_transfer", "0, 256]) # calc chi square dist chi2_dist = chi2_distance(hsv_hist_src,", "= np.zeros(w * border_size, dtype='uint8').reshape(border_size, w) left = np.zeros((h +", "border top_title_loc = (border_size, 75) top_true_loc = (border_size, 190) top_false_loc", "image: NumPy array OpenCV image in L*a*b* color space Returns:", "be in [new_range[0], new_range[1]] range \"\"\" # get array's current", "add text for preserve paper arg options to left border", "produce more consistently aesthetically pleasing results Returns: ------- transfer: NumPy", "255])] Returns: ------- NumPy array that has been scaled to", "bStdTar) * b # add in the source mean l", "bMeanSrc, bStdSrc) = image_stats(source) (lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar)", "options to top border top_title_loc = (border_size, 75) top_true_loc =", "check if scaling needs to be done to be in", "= [True, False] candidates = [] best_result = None best_dist", "to be done to be in new_range if mn <", "256, 0, 256]) # iterate through all 4 options for", "point data type (note: OpenCV # expects floats to be", "np.vstack(candidates[2:]))) # add border annotations showing values of params for", "output comparison = _bool_matrix_border(comparison) return best_result, comparison def chi2_distance(hist_a, hist_b,", "color space (the target image) Returns: ------- tuple: (best_result, comparison)", "# put black border on top and left of input", "Returns: ------- transfer: NumPy array OpenCV image (w, h, 3)", "color # space, being sure to utilize the 8-bit unsigned", "2), 190) cv2.putText(bordered_comparison_image, 'Clip', top_title_loc, cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255),", "text for preserve paper arg options to left border top_title_loc", "the paper. This method seems to produce more consistently aesthetically", "all candidates for comparison comparison = np.hstack((np.vstack(candidates[:2]), np.vstack(candidates[2:]))) # add", "Parameters: ------- arr: NumPy array to be scaled to [new_min," ]
[ "import CreateATree tree = CreateATree.BinarySearchTree() nodesList = list((4, 5, 1,", "CreateATree tree = CreateATree.BinarySearchTree() nodesList = list((4, 5, 1, 3,", "from Library.CreateATree import CreateATree tree = CreateATree.BinarySearchTree() nodesList = list((4,", "tree = CreateATree.BinarySearchTree() nodesList = list((4, 5, 1, 3, 2))", "2)) for i in range(0, len(nodesList)): tree.insert(nodesList[i]) #tree.printInorder() tree.printPreorder() #tree.printPostorder()", "= CreateATree.BinarySearchTree() nodesList = list((4, 5, 1, 3, 2)) for", "nodesList = list((4, 5, 1, 3, 2)) for i in", "5, 1, 3, 2)) for i in range(0, len(nodesList)): tree.insert(nodesList[i])", "list((4, 5, 1, 3, 2)) for i in range(0, len(nodesList)):", "3, 2)) for i in range(0, len(nodesList)): tree.insert(nodesList[i]) #tree.printInorder() tree.printPreorder()", "CreateATree.BinarySearchTree() nodesList = list((4, 5, 1, 3, 2)) for i", "= list((4, 5, 1, 3, 2)) for i in range(0,", "Library.CreateATree import CreateATree tree = CreateATree.BinarySearchTree() nodesList = list((4, 5,", "1, 3, 2)) for i in range(0, len(nodesList)): tree.insert(nodesList[i]) #tree.printInorder()" ]
[ "= 'home' ), path( 'about-me', views.About_me.as_view(), name = 'about_me' ),", "# # Author: <NAME> <<EMAIL>> from django.urls import path from", "= 'about_me' ), path( 'search', views.Search.as_view(), name = 'search' ),", "path( 'about-me', views.About_me.as_view(), name = 'about_me' ), path( 'search', views.Search.as_view(),", "path( '', views.Home.as_view(), name = 'home' ), path( 'about-me', views.About_me.as_view(),", "name = 'about_me' ), path( 'search', views.Search.as_view(), name = 'search'", "= 'siteApp' urlpatterns = [ path( '', views.Home.as_view(), name =", "[ path( '', views.Home.as_view(), name = 'home' ), path( 'about-me',", "path from . import views app_name = 'siteApp' urlpatterns =", "), path( 'search/page/<int:page>', views.Search.as_view(), name = 'search' ), path( 'sitemap.xml',", "Projects # # # Author: <NAME> <<EMAIL>> from django.urls import", "), path( 'search', views.Search.as_view(), name = 'search' ), path( 'search/page/<int:page>',", "<<EMAIL>> from django.urls import path from . import views app_name", "'', views.Home.as_view(), name = 'home' ), path( 'about-me', views.About_me.as_view(), name", "'about_me' ), path( 'search', views.Search.as_view(), name = 'search' ), path(", "VAZ Projects # # # Author: <NAME> <<EMAIL>> from django.urls", "views.Search.as_view(), name = 'search' ), path( 'search/page/<int:page>', views.Search.as_view(), name =", "path( 'search/page/<int:page>', views.Search.as_view(), name = 'search' ), path( 'sitemap.xml', views.Sitemap.as_view(),", "'search' ), path( 'search/page/<int:page>', views.Search.as_view(), name = 'search' ), path(", "views.Home.as_view(), name = 'home' ), path( 'about-me', views.About_me.as_view(), name =", "views.About_me.as_view(), name = 'about_me' ), path( 'search', views.Search.as_view(), name =", "'search' ), path( 'sitemap.xml', views.Sitemap.as_view(), name = 'sitemap' ), ]", "= 'search' ), path( 'sitemap.xml', views.Sitemap.as_view(), name = 'sitemap' ),", "# Author: <NAME> <<EMAIL>> from django.urls import path from .", "# VAZ Projects # # # Author: <NAME> <<EMAIL>> from", "path( 'search', views.Search.as_view(), name = 'search' ), path( 'search/page/<int:page>', views.Search.as_view(),", "<NAME> <<EMAIL>> from django.urls import path from . import views", "import views app_name = 'siteApp' urlpatterns = [ path( '',", "import path from . import views app_name = 'siteApp' urlpatterns", "'about-me', views.About_me.as_view(), name = 'about_me' ), path( 'search', views.Search.as_view(), name", "app_name = 'siteApp' urlpatterns = [ path( '', views.Home.as_view(), name", "from . import views app_name = 'siteApp' urlpatterns = [", "from django.urls import path from . import views app_name =", "'siteApp' urlpatterns = [ path( '', views.Home.as_view(), name = 'home'", "= [ path( '', views.Home.as_view(), name = 'home' ), path(", ". import views app_name = 'siteApp' urlpatterns = [ path(", "views.Search.as_view(), name = 'search' ), path( 'sitemap.xml', views.Sitemap.as_view(), name =", "# # # Author: <NAME> <<EMAIL>> from django.urls import path", "django.urls import path from . import views app_name = 'siteApp'", "name = 'home' ), path( 'about-me', views.About_me.as_view(), name = 'about_me'", "name = 'search' ), path( 'sitemap.xml', views.Sitemap.as_view(), name = 'sitemap'", "'search/page/<int:page>', views.Search.as_view(), name = 'search' ), path( 'sitemap.xml', views.Sitemap.as_view(), name", "# # VAZ Projects # # # Author: <NAME> <<EMAIL>>", "urlpatterns = [ path( '', views.Home.as_view(), name = 'home' ),", "views app_name = 'siteApp' urlpatterns = [ path( '', views.Home.as_view(),", "Author: <NAME> <<EMAIL>> from django.urls import path from . import", "name = 'search' ), path( 'search/page/<int:page>', views.Search.as_view(), name = 'search'", "'search', views.Search.as_view(), name = 'search' ), path( 'search/page/<int:page>', views.Search.as_view(), name", "), path( 'about-me', views.About_me.as_view(), name = 'about_me' ), path( 'search',", "= 'search' ), path( 'search/page/<int:page>', views.Search.as_view(), name = 'search' ),", "'home' ), path( 'about-me', views.About_me.as_view(), name = 'about_me' ), path(" ]
[]
[ "thus continues to next block of code #sys.exit() is to", "v) def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the service", "\"Scheduling restart of crashed service process\" #in case we called", "__init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service = PythonServiceClass.mService", "jnius import autoclass from Conf.Conf import * class ServiceBase(): def", "of crashed service process\" #in case we called only sys.exit()", "to next block of code #sys.exit() is to prevent subsequent", "k.isupper() and k.startswith(\"SMS\")} for k, v in confDict.items(): setattr(self, k,", "print(\"Attempting to kill service permanently.\") PythonService.stop() #service takes time to", "service process\" #in case we called only sys.exit() #this applies", "only sys.exit() #this applies even if we have setAutoRestartService(False) print(\"Exiting", "killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the service disabled.\") print(\"Attempting", "to avoid \"Scheduling restart of crashed service process\" #in case", "on Android 9 self.Service.setAutoRestartService(True) self.confDict = {k: v for k,v", "swiping on Android 9 self.Service.setAutoRestartService(True) self.confDict = {k: v for", "is to prevent subsequent code from execution #both calls are", "to task swiping on Android 9 self.Service.setAutoRestartService(True) self.confDict = {k:", "to kill service permanently.\") PythonService.stop() #service takes time to stop.", "print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the service disabled.\") print(\"Attempting to kill", "confDict.items(): setattr(self, k, v) def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart", "error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the service disabled.\") print(\"Attempting to", "''' import sys from jnius import autoclass from Conf.Conf import", "{k: v for k,v in globals().items() if k.isupper() and k.startswith(\"SMS\")}", "calls are neccesary to avoid \"Scheduling restart of crashed service", "for k,v in globals().items() if k.isupper() and k.startswith(\"SMS\")} for k,", "continues to next block of code #sys.exit() is to prevent", "self.Context = autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set autorestart to be", "= autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set autorestart", "PythonServiceClass.mService #set autorestart to be imune to task swiping on", "PythonService.stop() #service takes time to stop. flow thus continues to", "from Conf.Conf import * class ServiceBase(): def __init__(self): PythonServiceClass =", "#in case we called only sys.exit() #this applies even if", "''' @author <NAME> @since 10.8.2019 ''' import sys from jnius", "= autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set autorestart to be imune", "#this applies even if we have setAutoRestartService(False) print(\"Exiting python script\")", "PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set", "permanently.\") PythonService.stop() #service takes time to stop. flow thus continues", "#sys.exit() is to prevent subsequent code from execution #both calls", "k,v in globals().items() if k.isupper() and k.startswith(\"SMS\")} for k, v", "time to stop. flow thus continues to next block of", "globals().items() if k.isupper() and k.startswith(\"SMS\")} for k, v in confDict.items():", "the service disabled.\") print(\"Attempting to kill service permanently.\") PythonService.stop() #service", "task swiping on Android 9 self.Service.setAutoRestartService(True) self.confDict = {k: v", "for k, v in confDict.items(): setattr(self, k, v) def killGeneric(self,", "flow thus continues to next block of code #sys.exit() is", "block of code #sys.exit() is to prevent subsequent code from", "autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set autorestart to", "@since 10.8.2019 ''' import sys from jnius import autoclass from", "takes time to stop. flow thus continues to next block", "k, v) def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the", "def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service =", "neccesary to avoid \"Scheduling restart of crashed service process\" #in", "if k.isupper() and k.startswith(\"SMS\")} for k, v in confDict.items(): setattr(self,", "autorestart to be imune to task swiping on Android 9", "in confDict.items(): setattr(self, k, v) def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False)", "#both calls are neccesary to avoid \"Scheduling restart of crashed", "process\" #in case we called only sys.exit() #this applies even", "k.startswith(\"SMS\")} for k, v in confDict.items(): setattr(self, k, v) def", "crashed service process\" #in case we called only sys.exit() #this", "case we called only sys.exit() #this applies even if we", "autoclass('android.content.Context') self.Service = PythonServiceClass.mService #set autorestart to be imune to", "prevent subsequent code from execution #both calls are neccesary to", "<NAME> @since 10.8.2019 ''' import sys from jnius import autoclass", "v in confDict.items(): setattr(self, k, v) def killGeneric(self, error): print(repr(error))", "to stop. flow thus continues to next block of code", "import * class ServiceBase(): def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context", "setattr(self, k, v) def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of", "we called only sys.exit() #this applies even if we have", "service permanently.\") PythonService.stop() #service takes time to stop. flow thus", "import sys from jnius import autoclass from Conf.Conf import *", "self.confDict = {k: v for k,v in globals().items() if k.isupper()", "= {k: v for k,v in globals().items() if k.isupper() and", "called only sys.exit() #this applies even if we have setAutoRestartService(False)", "disabled.\") print(\"Attempting to kill service permanently.\") PythonService.stop() #service takes time", "be imune to task swiping on Android 9 self.Service.setAutoRestartService(True) self.confDict", "code #sys.exit() is to prevent subsequent code from execution #both", "autoclass from Conf.Conf import * class ServiceBase(): def __init__(self): PythonServiceClass", "imune to task swiping on Android 9 self.Service.setAutoRestartService(True) self.confDict =", "kill service permanently.\") PythonService.stop() #service takes time to stop. flow", "execution #both calls are neccesary to avoid \"Scheduling restart of", "in globals().items() if k.isupper() and k.startswith(\"SMS\")} for k, v in", "ServiceBase(): def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context') self.Service", "service disabled.\") print(\"Attempting to kill service permanently.\") PythonService.stop() #service takes", "to prevent subsequent code from execution #both calls are neccesary", "and k.startswith(\"SMS\")} for k, v in confDict.items(): setattr(self, k, v)", "def killGeneric(self, error): print(repr(error)) PythonService.setAutoRestartService(False) print(\"Autorestart of the service disabled.\")", "k, v in confDict.items(): setattr(self, k, v) def killGeneric(self, error):", "self.Service.setAutoRestartService(True) self.confDict = {k: v for k,v in globals().items() if", "#set autorestart to be imune to task swiping on Android", "@author <NAME> @since 10.8.2019 ''' import sys from jnius import", "print(\"Autorestart of the service disabled.\") print(\"Attempting to kill service permanently.\")", "import autoclass from Conf.Conf import * class ServiceBase(): def __init__(self):", "code from execution #both calls are neccesary to avoid \"Scheduling", "to be imune to task swiping on Android 9 self.Service.setAutoRestartService(True)", "of the service disabled.\") print(\"Attempting to kill service permanently.\") PythonService.stop()", "#service takes time to stop. flow thus continues to next", "self.Service = PythonServiceClass.mService #set autorestart to be imune to task", "sys from jnius import autoclass from Conf.Conf import * class", "next block of code #sys.exit() is to prevent subsequent code", "v for k,v in globals().items() if k.isupper() and k.startswith(\"SMS\")} for", "of code #sys.exit() is to prevent subsequent code from execution", "class ServiceBase(): def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context = autoclass('android.content.Context')", "from jnius import autoclass from Conf.Conf import * class ServiceBase():", "sys.exit() #this applies even if we have setAutoRestartService(False) print(\"Exiting python", "= PythonServiceClass.mService #set autorestart to be imune to task swiping", "are neccesary to avoid \"Scheduling restart of crashed service process\"", "applies even if we have setAutoRestartService(False) print(\"Exiting python script\") sys.exit()", "10.8.2019 ''' import sys from jnius import autoclass from Conf.Conf", "from execution #both calls are neccesary to avoid \"Scheduling restart", "Conf.Conf import * class ServiceBase(): def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService')", "* class ServiceBase(): def __init__(self): PythonServiceClass = autoclass('org.kivy.android.PythonService') self.Context =", "PythonService.setAutoRestartService(False) print(\"Autorestart of the service disabled.\") print(\"Attempting to kill service", "Android 9 self.Service.setAutoRestartService(True) self.confDict = {k: v for k,v in", "subsequent code from execution #both calls are neccesary to avoid", "stop. flow thus continues to next block of code #sys.exit()", "9 self.Service.setAutoRestartService(True) self.confDict = {k: v for k,v in globals().items()", "avoid \"Scheduling restart of crashed service process\" #in case we", "restart of crashed service process\" #in case we called only" ]
[ "bootstrap = Bootstrap() def create_app(script_info=None): # instantiate the app app", "__name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set config app_settings = os.getenv(\"APP_SETTINGS\")", "# api/queue/__init__.py import os from flask import Flask from flask_bootstrap", "template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings)", "import Bootstrap # instantiate the extensions bootstrap = Bootstrap() def", "Bootstrap() def create_app(script_info=None): # instantiate the app app = Flask(", "app.config.from_object(app_settings) # set up extensions bootstrap.init_app(app) # register blueprints from", "extensions bootstrap.init_app(app) # register blueprints from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint)", "static_folder=\"../client/static\", ) # set config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) #", "import Flask from flask_bootstrap import Bootstrap # instantiate the extensions", "# instantiate the app app = Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\",", "set config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up extensions", "register blueprints from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) # shell context", "# set config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up", "import os from flask import Flask from flask_bootstrap import Bootstrap", "from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) # shell context for flask", "api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) # shell context for flask cli", "Flask from flask_bootstrap import Bootstrap # instantiate the extensions bootstrap", "the app app = Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) #", "config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up extensions bootstrap.init_app(app)", "blueprints from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) # shell context for", "app.register_blueprint(main_blueprint) # shell context for flask cli app.shell_context_processor({\"app\": app}) return", "create_app(script_info=None): # instantiate the app app = Flask( __name__, template_folder=\"../client/templates\",", "api/queue/__init__.py import os from flask import Flask from flask_bootstrap import", "instantiate the extensions bootstrap = Bootstrap() def create_app(script_info=None): # instantiate", "from flask import Flask from flask_bootstrap import Bootstrap # instantiate", "flask_bootstrap import Bootstrap # instantiate the extensions bootstrap = Bootstrap()", "from flask_bootstrap import Bootstrap # instantiate the extensions bootstrap =", "app = Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set config", "up extensions bootstrap.init_app(app) # register blueprints from api.queue.push.views import main_blueprint", "os from flask import Flask from flask_bootstrap import Bootstrap #", "app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up extensions bootstrap.init_app(app) #", "Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set config app_settings =", "# shell context for flask cli app.shell_context_processor({\"app\": app}) return app", "Bootstrap # instantiate the extensions bootstrap = Bootstrap() def create_app(script_info=None):", "= os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up extensions bootstrap.init_app(app) # register", "flask import Flask from flask_bootstrap import Bootstrap # instantiate the", "# register blueprints from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) # shell", "extensions bootstrap = Bootstrap() def create_app(script_info=None): # instantiate the app", "instantiate the app app = Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", )", "os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set up extensions bootstrap.init_app(app) # register blueprints", "the extensions bootstrap = Bootstrap() def create_app(script_info=None): # instantiate the", ") # set config app_settings = os.getenv(\"APP_SETTINGS\") app.config.from_object(app_settings) # set", "= Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set config app_settings", "set up extensions bootstrap.init_app(app) # register blueprints from api.queue.push.views import", "# instantiate the extensions bootstrap = Bootstrap() def create_app(script_info=None): #", "app app = Flask( __name__, template_folder=\"../client/templates\", static_folder=\"../client/static\", ) # set", "bootstrap.init_app(app) # register blueprints from api.queue.push.views import main_blueprint app.register_blueprint(main_blueprint) #", "# set up extensions bootstrap.init_app(app) # register blueprints from api.queue.push.views", "import main_blueprint app.register_blueprint(main_blueprint) # shell context for flask cli app.shell_context_processor({\"app\":", "main_blueprint app.register_blueprint(main_blueprint) # shell context for flask cli app.shell_context_processor({\"app\": app})", "= Bootstrap() def create_app(script_info=None): # instantiate the app app =", "def create_app(script_info=None): # instantiate the app app = Flask( __name__," ]
[ "empty_engine() serialization_result = engine.serialize() assert isinstance(serialization_result, bytes) engine2 = empty_engine()", "engine0 = empty_engine() with pytest.raises(FileNotFoundError): # We haven't created the", "None def test_deserialize_corrupt(tmpdir): path = str(tmpdir / \"corrupt_cache.dat\") with open(path,", "\"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched", "def test_serde(): engine = empty_engine() serialization_result = engine.serialize() assert isinstance(serialization_result,", "= \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet())", "so we should get an exception # when attempting to", "engine2.deserialize_from_file(path) assert deserialization_result is None def test_deserialize_corrupt(tmpdir): path = str(tmpdir", "isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched def test_serde_file(tmpdir): path = str(tmpdir", "test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia =", "||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking():", "deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result = engine1.serialize_to_file(path) assert serialization_result", "blocker_result_facebook.matched def test_serde_file(tmpdir): path = str(tmpdir / \"cache.dat\") engine0 =", "import pytest SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def", "filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\",", "= empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde():", "\"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet()) def", "def test_serde_file(tmpdir): path = str(tmpdir / \"cache.dat\") engine0 = empty_engine()", "engine.deserialize(b\"abc\") def test_serde(): engine = empty_engine() serialization_result = engine.serialize() assert", "with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine = empty_engine() serialization_result =", "exception # when attempting to deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine()", "str(tmpdir / \"cache.dat\") engine0 = empty_engine() with pytest.raises(FileNotFoundError): # We", "engine2 = empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result is None", "\"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\") as f: f.write(\"abc\") engine =", "engine2 = empty_engine() deserialization_result = engine2.deserialize(serialization_result) assert deserialization_result is None", "engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine = empty_engine() serialization_result", "engine1 = empty_engine() serialization_result = engine1.serialize_to_file(path) assert serialization_result is None", "= empty_engine() with pytest.raises(FileNotFoundError): # We haven't created the cache.dat", "# when attempting to deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result", "adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", )", "= adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert", "SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine(): return", "we should get an exception # when attempting to deserialize.", "path = str(tmpdir / \"cache.dat\") engine0 = empty_engine() with pytest.raises(FileNotFoundError):", "<filename>tests/test_engine.py<gh_stars>10-100 import adblock import pytest SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^", "adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set)", "with pytest.raises(FileNotFoundError): # We haven't created the cache.dat file, so", "str(tmpdir / \"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\") as f: f.write(\"abc\")", "the cache.dat file, so we should get an exception #", "engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result = engine1.serialize_to_file(path) assert serialization_result is", "# We haven't created the cache.dat file, so we should", "assert isinstance(serialization_result, bytes) engine2 = empty_engine() deserialization_result = engine2.deserialize(serialization_result) assert", "f.write(\"abc\") engine = empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\")", "/ \"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\") as f: f.write(\"abc\") engine", "not blocker_result_facebook.matched def test_serde_file(tmpdir): path = str(tmpdir / \"cache.dat\") engine0", "created the cache.dat file, so we should get an exception", "empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result is None def test_deserialize_corrupt(tmpdir):", "with open(path, \"w\", encoding=\"utf-8\") as f: f.write(\"abc\") engine = empty_engine()", "engine = empty_engine() serialization_result = engine.serialize() assert isinstance(serialization_result, bytes) engine2", "= engine1.serialize_to_file(path) assert serialization_result is None engine2 = empty_engine() deserialization_result", "source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook =", "pytest SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine():", "return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine =", "adblock.BlockerResult) assert not blocker_result_facebook.matched def test_serde_file(tmpdir): path = str(tmpdir /", "import adblock import pytest SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^", "serialization_result = engine.serialize() assert isinstance(serialization_result, bytes) engine2 = empty_engine() deserialization_result", "= empty_engine() serialization_result = engine1.serialize_to_file(path) assert serialization_result is None engine2", "adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia,", "assert serialization_result is None engine2 = empty_engine() deserialization_result = engine2.deserialize_from_file(path)", "\"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched def test_serde_file(tmpdir):", "assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert", "blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult)", "engine1.serialize_to_file(path) assert serialization_result is None engine2 = empty_engine() deserialization_result =", "is None def test_deserialize_corrupt(tmpdir): path = str(tmpdir / \"corrupt_cache.dat\") with", "deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result is None def test_deserialize_corrupt(tmpdir): path", "f: f.write(\"abc\") engine = empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError):", "to deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result = engine1.serialize_to_file(path) assert", "engine = empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def", "serialization_result = engine1.serialize_to_file(path) assert serialization_result is None engine2 = empty_engine()", "||old.reddit.com^ ||lobste.rs^ \"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set", "None engine2 = empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result is", "blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook,", "engine.serialize() assert isinstance(serialization_result, bytes) engine2 = empty_engine() deserialization_result = engine2.deserialize(serialization_result)", "test_serde(): engine = empty_engine() serialization_result = engine.serialize() assert isinstance(serialization_result, bytes)", "isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\",", "bytes) engine2 = empty_engine() deserialization_result = engine2.deserialize(serialization_result) assert deserialization_result is", "cache.dat file, so we should get an exception # when", "open(path, \"w\", encoding=\"utf-8\") as f: f.write(\"abc\") engine = empty_engine() with", "filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls(", "empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine", "engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched", "is None engine2 = empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result", "def empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST)", "url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook", "path = str(tmpdir / \"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\") as", "serialization_result is None engine2 = empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert", "haven't created the cache.dat file, so we should get an", "= engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert", "def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia", "when attempting to deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result =", "We haven't created the cache.dat file, so we should get", "= str(tmpdir / \"cache.dat\") engine0 = empty_engine() with pytest.raises(FileNotFoundError): #", "assert not blocker_result_facebook.matched def test_serde_file(tmpdir): path = str(tmpdir / \"cache.dat\")", "= engine.serialize() assert isinstance(serialization_result, bytes) engine2 = empty_engine() deserialization_result =", "= str(tmpdir / \"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\") as f:", "adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\",", "assert deserialization_result is None def test_deserialize_corrupt(tmpdir): path = str(tmpdir /", "test_serde_file(tmpdir): path = str(tmpdir / \"cache.dat\") engine0 = empty_engine() with", "isinstance(serialization_result, bytes) engine2 = empty_engine() deserialization_result = engine2.deserialize(serialization_result) assert deserialization_result", ") assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\",", "\"w\", encoding=\"utf-8\") as f: f.write(\"abc\") engine = empty_engine() with pytest.raises(adblock.DeserializationError):", "request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls(", ") assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched def test_serde_file(tmpdir): path", "\"cache.dat\") engine0 = empty_engine() with pytest.raises(FileNotFoundError): # We haven't created", "with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine =", "\"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True)", "assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert blocker_result_wikipedia.matched blocker_result_facebook = engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\",", "blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult)", "= empty_engine() serialization_result = engine.serialize() assert isinstance(serialization_result, bytes) engine2 =", "deserialization_result is None def test_deserialize_corrupt(tmpdir): path = str(tmpdir / \"corrupt_cache.dat\")", "as f: f.write(\"abc\") engine = empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with", "empty_engine() serialization_result = engine1.serialize_to_file(path) assert serialization_result is None engine2 =", "pytest.raises(FileNotFoundError): # We haven't created the cache.dat file, so we", "= adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\",", "engine.check_network_urls( \"https://facebook.com/directory/img.png\", \"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not", "def test_deserialize_corrupt(tmpdir): path = str(tmpdir / \"corrupt_cache.dat\") with open(path, \"w\",", "= empty_engine() deserialization_result = engine2.deserialize_from_file(path) assert deserialization_result is None def", "||lobste.rs^ \"\"\" def empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set =", "attempting to deserialize. engine0.deserialize_from_file(path) engine1 = empty_engine() serialization_result = engine1.serialize_to_file(path)", "pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path) with pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine = empty_engine()", "an exception # when attempting to deserialize. engine0.deserialize_from_file(path) engine1 =", "assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched def test_serde_file(tmpdir): path =", "pytest.raises(adblock.DeserializationError): engine.deserialize(b\"abc\") def test_serde(): engine = empty_engine() serialization_result = engine.serialize()", "= engine2.deserialize_from_file(path) assert deserialization_result is None def test_deserialize_corrupt(tmpdir): path =", "test_deserialize_corrupt(tmpdir): path = str(tmpdir / \"corrupt_cache.dat\") with open(path, \"w\", encoding=\"utf-8\")", "/ \"cache.dat\") engine0 = empty_engine() with pytest.raises(FileNotFoundError): # We haven't", "empty_engine(): return adblock.Engine(adblock.FilterSet()) def test_engine_creation_and_blocking(): filter_set = adblock.FilterSet(debug=True) filter_set.add_filter_list(SMALL_FILTER_LIST) engine", "= engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", ) assert isinstance(blocker_result_wikipedia, adblock.BlockerResult) assert", "get an exception # when attempting to deserialize. engine0.deserialize_from_file(path) engine1", "engine = adblock.Engine(filter_set=filter_set) blocker_result_wikipedia = engine.check_network_urls( url=\"https://wikipedia.org/img.png\", source_url=\"https://google.com/\", request_type=\"image\", )", "file, so we should get an exception # when attempting", "encoding=\"utf-8\") as f: f.write(\"abc\") engine = empty_engine() with pytest.raises(adblock.DeserializationError): engine.deserialize_from_file(path)", "empty_engine() with pytest.raises(FileNotFoundError): # We haven't created the cache.dat file,", "adblock import pytest SMALL_FILTER_LIST = \"\"\" ||wikipedia.org^ ||old.reddit.com^ ||lobste.rs^ \"\"\"", "should get an exception # when attempting to deserialize. engine0.deserialize_from_file(path)", "\"https://old.reddit.com/r/all\", \"image\", ) assert isinstance(blocker_result_facebook, adblock.BlockerResult) assert not blocker_result_facebook.matched def" ]
[ "from rest_framework.routers import SimpleRouter from .views.upgrade_notice import UpgradeNoticeViewSet router =", "<gh_stars>10-100 from rest_framework.routers import SimpleRouter from .views.upgrade_notice import UpgradeNoticeViewSet router", "from .views.upgrade_notice import UpgradeNoticeViewSet router = SimpleRouter(trailing_slash=False) router.register('upgrade_notice', UpgradeNoticeViewSet, basename='upgrade_notice')", "SimpleRouter from .views.upgrade_notice import UpgradeNoticeViewSet router = SimpleRouter(trailing_slash=False) router.register('upgrade_notice', UpgradeNoticeViewSet,", "import SimpleRouter from .views.upgrade_notice import UpgradeNoticeViewSet router = SimpleRouter(trailing_slash=False) router.register('upgrade_notice',", "rest_framework.routers import SimpleRouter from .views.upgrade_notice import UpgradeNoticeViewSet router = SimpleRouter(trailing_slash=False)" ]
[ "area) while stack: top_of_stack = stack.pop() area = (histogram[top_of_stack] *", "<gh_stars>1000+ ''' Largest rectangle area in a histogram:: Find the", "the largest rectangle can be made of a number of", "def max_area_histogram(histogram): stack = list() max_area = 0 # Initialize", "1) if stack else index)) max_area = max(max_area, area) return", "((index - stack[-1] - 1) if stack else index)) max_area", "simplicity, assume that all bars have same width and the", "can be made of a number of contiguous bars. For", "- 1) if stack else index)) max_area = max(max_area, area)", "the width is 1 unit. ''' def max_area_histogram(histogram): stack =", "else: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index -", "stack.append(index) index += 1 else: top_of_stack = stack.pop() area =", "index)) max_area = max(max_area, area) return max_area hist = [4,", "return max_area hist = [4, 7, 1, 8, 4, 9,", "+= 1 else: top_of_stack = stack.pop() area = (histogram[top_of_stack] *", "= max(max_area, area) while stack: top_of_stack = stack.pop() area =", "rectangle area in a histogram:: Find the largest rectangular area", "if stack else index)) max_area = max(max_area, area) while stack:", "= list() max_area = 0 # Initialize max area index", "max(max_area, area) while stack: top_of_stack = stack.pop() area = (histogram[top_of_stack]", "= 0 while index < len(histogram): if (not stack) or", "[4, 7, 1, 8, 4, 9, 5] print(\"Maximum area is\",", "= (histogram[top_of_stack] * ((index - stack[-1] - 1) if stack", "<= histogram[index]): stack.append(index) index += 1 else: top_of_stack = stack.pop()", "largest rectangular area possible in a given histogram where the", "max_area_histogram(histogram): stack = list() max_area = 0 # Initialize max", "top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1]", "(not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1", "max_area = 0 # Initialize max area index = 0", "area = (histogram[top_of_stack] * ((index - stack[-1] - 1) if", "max_area = max(max_area, area) return max_area hist = [4, 7,", "index = 0 while index < len(histogram): if (not stack)", "possible in a given histogram where the largest rectangle can", "1) if stack else index)) max_area = max(max_area, area) while", "1 unit. ''' def max_area_histogram(histogram): stack = list() max_area =", "area index = 0 while index < len(histogram): if (not", "the largest rectangular area possible in a given histogram where", "a number of contiguous bars. For simplicity, assume that all", "Initialize max area index = 0 while index < len(histogram):", "area) return max_area hist = [4, 7, 1, 8, 4,", "7, 1, 8, 4, 9, 5] print(\"Maximum area is\", max_area_histogram(hist))", "width is 1 unit. ''' def max_area_histogram(histogram): stack = list()", "(histogram[top_of_stack] * ((index - stack[-1] - 1) if stack else", "bars. For simplicity, assume that all bars have same width", "have same width and the width is 1 unit. '''", "while stack: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index", "''' def max_area_histogram(histogram): stack = list() max_area = 0 #", "# Initialize max area index = 0 while index <", "stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] - 1)", "max_area = max(max_area, area) while stack: top_of_stack = stack.pop() area", "= max(max_area, area) return max_area hist = [4, 7, 1,", "that all bars have same width and the width is", "given histogram where the largest rectangle can be made of", "assume that all bars have same width and the width", "a given histogram where the largest rectangle can be made", "number of contiguous bars. For simplicity, assume that all bars", "index)) max_area = max(max_area, area) while stack: top_of_stack = stack.pop()", "list() max_area = 0 # Initialize max area index =", "For simplicity, assume that all bars have same width and", "of contiguous bars. For simplicity, assume that all bars have", "index += 1 else: top_of_stack = stack.pop() area = (histogram[top_of_stack]", "or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1 else: top_of_stack", "if (not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index +=", "Largest rectangle area in a histogram:: Find the largest rectangular", "unit. ''' def max_area_histogram(histogram): stack = list() max_area = 0", "width and the width is 1 unit. ''' def max_area_histogram(histogram):", "in a histogram:: Find the largest rectangular area possible in", "area in a histogram:: Find the largest rectangular area possible", "of a number of contiguous bars. For simplicity, assume that", "0 while index < len(histogram): if (not stack) or (histogram[stack[-1]]", "in a given histogram where the largest rectangle can be", "< len(histogram): if (not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index)", "rectangle can be made of a number of contiguous bars.", "0 # Initialize max area index = 0 while index", "= 0 # Initialize max area index = 0 while", "histogram[index]): stack.append(index) index += 1 else: top_of_stack = stack.pop() area", "len(histogram): if (not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index", "hist = [4, 7, 1, 8, 4, 9, 5] print(\"Maximum", "same width and the width is 1 unit. ''' def", "- stack[-1] - 1) if stack else index)) max_area =", "where the largest rectangle can be made of a number", "Find the largest rectangular area possible in a given histogram", "''' Largest rectangle area in a histogram:: Find the largest", "and the width is 1 unit. ''' def max_area_histogram(histogram): stack", "rectangular area possible in a given histogram where the largest", "largest rectangle can be made of a number of contiguous", "all bars have same width and the width is 1", "else index)) max_area = max(max_area, area) while stack: top_of_stack =", "while index < len(histogram): if (not stack) or (histogram[stack[-1]] <=", "index < len(histogram): if (not stack) or (histogram[stack[-1]] <= histogram[index]):", "if stack else index)) max_area = max(max_area, area) return max_area", "is 1 unit. ''' def max_area_histogram(histogram): stack = list() max_area", "stack else index)) max_area = max(max_area, area) while stack: top_of_stack", "area possible in a given histogram where the largest rectangle", "histogram:: Find the largest rectangular area possible in a given", "made of a number of contiguous bars. For simplicity, assume", "histogram where the largest rectangle can be made of a", "be made of a number of contiguous bars. For simplicity,", "bars have same width and the width is 1 unit.", "a histogram:: Find the largest rectangular area possible in a", "contiguous bars. For simplicity, assume that all bars have same", "(histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1 else: top_of_stack =", "max area index = 0 while index < len(histogram): if", "stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1 else:", "1 else: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index", "stack: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index -", "* ((index - stack[-1] - 1) if stack else index))", "else index)) max_area = max(max_area, area) return max_area hist =", "max(max_area, area) return max_area hist = [4, 7, 1, 8,", "max_area hist = [4, 7, 1, 8, 4, 9, 5]", "= stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] -", "= [4, 7, 1, 8, 4, 9, 5] print(\"Maximum area", "stack = list() max_area = 0 # Initialize max area", "stack else index)) max_area = max(max_area, area) return max_area hist", "stack[-1] - 1) if stack else index)) max_area = max(max_area," ]
[ "c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass,", "== '__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import", "= platform.system() if system == 'Windows': if platform.architecture()[0] == '64bit':", "platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if not libname: raise OSError('Library not", "ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int", "= ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff =", "= ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations, digest, keylen):", "system. system = platform.system() if system == 'Windows': if platform.architecture()[0]", "print(crypto.SSLeay_version(0)) except: pass import platform if platform.python_version_tuple() < ('3', '0',", "== 0: raise ValueError('wrong parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data, salt,", "pbkdf2. This module implements pbkdf2 for Python using crypto lib", "sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3' def", "char *pass, int passlen, # const unsigned char *salt, int", "# PKCS5_PBKDF2_HMAC(const char *pass, int passlen, # const unsigned char", "found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test", "'__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import platform", "hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc) if __name__ ==", "https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: <NAME> <<EMAIL>> :license: LGPLv3 \"\"\"", "This module implements pbkdf2 for Python using crypto lib from", "libname: raise OSError('Library crypto not found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac", "% hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen):", "int keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p,", "or commoncrypto. Note: This module is intended as a plugin", "library ' 'on your system. %s' % e) def pkcs5_pbkdf2_hmac(data,", "e, _ = sys.exc_info() raise ImportError('Cannot find a compatible cryptographic", "crypto not found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC", "ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import platform if platform.python_version_tuple() < ('3',", "crypto lib from openssl or commoncrypto. Note: This module is", "= ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass, int passlen, # const", "('3', '0', '0'): def bytes(*args): return str(args[0]) for h in", "\"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data)", "None: raise ValueError('Unkwnown digest %s' % hashfunc) return crypto_hashfunc def", "iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc) if", "_pbkdf2_hmac(data, salt, iterations, hashfunc, keylen) if err == 0: raise", "raise OSError('Library libeay32 not found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac =", "\"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data))", "= [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype", "ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility elif system", "= ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen =", "[int(x) for x in platform.mac_ver()[0].split('.')] < [10, 7, 0]: raise", "c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p,", "crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None:", "commoncrypto. Note: This module is intended as a plugin replacement", "ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt))", "hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations,", "= ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc,", "% e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None): if hashfunc", "ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded 2->", "= ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen =", "crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations, digest,", "binascii import sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ =", "if not libname: raise OSError('Library not found') crypto = ctypes.CDLL(os.path.basename(libname))", "ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret =", "= ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const", "raise ValueError('Unkwnown digest %s' % hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data,", "crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import platform if platform.python_version_tuple()", "ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations)", "system == 'Windows': if platform.architecture()[0] == '64bit': libname = ctypes.util.find_library('libeay64')", "_pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility except (OSError, AttributeError):", "(1 - ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5,", "ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint,", "import platform if platform.python_version_tuple() < ('3', '0', '0'): def bytes(*args):", "c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt,", "c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) #", "hashlib.sha1 err, c_buff = _pbkdf2_hmac(data, salt, iterations, hashfunc, keylen) if", "= ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype =", "ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen)", "% hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data, salt,", "import sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3'", "= sys.exc_info() raise ImportError('Cannot find a compatible cryptographic library '", "crypto = ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32') if not libname:", "c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return (1 - ret,", "not found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname", "clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: <NAME> <<EMAIL>> :license: LGPLv3", "your system. %s' % e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24,", "binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)) def pbkdf2_bin(data, salt, iterations=1000, keylen=24,", ":license: LGPLv3 \"\"\" import ctypes import ctypes.util import hashlib import", "'64bit': libname = ctypes.util.find_library('libeay64') if not libname: raise OSError('Library not", "return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"Common Crypto", "def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations,", "e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None): if hashfunc is", "by <NAME>. Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright", "import binascii import sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__", "(err, c_buff) try: # check that we have proper OpenSSL", "ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"OpenSSL", "c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype", "ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2 c_pass, c_passlen,", "crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p]", "= hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise ValueError('Unkwnown digest %s'", "hashlib import platform import os.path import binascii import sys __all__", "if crypto_hashfunc is None: raise ValueError('Unkwnown digest %s' % hashfunc)", "# const EVP_MD *digest, # int keylen, unsigned char *out);", "10.7.0' % platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if not libname: raise", "salt, iterations, hashfunc, keylen) if err == 0: raise ValueError('wrong", "salt, iterations, keylen, hashfunc) if __name__ == '__main__': try: crypto.SSLeay_version.restype", "think different(TM)! i.e. break things! if [int(x) for x in", "hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise", "is None: raise ValueError('Unkwnown digest %s' % hashfunc) return crypto_hashfunc", "on the system. system = platform.system() if system == 'Windows':", "_openssl_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc", "system == 'Darwin': # think different(TM)! i.e. break things! if", "OSError('Library libeay32 not found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2", "= ctypes.util.find_library('crypto') if not libname: raise OSError('Library crypto not found.')", "for Python using crypto lib from openssl or commoncrypto. Note:", "[ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret", "hashfunc = hashlib.sha1 err, c_buff = _pbkdf2_hmac(data, salt, iterations, hashfunc,", "pbkdf2.py by <NAME>. Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright:", "ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, #", "crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512:", "pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc) if __name__ == '__main__': try:", "implements pbkdf2 for Python using crypto lib from openssl or", "iterations, keylen, hashfunc)) def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): return", "'0'): def bytes(*args): return str(args[0]) for h in [hashlib.sha1, hashlib.sha224,", "have proper OpenSSL or Common Crypto on the system. system", "return (err, c_buff) try: # check that we have proper", "0: raise ValueError('wrong parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000,", "hashfunc)) def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt,", "iterations, digest, keylen): \"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest))", "passlen, # const unsigned char *salt, int saltlen, int iter,", "_pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto') if not libname:", "keylen): \"\"\"Common Crypto compatibile wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass", "ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass,", "<NAME>. Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c)", "hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc =", "pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen,", "c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter", "= ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt =", "2-> PBKDF2 c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen)", "as a plugin replacement of pbkdf2.py by <NAME>. Git repository:", "*digest, # int keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p,", "hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is", "in platform.mac_ver()[0].split('.')] < [10, 7, 0]: raise OSError('OS X Version", "raise OSError('Library not found') crypto = ctypes.CDLL(libname) else: libname =", "crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"OpenSSL compatibile wrapper", "hashfunc) if __name__ == '__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0))", "const EVP_MD *digest, # int keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes", "hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8') * 11, bytes('salt', 'utf-8'), hashfunc=h)))", "Python using crypto lib from openssl or commoncrypto. Note: This", "else: libname = ctypes.util.find_library('libeay32') if not libname: raise OSError('Library libeay32", "libname: raise OSError('Library not found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac =", "if err == 0: raise ValueError('wrong parameters') return c_buff.raw[:keylen] def", "find a compatible cryptographic library ' 'on your system. %s'", "is None: raise ValueError('Unkwnown digest %s' % hashfunc) crypto_hashfunc.restype =", "= ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map", "digest %s' % hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations,", "hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise ValueError('Unkwnown digest %s' %", "c_iter, c_hashfunc, c_keylen, c_buff) return (err, c_buff) try: # check", "hardcoded 2-> PBKDF2 c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff,", "EVP_MD *digest, # int keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes =", "= _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility except (OSError, AttributeError): _,", "if not libname: raise OSError('Library crypto not found.') crypto =", "libname = ctypes.util.find_library('crypto') if not libname: raise OSError('Library crypto not", "= {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384:", "OSError('OS X Version too old %s < 10.7.0' % platform.mac_ver()[0])", "' 'on your system. %s' % e) def pkcs5_pbkdf2_hmac(data, salt,", "# int keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int,", "char *salt, int saltlen, int iter, # const EVP_MD *digest,", "plugin replacement of pbkdf2.py by <NAME>. Git repository: $ git", "pbkdf2 for Python using crypto lib from openssl or commoncrypto.", "not found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC #", "ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations)", "c_iter, c_buff, c_keylen) return (1 - ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc):", "keylen): \"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass =", "module is intended as a plugin replacement of pbkdf2.py by", "Crypto compatibile wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data)", "# hardcoded 2-> PBKDF2 c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter,", "keylen, hashfunc)) def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data,", "wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen =", "x in platform.mac_ver()[0].split('.')] < [10, 7, 0]: raise OSError('OS X", "ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err =", "_openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility except (OSError, AttributeError): _, e,", "platform if platform.python_version_tuple() < ('3', '0', '0'): def bytes(*args): return", "salt, iterations, digest, keylen): \"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc =", "digest, keylen): \"\"\"Common Crypto compatibile wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest))", "pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen,", "if [int(x) for x in platform.mac_ver()[0].split('.')] < [10, 7, 0]:", "< [10, 7, 0]: raise OSError('OS X Version too old", "int saltlen, int iter, # const EVP_MD *digest, # int", "int iter, # const EVP_MD *digest, # int keylen, unsigned", "that we have proper OpenSSL or Common Crypto on the", "ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen,", "Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013:", "LGPLv3 \"\"\" import ctypes import ctypes.util import hashlib import platform", "OSError('Library not found') crypto = ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32')", "This module is intended as a plugin replacement of pbkdf2.py", "return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc) if __name__ == '__main__':", "err == 0: raise ValueError('wrong parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data,", "crypto.PKCS5_PBKDF2_HMAC # test compatibility except (OSError, AttributeError): _, e, _", "crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff) return (err,", "{hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384,", "pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This module implements pbkdf2 for Python", "salt, iterations=1000, keylen=24, hashfunc=None): if hashfunc is None: hashfunc =", "not libname: raise OSError('Library libeay32 not found.') crypto = ctypes.CDLL(libname)", "= hashlib.sha1 err, c_buff = _pbkdf2_hmac(data, salt, iterations, hashfunc, keylen)", "'0', '0'): def bytes(*args): return str(args[0]) for h in [hashlib.sha1,", "or Common Crypto on the system. system = platform.system() if", "crypto_hashfunc is None: raise ValueError('Unkwnown digest %s' % hashfunc) crypto_hashfunc.restype", "raise ValueError('wrong parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000, keylen=24,", "crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise ValueError('Unkwnown", "= ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32,", "ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen)", "salt, iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc))", "keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc) if __name__", "hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if", "ctypes.util.find_library('libeay32') if not libname: raise OSError('Library libeay32 not found.') crypto", "def _openssl_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"OpenSSL compatibile wrapper \"\"\"", "const unsigned char *salt, int saltlen, int iter, # const", "ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt)", "PBKDF2 c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return", "not found') crypto = ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32') if", "def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256,", "we have proper OpenSSL or Common Crypto on the system.", "ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen,", "# test compatibility except (OSError, AttributeError): _, e, _ =", "platform.python_version_tuple() < ('3', '0', '0'): def bytes(*args): return str(args[0]) for", "OSError('Library not found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else:", "iterations, hashfunc, keylen) if err == 0: raise ValueError('wrong parameters')", "libname = ctypes.util.find_library('libeay64') if not libname: raise OSError('Library not found')", "-*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This module implements pbkdf2", "%s' % hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() def _openssl_pbkdf2(data,", "try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import platform if", "\"\"\"Common Crypto compatibile wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass =", "# check that we have proper OpenSSL or Common Crypto", "ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2", "ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen)", "_openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility elif system == 'Darwin': #", "< 10.7.0' % platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if not libname:", "ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto') if not", "if __name__ == '__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except:", "hashfunc, keylen) if err == 0: raise ValueError('wrong parameters') return", "unsigned char *salt, int saltlen, int iter, # const EVP_MD", "ctypes import ctypes.util import hashlib import platform import os.path import", "is intended as a plugin replacement of pbkdf2.py by <NAME>.", "== 'Darwin': # think different(TM)! i.e. break things! if [int(x)", "iterations, keylen, hashfunc) if __name__ == '__main__': try: crypto.SSLeay_version.restype =", "keylen, hashfunc) if __name__ == '__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p", "digest, keylen): \"\"\"OpenSSL compatibile wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass", "ctypes.util.find_library('crypto') if not libname: raise OSError('Library crypto not found.') crypto", "None: raise ValueError('Unkwnown digest %s' % hashfunc) crypto_hashfunc.restype = ctypes.c_void_p", "not libname: raise OSError('Library crypto not found.') crypto = ctypes.CDLL(os.path.basename(libname))", "1, hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc", "not libname: raise OSError('Library not found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac", "crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility", "= _pbkdf2_hmac(data, salt, iterations, hashfunc, keylen) if err == 0:", "= ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes =", "iterations, digest, keylen): \"\"\"Common Crypto compatibile wrapper \"\"\" c_hashfunc =", "ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded", "for h in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8')", "things! if [int(x) for x in platform.mac_ver()[0].split('.')] < [10, 7,", "Fast pbkdf2. This module implements pbkdf2 for Python using crypto", "old %s < 10.7.0' % platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if", "c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen", "saltlen, int iter, # const EVP_MD *digest, # int keylen,", "compatible cryptographic library ' 'on your system. %s' % e)", "def bytes(*args): return str(args[0]) for h in [hashlib.sha1, hashlib.sha224, hashlib.sha256,", "keylen) if err == 0: raise ValueError('wrong parameters') return c_buff.raw[:keylen]", "return crypto_hashfunc() def _openssl_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"OpenSSL compatibile", "= ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff =", "c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt", "*out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int,", "Version too old %s < 10.7.0' % platform.mac_ver()[0]) libname =", "% platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if not libname: raise OSError('Library", "ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen,", "c_keylen = ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes", "pass import platform if platform.python_version_tuple() < ('3', '0', '0'): def", "== 'Windows': if platform.architecture()[0] == '64bit': libname = ctypes.util.find_library('libeay64') if", "c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff) return (err, c_buff)", "if platform.python_version_tuple() < ('3', '0', '0'): def bytes(*args): return str(args[0])", "= ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt =", "ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen)", "= ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass, int", "= '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224: 2,", "c_keylen) return (1 - ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map =", "AttributeError): _, e, _ = sys.exc_info() raise ImportError('Cannot find a", "Crypto on the system. system = platform.system() if system ==", "[hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8') * 11, bytes('salt',", "hashfunc=None): if hashfunc is None: hashfunc = hashlib.sha1 err, c_buff", "intended as a plugin replacement of pbkdf2.py by <NAME>. Git", "except: pass import platform if platform.python_version_tuple() < ('3', '0', '0'):", "c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff) return (err, c_buff) try:", "crypto_hashfunc is None: raise ValueError('Unkwnown digest %s' % hashfunc) return", "test compatibility elif system == 'Darwin': # think different(TM)! i.e.", "c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return (1", "[ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype =", "<<EMAIL>> :license: LGPLv3 \"\"\" import ctypes import ctypes.util import hashlib", "# const unsigned char *salt, int saltlen, int iter, #", "in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8') * 11,", "= [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t]", "libname: raise OSError('Library libeay32 not found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac", "c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass, int passlen, #", "_ = sys.exc_info() raise ImportError('Cannot find a compatible cryptographic library", "# think different(TM)! i.e. break things! if [int(x) for x", "import hashlib import platform import os.path import binascii import sys", "hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224,", "= ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility elif", "found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test", "cryptographic library ' 'on your system. %s' % e) def", "proper OpenSSL or Common Crypto on the system. system =", "ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt,", "crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc", "ctypes.util.find_library('System') if not libname: raise OSError('Library not found') crypto =", "def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None): if hashfunc is None:", "return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)) def pbkdf2_bin(data, salt, iterations=1000,", "'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1:", "unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int,", "found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname =", "salt, iterations, digest, keylen): \"\"\"Common Crypto compatibile wrapper \"\"\" c_hashfunc", "compatibile wrapper \"\"\" c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen", "{hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512: 5}", "crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2 c_pass, c_passlen, c_salt, c_saltlen, c_hashfunc,", "the system. system = platform.system() if system == 'Windows': if", "char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p,", "_commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"Common Crypto compatibile wrapper \"\"\"", "iter, # const EVP_MD *digest, # int keylen, unsigned char", "hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise", "= ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen =", "X Version too old %s < 10.7.0' % platform.mac_ver()[0]) libname", "a plugin replacement of pbkdf2.py by <NAME>. Git repository: $", "c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen", "_openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224:", "return (1 - ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5:", "= ctypes.util.find_library('libeay32') if not libname: raise OSError('Library libeay32 not found.')", "*salt, int saltlen, int iter, # const EVP_MD *digest, #", "os.path import binascii import sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex']", "if hashfunc is None: hashfunc = hashlib.sha1 err, c_buff =", "ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p,", "hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8') * 11, bytes('salt', 'utf-8'),", "# test compatibility elif system == 'Darwin': # think different(TM)!", "check that we have proper OpenSSL or Common Crypto on", "raise OSError('Library not found') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2", "-*- coding: utf-8 -*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This", "Common Crypto on the system. system = platform.system() if system", "c_passlen, c_salt, c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return (1 -", "return str(args[0]) for h in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]:", "utf-8 -*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This module implements", "= crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2 c_pass, c_passlen, c_salt, c_saltlen,", "repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: <NAME>", "%s < 10.7.0' % platform.mac_ver()[0]) libname = ctypes.util.find_library('System') if not", "hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"Common", "ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2,", "ValueError('wrong parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None):", "ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt)", "bytes(*args): return str(args[0]) for h in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384,", "import ctypes import ctypes.util import hashlib import platform import os.path", "crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto')", "libname = ctypes.util.find_library('libeay32') if not libname: raise OSError('Library libeay32 not", "using crypto lib from openssl or commoncrypto. Note: This module", "salt, iterations, keylen, hashfunc)) def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):", "None: hashfunc = hashlib.sha1 err, c_buff = _pbkdf2_hmac(data, salt, iterations,", "return c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data,", "iterations=1000, keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)) def", "elif system == 'Darwin': # think different(TM)! i.e. break things!", "# -*- coding: utf-8 -*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2.", "hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is", "c_keylen, c_buff) return (err, c_buff) try: # check that we", "ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2 c_pass, c_passlen, c_salt,", "\"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This module implements pbkdf2 for", "crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc", "lib from openssl or commoncrypto. Note: This module is intended", "ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1,", "system = platform.system() if system == 'Windows': if platform.architecture()[0] ==", "crypto.PKCS5_PBKDF2_HMAC # test compatibility elif system == 'Darwin': # think", "ctypes.c_size_t(keylen) c_buff = ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32,", "__version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224:", "Copyright (c) 2013: <NAME> <<EMAIL>> :license: LGPLv3 \"\"\" import ctypes", "h in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret', 'utf-8') *", "hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if", "ValueError('Unkwnown digest %s' % hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt,", "= crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff) return", "== '64bit': libname = ctypes.util.find_library('libeay64') if not libname: raise OSError('Library", "_, e, _ = sys.exc_info() raise ImportError('Cannot find a compatible", "c_passlen = ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter", "3, hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc", "crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter,", "i.e. break things! if [int(x) for x in platform.mac_ver()[0].split('.')] <", "module implements pbkdf2 for Python using crypto lib from openssl", "[10, 7, 0]: raise OSError('OS X Version too old %s", "'pbkdf2_hex'] __version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1,", "%s' % hashfunc) return crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations, digest,", "c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen = ctypes.c_size_t(keylen) c_buff", "0]: raise OSError('OS X Version too old %s < 10.7.0'", "of pbkdf2.py by <NAME>. Git repository: $ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git", "libname = ctypes.util.find_library('System') if not libname: raise OSError('Library not found')", "crypto_hashfunc def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"Common Crypto compatibile", "ctypes.util import hashlib import platform import os.path import binascii import", "= ctypes.util.find_library('libeay64') if not libname: raise OSError('Library not found') crypto", "= ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_int(len(salt)) c_iter =", "= ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter =", "else: libname = ctypes.util.find_library('crypto') if not libname: raise OSError('Library crypto", "c_buff) return (err, c_buff) try: # check that we have", "5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise ValueError('Unkwnown", "parameters') return c_buff.raw[:keylen] def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): return", "salt, iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)", "git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: <NAME> <<EMAIL>> :license:", "try: # check that we have proper OpenSSL or Common", "7, 0]: raise OSError('OS X Version too old %s <", "ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int", "if system == 'Windows': if platform.architecture()[0] == '64bit': libname =", "not found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC #", "libname: raise OSError('Library not found') crypto = ctypes.CDLL(libname) else: libname", "<reponame>Cwlowe/web2py # -*- coding: utf-8 -*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast", "hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)) def pbkdf2_bin(data, salt,", "= ctypes.util.find_library('System') if not libname: raise OSError('Library not found') crypto", "c_hashfunc = ctypes.c_uint32(_commoncrypto_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt", "(OSError, AttributeError): _, e, _ = sys.exc_info() raise ImportError('Cannot find", "pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None): if hashfunc is None: hashfunc", "~~~~~~ Fast pbkdf2. This module implements pbkdf2 for Python using", "ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass, int passlen,", "ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p] crypto.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int err", "2013: <NAME> <<EMAIL>> :license: LGPLv3 \"\"\" import ctypes import ctypes.util", "= ctypes.create_string_buffer(keylen) crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t,", "compatibile wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen", "hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc =", "raise OSError('OS X Version too old %s < 10.7.0' %", "- ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1:", "c_buff, c_keylen) return (1 - ret, c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map", ":copyright: Copyright (c) 2013: <NAME> <<EMAIL>> :license: LGPLv3 \"\"\" import", "def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None): return pkcs5_pbkdf2_hmac(data, salt, iterations,", "if platform.architecture()[0] == '64bit': libname = ctypes.util.find_library('libeay64') if not libname:", "raise OSError('Library crypto not found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac =", "not libname: raise OSError('Library not found') crypto = ctypes.CDLL(libname) else:", "platform import os.path import binascii import sys __all__ = ['pkcs5_pbkdf2_hmac',", "$ git clone https://github.com/michele-comitini/pbkdf2_ctypes.git :copyright: Copyright (c) 2013: <NAME> <<EMAIL>>", "keylen, unsigned char *out); crypto.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_int,", "different(TM)! i.e. break things! if [int(x) for x in platform.mac_ver()[0].split('.')]", "keylen=24, hashfunc=None): if hashfunc is None: hashfunc = hashlib.sha1 err,", "openssl or commoncrypto. Note: This module is intended as a", "ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32') if not libname: raise OSError('Library", "_commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384:", "'on your system. %s' % e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000,", "platform.system() if system == 'Windows': if platform.architecture()[0] == '64bit': libname", "str(args[0]) for h in [hashlib.sha1, hashlib.sha224, hashlib.sha256, hashlib.sha384, hashlib.sha512]: print(binascii.hexlify(pkcs5_pbkdf2_hmac(bytes('secret',", "= ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto') if", "digest %s' % hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc() def", "_pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility elif system ==", "break things! if [int(x) for x in platform.mac_ver()[0].split('.')] < [10,", "= _commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto') if not libname: raise", "import platform import os.path import binascii import sys __all__ =", "ctypes.util.find_library('libeay64') if not libname: raise OSError('Library not found') crypto =", "system. %s' % e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None):", "*pass, int passlen, # const unsigned char *salt, int saltlen,", "def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256: 3,", "'Windows': if platform.architecture()[0] == '64bit': libname = ctypes.util.find_library('libeay64') if not", "keylen=24, hashfunc=None): return binascii.hexlify(pkcs5_pbkdf2_hmac(data, salt, iterations, keylen, hashfunc)) def pbkdf2_bin(data,", "int passlen, # const unsigned char *salt, int saltlen, int", "= ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility except", "%s' % e) def pkcs5_pbkdf2_hmac(data, salt, iterations=1000, keylen=24, hashfunc=None): if", "if not libname: raise OSError('Library not found') crypto = ctypes.CDLL(libname)", "= ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32') if not libname: raise", "crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None: raise ValueError('Unkwnown digest", "sys.exc_info() raise ImportError('Cannot find a compatible cryptographic library ' 'on", "wrapper \"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen =", "except (OSError, AttributeError): _, e, _ = sys.exc_info() raise ImportError('Cannot", "< ('3', '0', '0'): def bytes(*args): return str(args[0]) for h", "compatibility elif system == 'Darwin': # think different(TM)! i.e. break", "found') crypto = ctypes.CDLL(libname) else: libname = ctypes.util.find_library('libeay32') if not", "def _commoncrypto_pbkdf2(data, salt, iterations, digest, keylen): \"\"\"Common Crypto compatibile wrapper", "replacement of pbkdf2.py by <NAME>. Git repository: $ git clone", "OpenSSL or Common Crypto on the system. system = platform.system()", "'0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256:", "\"\"\" c_hashfunc = ctypes.c_void_p(_openssl_hashlib_to_crypto_map_get(digest)) c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data))", "(c) 2013: <NAME> <<EMAIL>> :license: LGPLv3 \"\"\" import ctypes import", "ctypes.c_char_p(data) c_passlen = ctypes.c_size_t(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt))", "err, c_buff = _pbkdf2_hmac(data, salt, iterations, hashfunc, keylen) if err", "compatibility except (OSError, AttributeError): _, e, _ = sys.exc_info() raise", "platform.mac_ver()[0].split('.')] < [10, 7, 0]: raise OSError('OS X Version too", "crypto.CCKeyDerivationPBKDF.restype = ctypes.c_int crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t,", "c_buff) try: # check that we have proper OpenSSL or", "= ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass import platform if platform.python_version_tuple() <", "4, hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc) if crypto_hashfunc is None:", "for x in platform.mac_ver()[0].split('.')] < [10, 7, 0]: raise OSError('OS", "raise ValueError('Unkwnown digest %s' % hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return", "= ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen =", "platform.architecture()[0] == '64bit': libname = ctypes.util.find_library('libeay64') if not libname: raise", "ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char *pass, int passlen, # const unsigned", "c_buff) def _openssl_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map = {hashlib.md5: crypto.EVP_md5, hashlib.sha1: crypto.EVP_sha1, hashlib.sha256:", "__name__ == '__main__': try: crypto.SSLeay_version.restype = ctypes.c_char_p print(crypto.SSLeay_version(0)) except: pass", "from openssl or commoncrypto. Note: This module is intended as", "hashlib.sha1: crypto.EVP_sha1, hashlib.sha256: crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512}", "['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc): hashlib_to_crypto_map =", "= {hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512:", "err = crypto.PKCS5_PBKDF2_HMAC(c_pass, c_passlen, c_salt, c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff)", "is None: hashfunc = hashlib.sha1 err, c_buff = _pbkdf2_hmac(data, salt,", "OSError('Library crypto not found.') crypto = ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2", "raise ImportError('Cannot find a compatible cryptographic library ' 'on your", "PKCS5_PBKDF2_HMAC(const char *pass, int passlen, # const unsigned char *salt,", "hashfunc is None: hashfunc = hashlib.sha1 err, c_buff = _pbkdf2_hmac(data,", "c_hashfunc, c_keylen, c_buff) return (err, c_buff) try: # check that", "<NAME> <<EMAIL>> :license: LGPLv3 \"\"\" import ctypes import ctypes.util import", "ImportError('Cannot find a compatible cryptographic library ' 'on your system.", "coding: utf-8 -*- \"\"\" pbkdf2_ctypes ~~~~~~ Fast pbkdf2. This module", "import os.path import binascii import sys __all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin',", "crypto.CCKeyDerivationPBKDF.argtypes = [ctypes.c_uint32, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint, ctypes.c_char_p,", "ctypes.c_char_p, ctypes.c_size_t] ret = crypto.CCKeyDerivationPBKDF(2, # hardcoded 2-> PBKDF2 c_pass,", "import ctypes.util import hashlib import platform import os.path import binascii", "iterations=1000, keylen=24, hashfunc=None): if hashfunc is None: hashfunc = hashlib.sha1", "too old %s < 10.7.0' % platform.mac_ver()[0]) libname = ctypes.util.find_library('System')", "ValueError('Unkwnown digest %s' % hashfunc) crypto_hashfunc.restype = ctypes.c_void_p return crypto_hashfunc()", "ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff = ctypes.create_string_buffer(keylen) # PKCS5_PBKDF2_HMAC(const char", "hashlib_to_crypto_map = {hashlib.sha1: 1, hashlib.sha224: 2, hashlib.sha256: 3, hashlib.sha384: 4,", "= _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility elif system == 'Darwin':", "c_buff = _pbkdf2_hmac(data, salt, iterations, hashfunc, keylen) if err ==", "2, hashlib.sha256: 3, hashlib.sha384: 4, hashlib.sha512: 5} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)", "c_salt = ctypes.c_char_p(salt) c_saltlen = ctypes.c_size_t(len(salt)) c_iter = ctypes.c_uint(iterations) c_keylen", "crypto = ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility", "crypto.EVP_sha256, hashlib.sha224: crypto.EVP_sha224, hashlib.sha384: crypto.EVP_sha384, hashlib.sha512: crypto.EVP_sha512} crypto_hashfunc = hashlib_to_crypto_map.get(hashfunc)", "ctypes.CDLL(os.path.basename(libname)) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC # test compatibility except (OSError,", "c_saltlen = ctypes.c_int(len(salt)) c_iter = ctypes.c_int(iterations) c_keylen = ctypes.c_int(keylen) c_buff", "test compatibility except (OSError, AttributeError): _, e, _ = sys.exc_info()", "'Darwin': # think different(TM)! i.e. break things! if [int(x) for", "_commoncrypto_pbkdf2 else: libname = ctypes.util.find_library('crypto') if not libname: raise OSError('Library", "c_pass = ctypes.c_char_p(data) c_passlen = ctypes.c_int(len(data)) c_salt = ctypes.c_char_p(salt) c_saltlen", "__all__ = ['pkcs5_pbkdf2_hmac', 'pbkdf2_bin', 'pbkdf2_hex'] __version__ = '0.99.3' def _commoncrypto_hashlib_to_crypto_map_get(hashfunc):", "c_hashfunc, c_iter, c_buff, c_keylen) return (1 - ret, c_buff) def", "if not libname: raise OSError('Library libeay32 not found.') crypto =", "c_saltlen, c_hashfunc, c_iter, c_buff, c_keylen) return (1 - ret, c_buff)", "\"\"\" import ctypes import ctypes.util import hashlib import platform import", "Note: This module is intended as a plugin replacement of", "a compatible cryptographic library ' 'on your system. %s' %", "libeay32 not found.') crypto = ctypes.CDLL(libname) _pbkdf2_hmac = _openssl_pbkdf2 crypto.PKCS5_PBKDF2_HMAC", "c_saltlen, c_iter, c_hashfunc, c_keylen, c_buff) return (err, c_buff) try: #" ]
[ "= cursor.fetchall() if len(res) == 0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048,", "psycopg2 import base64 from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric", "cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped old keys\") else: print(\"Invalid option!", "with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as conn: with conn.cursor() as", "generated!\") elif sys.argv[1] == \"generate_if_needed\": #Load the key or generate", "user='auth_db' host='authdb' [redacted-2]\") as conn: with conn.cursor() as cursor: if", "KEY)\") cursor.execute(\"SELECT * FROM key\") res = cursor.fetchall() if len(res)", "psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as conn: with conn.cursor() as cursor:", "os import psycopg2 import base64 from cryptography.hazmat.primitives import serialization, hashes", "sys import os import psycopg2 import base64 from cryptography.hazmat.primitives import", "import os import psycopg2 import base64 from cryptography.hazmat.primitives import serialization,", "\"drop\": cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped old keys\") else: print(\"Invalid", "#Load the key or generate a new one: cursor.execute(\"CREATE TABLE", "as conn: with conn.cursor() as cursor: if sys.argv[1] == \"generate\":", "pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New", "import psycopg2 import base64 from cryptography.hazmat.primitives import serialization, hashes from", "as database was empty!\") else: print(\"Database has key ready!\") elif", "TABLE IF NOT EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY", "remove as a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\")", "was empty!\") else: print(\"Database has key ready!\") elif sys.argv[1] ==", "has key ready!\") elif sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE key\")", "or generate a new one: cursor.execute(\"CREATE TABLE IF NOT EXISTS", "as a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as", "rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time)", "cursor.execute(\"SELECT * FROM key\") res = cursor.fetchall() if len(res) ==", "import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends", "PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption())", "[redacted-2]\") as conn: with conn.cursor() as cursor: if sys.argv[1] ==", "\"generate\": #Load the key or generate a new one: cursor.execute(\"CREATE", "key or generate a new one: cursor.execute(\"CREATE TABLE IF NOT", "elif sys.argv[1] == \"generate_if_needed\": #Load the key or generate a", "either create or remove as a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db'", "(key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048,", "len(sys.argv) < 2: print(\"Please enter either create or remove as", "a new one: cursor.execute(\"CREATE TABLE IF NOT EXISTS key (key", "database was empty!\") else: print(\"Database has key ready!\") elif sys.argv[1]", "== \"generate\": #Load the key or generate a new one:", "EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT *", "bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT * FROM key\") res =", "key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\")", "backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit()", "cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated, as", "cursor.execute(\"CREATE TABLE IF NOT EXISTS key (key varchar(4096),time bigint UNIQUE", "cursor.fetchall() if len(res) == 0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())", "IF NOT EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\")", "cursor: if sys.argv[1] == \"generate\": #Load the key or generate", "with conn.cursor() as cursor: if sys.argv[1] == \"generate\": #Load the", "= privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key", "new one: cursor.execute(\"CREATE TABLE IF NOT EXISTS key (key varchar(4096),time", "< 2: print(\"Please enter either create or remove as a", "TABLE key\") conn.commit() print(\"Dropped old keys\") else: print(\"Invalid option! Try", "KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT", "elif sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped old", "\"generate_if_needed\": #Load the key or generate a new one: cursor.execute(\"CREATE", "if sys.argv[1] == \"generate\": #Load the key or generate a", "conn.commit() print(\"New key generated!\") elif sys.argv[1] == \"generate_if_needed\": #Load the", "INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\") elif sys.argv[1]", "conn.cursor() as cursor: if sys.argv[1] == \"generate\": #Load the key", "if len(res) == 0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem", "import base64 from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import", "hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends import default_backend", "old keys\") else: print(\"Invalid option! Try 'drop', 'generate' or 'generate_if_needed'...\")", "NOT EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT", "rsa from cryptography.hazmat.backends import default_backend import time if len(sys.argv) <", "one: cursor.execute(\"CREATE TABLE IF NOT EXISTS key (key varchar(4096),time bigint", "print(\"New key generated!\") elif sys.argv[1] == \"generate_if_needed\": #Load the key", "= rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key", "== \"generate_if_needed\": #Load the key or generate a new one:", "a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as conn:", "sys.argv[1] == \"generate\": #Load the key or generate a new", "print(\"Dropped old keys\") else: print(\"Invalid option! Try 'drop', 'generate' or", "cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\") elif", "import sys import os import psycopg2 import base64 from cryptography.hazmat.primitives", "print(\"New key generated, as database was empty!\") else: print(\"Database has", "cryptography.hazmat.backends import default_backend import time if len(sys.argv) < 2: print(\"Please", "== 0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption())", "PRIMARY KEY)\") cursor.execute(\"SELECT * FROM key\") res = cursor.fetchall() if", "if len(sys.argv) < 2: print(\"Please enter either create or remove", "(key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT * FROM key\")", "privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\")", "NOT EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") privkey", "empty!\") else: print(\"Database has key ready!\") elif sys.argv[1] == \"drop\":", "else: print(\"Database has key ready!\") elif sys.argv[1] == \"drop\": cursor.execute(\"DROP", "* FROM key\") res = cursor.fetchall() if len(res) == 0:", "generated, as database was empty!\") else: print(\"Database has key ready!\")", "(key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated, as database was empty!\")", "EXISTS key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") privkey =", "key generated!\") elif sys.argv[1] == \"generate_if_needed\": #Load the key or", "key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated, as database was", "default_backend import time if len(sys.argv) < 2: print(\"Please enter either", "print(\"Please enter either create or remove as a argv[1]\") sys.exit(0)", "bigint UNIQUE PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem", "as cursor: if sys.argv[1] == \"generate\": #Load the key or", "create or remove as a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db'", "sys.argv[1] == \"generate_if_needed\": #Load the key or generate a new", "conn.commit() print(\"New key generated, as database was empty!\") else: print(\"Database", "privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO", "ready!\") elif sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped", "0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT", "import default_backend import time if len(sys.argv) < 2: print(\"Please enter", "from cryptography.hazmat.backends import default_backend import time if len(sys.argv) < 2:", "len(res) == 0: privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem =", "cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends import default_backend import time", "padding, rsa from cryptography.hazmat.backends import default_backend import time if len(sys.argv)", "time if len(sys.argv) < 2: print(\"Please enter either create or", "argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as conn: with", "host='authdb' [redacted-2]\") as conn: with conn.cursor() as cursor: if sys.argv[1]", "from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends import default_backend import", "sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped old keys\")", "varchar(4096),time bigint UNIQUE PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())", "(key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\") elif sys.argv[1] == \"generate_if_needed\":", "or remove as a argv[1]\") sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb'", "serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from cryptography.hazmat.backends import", "key ready!\") elif sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE key\") conn.commit()", "key\") conn.commit() print(\"Dropped old keys\") else: print(\"Invalid option! Try 'drop',", "enter either create or remove as a argv[1]\") sys.exit(0) with", "VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated, as database was empty!\") else:", "cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa from", "2: print(\"Please enter either create or remove as a argv[1]\")", "VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\") elif sys.argv[1] == \"generate_if_needed\": #Load", "the key or generate a new one: cursor.execute(\"CREATE TABLE IF", "res = cursor.fetchall() if len(res) == 0: privkey = rsa.generate_private_key(public_exponent=65537,", "conn.commit() print(\"Dropped old keys\") else: print(\"Invalid option! Try 'drop', 'generate'", "== \"drop\": cursor.execute(\"DROP TABLE key\") conn.commit() print(\"Dropped old keys\") else:", "varchar(4096),time bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT * FROM key\") res", "generate a new one: cursor.execute(\"CREATE TABLE IF NOT EXISTS key", "base64 from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding,", "privkey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.TraditionalOpenSSL,encryption_algorithm=serialization.NoEncryption()) cursor.execute(\"INSERT INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated,", "key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated!\") elif sys.argv[1] ==", "import padding, rsa from cryptography.hazmat.backends import default_backend import time if", "import time if len(sys.argv) < 2: print(\"Please enter either create", "INTO key (key,time) VALUES('\"+str(pem.decode(\"utf-8\"))+\"',\"+str(int(time.time()))+\")\") conn.commit() print(\"New key generated, as database", "sys.exit(0) with psycopg2.connect(\"dbname='auth_db' user='auth_db' host='authdb' [redacted-2]\") as conn: with conn.cursor()", "UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT * FROM key\") res = cursor.fetchall()", "conn: with conn.cursor() as cursor: if sys.argv[1] == \"generate\": #Load", "FROM key\") res = cursor.fetchall() if len(res) == 0: privkey", "from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding, rsa", "key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") cursor.execute(\"SELECT * FROM", "key (key varchar(4096),time bigint UNIQUE PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537,", "key\") res = cursor.fetchall() if len(res) == 0: privkey =", "print(\"Database has key ready!\") elif sys.argv[1] == \"drop\": cursor.execute(\"DROP TABLE", "UNIQUE PRIMARY KEY)\") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pem =", "key generated, as database was empty!\") else: print(\"Database has key" ]
[ "Copyright <NAME> 2004. Distributed under the Boost # Software License,", "# file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import", "Boost # Software License, Version 1.0. (See accompanying # file", "https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type def register (): type.register_type ('OBJ',", "import type def register (): type.register_type ('OBJ', ['obj'], None, ['NT',", "under the Boost # Software License, Version 1.0. (See accompanying", "License, Version 1.0. (See accompanying # file LICENSE.txt or copy", "1.0. (See accompanying # file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt)", "LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type def", "from b2.build import type def register (): type.register_type ('OBJ', ['obj'],", "file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type", "Software License, Version 1.0. (See accompanying # file LICENSE.txt or", "at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type def register (): type.register_type", "<filename>src/tools/types/obj.py<gh_stars>100-1000 # Copyright <NAME> 2004. Distributed under the Boost #", "type def register (): type.register_type ('OBJ', ['obj'], None, ['NT', 'CYGWIN'])", "# Copyright <NAME> 2004. Distributed under the Boost # Software", "(): type.register_type ('OBJ', ['obj'], None, ['NT', 'CYGWIN']) type.register_type ('OBJ', ['o'])", "Distributed under the Boost # Software License, Version 1.0. (See", "(See accompanying # file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from", "Version 1.0. (See accompanying # file LICENSE.txt or copy at", "def register (): type.register_type ('OBJ', ['obj'], None, ['NT', 'CYGWIN']) type.register_type", "the Boost # Software License, Version 1.0. (See accompanying #", "accompanying # file LICENSE.txt or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build", "2004. Distributed under the Boost # Software License, Version 1.0.", "<NAME> 2004. Distributed under the Boost # Software License, Version", "# Software License, Version 1.0. (See accompanying # file LICENSE.txt", "b2.build import type def register (): type.register_type ('OBJ', ['obj'], None,", "register (): type.register_type ('OBJ', ['obj'], None, ['NT', 'CYGWIN']) type.register_type ('OBJ',", "or copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type def register", "type.register_type ('OBJ', ['obj'], None, ['NT', 'CYGWIN']) type.register_type ('OBJ', ['o']) register", "('OBJ', ['obj'], None, ['NT', 'CYGWIN']) type.register_type ('OBJ', ['o']) register ()", "copy at https://www.bfgroup.xyz/b2/LICENSE.txt) from b2.build import type def register ():" ]
[ "== \\ ( 1, [(x, 2), (x**2 + 2, 3)])", "[(x, 2)]) assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)]) assert R.dup_sqf_list(-x**5", "[(h, 3)]) R, x = ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0,", "assert R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4)", "is True assert R.dup_sqf_part(-x**3 + x + 1) == x**3", "False assert R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2) is False assert", "(x + 2, 4)] g = x**9 - 20*x**8 +", "== (2, [(x, 2)]) assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)])", "= ring(\"x\", ZZ) R2, y = ring(\"y\", FF(3)) f =", "+ x + 1, 1), (x - 1, 2)]) assert", "1, [(x, 2), (x**2 + 2, 3)]) assert R.dup_sqf_list(2*x**2 +", "+ x - 1 assert R.dmp_sqf_list(f) == (-1, [(x**3 +", "x, y = ring(\"x,y\", ZZ) f = -x**5 + x**4", "is False assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 - 3*x", "2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False assert", "== 2*x**2 + 3*x assert R.dup_sqf_p(2*x**3 + 3*x**2) is False", "z = ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2)", "R.dup_sqf_list(2*x**2) == (2, [(x, 2)]) assert R.dup_sqf_list(3*x**3) == (3, [(x,", "4 f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res", "True assert R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2) is True assert", "False assert R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4) == -f_4 assert", "- 3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False assert R.dup_sqf_list(0)", "True assert R.dmp_sqf_part(f_6) == f_6 R, x = ring(\"x\", ZZ)", "\"\"\"Tests for square-free decomposition algorithms and related tools. \"\"\" from", "x + 1) is True assert R.dup_sqf_part(-x**3 + x +", "0], ZZ), 1), (DMP([1], ZZ)*x, 2)] def test_dmp_sqf(): R, x,", "assert R.dup_sqf_list(0) == (0, []) assert R.dup_sqf_list(1) == (1, [])", "x = ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4", "\\ [(DMP([1, 0, 0, 0], ZZ), 1), (DMP([1], ZZ)*x, 2)]", "0 assert R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7) == 1 assert", "x) == \\ (1, [(x, 1), (x + 1, 3),", "x**3 + 1 g = y**3 + 1 assert R1.dup_sqf_part(f)", "assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 + 8*x**2) == \\", "3132*x**4 + 2948*x**3 - 1504*x**2 + 320*x assert R.dup_gff_list(g) ==", "h = (4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796, [(h,", "y, z, t = ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is True", "is True assert R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7) is True", "f_polys() def test_dup_sqf(): R, x = ring(\"x\", ZZ) assert R.dup_sqf_part(0)", "ring from sympy.polys.domains import FF, ZZ, QQ from sympy.polys.polyclasses import", "+ 1) is True assert R.dup_sqf_part(-x**3 + x + 1)", "ZZ) A = x**4 - 3*x**2 + 6 D =", "ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list(): R,", "== (-1, [(x**3 + x**2 + x + 1, 1),", "(x - 1, 2)] f = -x**2 + 2*x -", "- 1 assert R.dmp_sqf_list_include(f) == [(-1, 1), (x - 1,", "[(x**3 + x**2 + x + 1, 1), (x -", "is True assert R.dmp_sqf_list(3) == (3, []) assert R.dmp_sqf_list_include(3) ==", "assert R.dmp_sqf_list(3) == (3, []) assert R.dmp_sqf_list_include(3) == [(3, 1)]", "False assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 - 3*x assert", "assert R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1)", "6)]) R1, x = ring(\"x\", ZZ) R2, y = ring(\"y\",", "assert R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2)", "1) is True assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 +", "R.dup_gff_list(g) == [(x**2 - 5*x + 4, 1), (x**2 -", "+ 2*x - 1 assert R.dmp_sqf_list_include(f) == [(-1, 1), (x", "1) == x**3 + x + 1 assert R.dup_sqf_p(x**3 +", "== 1 assert R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3) == (3,", "R.dup_sqf_p(2*x**3 + 3*x**2) is False assert R.dup_sqf_part(-2*x**3 + 3*x**2) ==", "f_2, f_3, f_4, f_5, f_6 = f_polys() def test_dup_sqf(): R,", "is False assert R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4) is True", "assert R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0) is True assert R.dup_sqf_part(7)", "1) == \\ (-1, [(x**3 + x**2 + x +", "+ 2*x**4 + x) == \\ (1, [(x, 1), (x", "f = x**5 + 2*x**4 - x**3 - 2*x**2 assert", "R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x + 2) == x +", "+ 3*x**2) is False assert R.dup_sqf_list(0) == (0, []) assert", "import DMP from sympy.polys.specialpolys import f_polys from sympy.utilities.pytest import raises", "- z R, x, y, z, t = ring(\"x,y,z,t\", ZZ)", "= ring(\"x,y\", ZZ) A = x**4 - 3*x**2 + 6", "False assert R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2) is False assert", "R.dup_sqf_p(x**3 + x + 1) is True assert R.dup_sqf_part(-x**3 +", "ZZ) assert R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0) is True assert", "def test_dup_sqf(): R, x = ring(\"x\", ZZ) assert R.dup_sqf_part(0) ==", "+ x**2 + x + 1, 1), (x - 1,", "- 1, 2)] R, x, y = ring(\"x,y\", ZZ) f", "R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5) is", "R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2) is", "+ 1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)]) R, x", "f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res =", "ring(\"y\", FF(3)) f = x**3 + 1 g = y**3", "+ x + 1) == x**3 - x - 1", "is False assert R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2) is False", "x = ring(\"x\", ZZ) f = -x**5 + x**4 +", "R.dmp_sqf_list_include(f) == [(-1, 1), (x - 1, 2)] R, x,", "from sympy.polys.specialpolys import f_polys from sympy.utilities.pytest import raises f_0, f_1,", "== 1 assert R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x + 2)", "3), (x + 2, 6)]) R1, x = ring(\"x\", ZZ)", "ZZ)*x**2) == \\ [(DMP([1, 0, 0, 0], ZZ), 1), (DMP([1],", "\\ (1, [(x, 1), (x + 1, 3), (x +", "( 1, [(x, 2), (x**2 + 2, 3)]) assert R.dup_sqf_list(2*x**2", "assert R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x + 2) == x", "ring(\"x\", ZZ) R2, y = ring(\"y\", FF(3)) f = x**3", "[(-1, 1), (x - 1, 2)] R, x, y =", "= (4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)])", "is False assert R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2) is False", "R, x, y = ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 +", "- 5*x + 4, 1), (x**2 - 5*x + 4,", "1 assert R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g) == y +", "and related tools. \"\"\" from sympy.polys.rings import ring from sympy.polys.domains", "t = ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6)", "is False assert R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4) == -f_4", "+ 166*x**7 - 744*x**6 + 1965*x**5 - 3132*x**4 + 2948*x**3", "ZZ) R2, y = ring(\"y\", FF(3)) f = x**3 +", "(x + 1, 3), (x + 2, 6)]) R1, x", "R2.dup_sqf_p(g) is False R, x, y = ring(\"x,y\", ZZ) A", "<filename>sympy/polys/tests/test_sqfreetools.py \"\"\"Tests for square-free decomposition algorithms and related tools. \"\"\"", "+ 3*x**2) is False assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2", "from sympy.polys.rings import ring from sympy.polys.domains import FF, ZZ, QQ", "- 5*x + 4, 2), (x, 3)] raises(ValueError, lambda: R.dup_gff_list(0))", "sympy.utilities.pytest import raises f_0, f_1, f_2, f_3, f_4, f_5, f_6", "R.dmp_sqf_list_include(3) == [(3, 1)] R, x, y, z = ring(\"x,y,z\",", "1 assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 + x", "+ 3*x**2) == 2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2)", "assert R.dup_sqf_list(1) == (1, []) assert R.dup_sqf_list(x) == (1, [(x,", "+ 320*x assert R.dup_gff_list(g) == [(x**2 - 5*x + 4,", "assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False assert R.dup_sqf_list(0) == (0,", "ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0) is True", "+ 2) == x + 1 assert R.dup_sqf_p(2*x + 2)", "f_5, f_6 = f_polys() def test_dup_sqf(): R, x = ring(\"x\",", "+ 1 assert R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g) is False", "assert R.dup_gff_list(g) == [(x**2 - 5*x + 4, 1), (x**2", "== f_6 R, x = ring(\"x\", ZZ) f = -x**5", "R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 + 3*x assert R.dup_sqf_p(2*x**3 +", "- 5*x**4 + 5*x**2 + 4 f, g = D,", "2)]) R, x = ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 + 4*x", "x = ring(\"x\", ZZ) assert R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0)", "[]) assert R.dup_sqf_list(1) == (1, []) assert R.dup_sqf_list(x) == (1,", "+ 2, 3)]) assert R.dup_sqf_list(2*x**2 + 4*x + 2) ==", "1, 2)]) R, x = ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 +", "== \\ (-1, [(x**3 + x**2 + x + 1,", "- 1, 2)]) assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 +", "1504*x**2 + 320*x assert R.dup_gff_list(g) == [(x**2 - 5*x +", "assert R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2) == \\ [(DMP([1, 0,", "sympy.polys.polyclasses import DMP from sympy.polys.specialpolys import f_polys from sympy.utilities.pytest import", "False assert R.dup_sqf_list(0) == (0, []) assert R.dup_sqf_list(1) == (1,", "+ 1, 2)]) R, x = ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10", "1), (x - 1, 2)] R, x, y = ring(\"x,y\",", "R.dup_sqf_part(x**3 + x + 1) == x**3 + x +", "x = ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 + 4*x + 2)", "R.dup_sqf_list(x**2 + 1) == (1, [(x + 1, 2)]) R,", "import raises f_0, f_1, f_2, f_3, f_4, f_5, f_6 =", "== x + 1 assert R.dup_sqf_p(2*x + 2) is True", "\\ ( 1, [(x, 2), (x**2 + 2, 3)]) assert", "= x**3 + 1 g = y**3 + 1 assert", "3)]) R, x = ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0,", "y, z = ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is True assert", "= x**5 + 2*x**4 - x**3 - 2*x**2 assert R.dup_gff_list(f)", "- 1, 1), (x - 1, 2)] R, x, y", "[(-x**3 - x**2 - x - 1, 1), (x -", "= ring(\"x\", ZZ) f = -x**5 + x**4 + x", "= x**6 - 5*x**4 + 5*x**2 + 4 f, g", "2*x**7 + 2*x**4 + x) == \\ (1, [(x, 1),", "True assert R.dmp_sqf_list(3) == (3, []) assert R.dmp_sqf_list_include(3) == [(3,", "R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res = R.dmp_resultant(f, g) h =", "2), (x**2 + 2, 3)]) assert R.dup_sqf_list(2*x**2 + 4*x +", "square-free decomposition algorithms and related tools. \"\"\" from sympy.polys.rings import", "g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res = R.dmp_resultant(f,", "8*x**2) == \\ ( 1, [(x, 2), (x**2 + 2,", "for square-free decomposition algorithms and related tools. \"\"\" from sympy.polys.rings", "+ 6*x**6 + 12*x**4 + 8*x**2) == \\ ( 1,", "= x**4 - 3*x**2 + 6 D = x**6 -", "1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)]) R, x =", "QQ from sympy.polys.polyclasses import DMP from sympy.polys.specialpolys import f_polys from", "= ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2) ==", "assert R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2)", "= ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2) is", "2)] R, x, y = ring(\"x,y\", ZZ) f = -x**5", "ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6) == f_6", "[(x, 3)]) assert R.dup_sqf_list(-x**5 + x**4 + x - 1)", "+ 1965*x**5 - 3132*x**4 + 2948*x**3 - 1504*x**2 + 320*x", "\"\"\" from sympy.polys.rings import ring from sympy.polys.domains import FF, ZZ,", "[(x + 1, 2)]) R, x = ring(\"x\", FF(2)) assert", "R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2) is", "R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x - 1, 1),", "x**3 - x - 1 assert R.dup_sqf_p(-x**3 + x +", "f_3, f_4, f_5, f_6 = f_polys() def test_dup_sqf(): R, x", "1), (DMP([1], ZZ)*x, 2)] def test_dmp_sqf(): R, x, y =", "(0, []) assert R.dup_sqf_list(1) == (1, []) assert R.dup_sqf_list(x) ==", "assert R.dup_sqf_p(x**3 + x + 1) is True assert R.dup_sqf_part(-x**3", "2, 3)]) assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2,", "(2, [(x + 1, 2)]) R, x = ring(\"x\", FF(2))", "(x - 1, 2)] R, x, y = ring(\"x,y\", FF(2))", "is True assert R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5) == x", "= x**9 - 20*x**8 + 166*x**7 - 744*x**6 + 1965*x**5", "(2, [(x + 1, 2)]) R, x = ring(\"x\", QQ)", "2, 4)] g = x**9 - 20*x**8 + 166*x**7 -", "== (45796, [(h, 3)]) R, x = ring(\"x\", ZZ[\"t\"]) assert", "f_6 = f_polys() def test_dup_sqf(): R, x = ring(\"x\", ZZ)", "assert R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7)", "+ x + 1) == x**3 + x + 1", "+ 1 assert R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g) == y", "- 20*x**8 + 166*x**7 - 744*x**6 + 1965*x**5 - 3132*x**4", "assert R.dmp_sqf_part(f_6) == f_6 R, x = ring(\"x\", ZZ) f", "y = ring(\"y\", FF(3)) f = x**3 + 1 g", "== (1, [(x, 1)]) assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)])", "y = ring(\"x,y\", ZZ) f = -x**5 + x**4 +", "- x - 1, 1), (x - 1, 2)] f", "0, 0], ZZ)*x**2) == \\ [(DMP([1, 0, 0, 0], ZZ),", "True assert R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5) == x +", "+ 2, 6)]) R1, x = ring(\"x\", ZZ) R2, y", "R2.dup_sqf_part(g) == y + 1 assert R1.dup_sqf_p(f) is True assert", "test_dmp_sqf(): R, x, y = ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) ==", "+ 1) == x**3 - x - 1 assert R.dup_sqf_p(-x**3", "+ 2948*x**3 - 1504*x**2 + 320*x assert R.dup_gff_list(g) == [(x**2", "ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2) is False", "+ 2) == (2, [(x + 1, 2)]) R, x", "+ 1)) def test_dup_gff_list(): R, x = ring(\"x\", ZZ) f", "== -f_4 assert R.dmp_sqf_part(f_5) == x + y - z", "assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 + 3*x assert R.dup_sqf_p(2*x**3", "ring(\"x\", ZZ) f = x**5 + 2*x**4 - x**3 -", "1, 2)]) assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x", "- 1, 2)] R, x, y = ring(\"x,y\", FF(2)) raises(NotImplementedError,", "assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)]) assert R.dup_sqf_list(3*x**3) == (3,", "x = ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 + 1) == (1,", "+ 8*x**2) == \\ ( 1, [(x, 2), (x**2 +", "+ 1, 2)]) R, x = ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2", "y = ring(\"x,y\", ZZ) A = x**4 - 3*x**2 +", "R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2) is", "R.dup_sqf_list(-x**5 + x**4 + x - 1) == \\ (-1,", "assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3", "(4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)]) R,", "+ 6 D = x**6 - 5*x**4 + 5*x**2 +", "assert R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4)", "is False assert R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2) is False", "assert R.dup_sqf_p(2*x + 2) is True assert R.dup_sqf_part(x**3 + x", "is False assert R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2) is False", "False assert R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4) is True assert", "+ 1 g = y**3 + 1 assert R1.dup_sqf_part(f) ==", "4)] g = x**9 - 20*x**8 + 166*x**7 - 744*x**6", "R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x + 1,", "2948*x**3 - 1504*x**2 + 320*x assert R.dup_gff_list(g) == [(x**2 -", "ZZ)*x, 2)] def test_dmp_sqf(): R, x, y = ring(\"x,y\", ZZ)", "z, t = ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is True assert", "algorithms and related tools. \"\"\" from sympy.polys.rings import ring from", "True assert R.dup_sqf_part(x**3 + x + 1) == x**3 +", "R1, x = ring(\"x\", ZZ) R2, y = ring(\"y\", FF(3))", "x**3 + x + 1 assert R.dup_sqf_p(x**3 + x +", "R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3) is", "1 assert R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3) == (3, [])", "(3, []) assert R.dmp_sqf_list_include(3) == [(3, 1)] R, x, y,", "assert R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6) == f_6 R, x", "+ 1) is True assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2", "(x - 1, 2)]) assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2", "ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2) == \\", "= ring(\"y\", FF(3)) f = x**3 + 1 g =", "+ 1 assert R.dup_sqf_p(x**3 + x + 1) is True", "ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2) == \\ [(DMP([1,", "lambda: R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list(): R, x = ring(\"x\",", "is True assert R.dmp_sqf_part(f_6) == f_6 R, x = ring(\"x\",", "1965*x**5 - 3132*x**4 + 2948*x**3 - 1504*x**2 + 320*x assert", "[]) assert R.dup_sqf_list(x) == (1, [(x, 1)]) assert R.dup_sqf_list(2*x**2) ==", "(1, []) assert R.dup_sqf_list(x) == (1, [(x, 1)]) assert R.dup_sqf_list(2*x**2)", "ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 + x)", "assert R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2)", "2)] f = -x**2 + 2*x - 1 assert R.dmp_sqf_list_include(f)", "-f_4 assert R.dmp_sqf_part(f_5) == x + y - z R,", "== \\ (1, [(x, 1), (x + 1, 3), (x", "R.dup_gff_list(f) == [(x, 1), (x + 2, 4)] g =", "== \\ [(DMP([1, 0, 0, 0], ZZ), 1), (DMP([1], ZZ)*x,", "is True assert R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2) is True", "True assert R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3) is True assert", "+ 2) is True assert R.dup_sqf_part(x**3 + x + 1)", "= ring(\"x\", ZZ) assert R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0) is", "= ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 + 1) == (1, [(x", "- 3*x**2 + 6 D = x**6 - 5*x**4 +", "2)]) R, x = ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 + 1)", "2*x**4 + x) == \\ (1, [(x, 1), (x +", "-x**2 + 2*x - 1 assert R.dmp_sqf_list_include(f) == [(-1, 1),", "R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4) ==", "assert R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)]) R, x = ring(\"x\",", "5*x**2 + 4 f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1),", "+ x**4 + x - 1 assert R.dmp_sqf_list(f) == (-1,", "- 2*x**2 assert R.dup_gff_list(f) == [(x, 1), (x + 2,", "= ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 +", "== (3, [(x, 3)]) assert R.dup_sqf_list(-x**5 + x**4 + x", "+ 1) == (1, [(x + 1, 2)]) R, x", "assert R.dmp_sqf_part(f_5) == x + y - z R, x,", "is True assert R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7) is True", "assert R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7)", "+ y - z R, x, y, z, t =", "import ring from sympy.polys.domains import FF, ZZ, QQ from sympy.polys.polyclasses", "== 0 assert R.dup_sqf_p(0) is True assert R.dup_sqf_part(7) == 1", "== (1, []) assert R.dup_sqf_list(x) == (1, [(x, 1)]) assert", "- 1) == \\ (-1, [(x**3 + x**2 + x", "y + 1 assert R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g) is", "1) == x**3 - x - 1 assert R.dup_sqf_p(-x**3 +", "1), (x + 2, 4)] g = x**9 - 20*x**8", "assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 + x +", "assert R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3)", "x - 1 assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2", "4*x + 2) == (2, [(x + 1, 2)]) R,", "1, 2)] R, x, y = ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda:", "assert R.dup_sqf_part(x**3 + x + 1) == x**3 + x", "2*x**2 + 3*x assert R.dup_sqf_p(2*x**3 + 3*x**2) is False assert", "+ 5*x**2 + 4 f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D,", "ZZ, QQ from sympy.polys.polyclasses import DMP from sympy.polys.specialpolys import f_polys", "x - 1 assert R.dup_sqf_p(-x**3 + x + 1) is", "R.dup_sqf_p(2*x + 2) is True assert R.dup_sqf_part(x**3 + x +", "== 0 assert R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7) == 1", "+ 4*x + 2) == (2, [(x + 1, 2)])", "R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2) is", "== y + 1 assert R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g)", "+ 1, 2)]) R, x = ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2", "R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3 +", "assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x +", "sympy.polys.specialpolys import f_polys from sympy.utilities.pytest import raises f_0, f_1, f_2,", "= -x**2 + 2*x - 1 assert R.dmp_sqf_list_include(f) == [(-1,", "assert R.dup_gff_list(f) == [(x, 1), (x + 2, 4)] g", "assert R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2)", "x + 1) is True assert R.dup_sqf_part(2*x**3 + 3*x**2) ==", "-x**5 + x**4 + x - 1 assert R.dmp_sqf_list(f) ==", "3*x**2 + 6 D = x**6 - 5*x**4 + 5*x**2", "R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x +", "FF(3)) f = x**3 + 1 g = y**3 +", "(x**2 + 2, 3)]) assert R.dup_sqf_list(2*x**2 + 4*x + 2)", "assert R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x", "6*x**6 + 12*x**4 + 8*x**2) == \\ ( 1, [(x,", "- 1504*x**2 + 320*x assert R.dup_gff_list(g) == [(x**2 - 5*x", "assert R.dup_sqf_part(2*x + 2) == x + 1 assert R.dup_sqf_p(2*x", "ring(\"x\", ZZ) f = -x**5 + x**4 + x -", "R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3) ==", "x**3 - 2*x**2 assert R.dup_gff_list(f) == [(x, 1), (x +", "R, x = ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 + 4*x +", "R.dmp_resultant(f, g) h = (4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res) ==", "False R, x, y = ring(\"x,y\", ZZ) A = x**4", "is True assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 + 3*x", "f_0, f_1, f_2, f_3, f_4, f_5, f_6 = f_polys() def", "assert R.dmp_sqf_list_include(3) == [(3, 1)] R, x, y, z =", "R.dup_sqf_list(3*x**3) == (3, [(x, 3)]) assert R.dup_sqf_list(-x**5 + x**4 +", "R, x = ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0, 0],", "ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2,", "2)] R, x, y = ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2", "= -x**5 + x**4 + x - 1 assert R.dmp_sqf_list(f)", "+ 3*x**2) == 2*x**2 + 3*x assert R.dup_sqf_p(2*x**3 + 3*x**2)", "[(x, 1), (x + 2, 4)] g = x**9 -", "x**6 - 5*x**4 + 5*x**2 + 4 f, g =", "== 2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False", "[]) assert R.dmp_sqf_list_include(3) == [(3, 1)] R, x, y, z", "f_4, f_5, f_6 = f_polys() def test_dup_sqf(): R, x =", "f = -x**5 + x**4 + x - 1 assert", "A = x**4 - 3*x**2 + 6 D = x**6", "x - 1, 1), (x - 1, 2)] R, x,", "x + 1, 1), (x - 1, 2)]) assert R.dmp_sqf_list_include(f)", "R, x = ring(\"x\", ZZ) f = -x**5 + x**4", "1)]) assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)]) assert R.dup_sqf_list(3*x**3) ==", "x, y, z = ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is True", "1, 2)] f = -x**2 + 2*x - 1 assert", "tools. \"\"\" from sympy.polys.rings import ring from sympy.polys.domains import FF,", "1 g = y**3 + 1 assert R1.dup_sqf_part(f) == f", "[(3, 1)] R, x, y, z = ring(\"x,y,z\", ZZ) assert", "2) == x + 1 assert R.dup_sqf_p(2*x + 2) is", "+ 2, 4)] g = x**9 - 20*x**8 + 166*x**7", "4, 1), (x**2 - 5*x + 4, 2), (x, 3)]", "test_dup_gff_list(): R, x = ring(\"x\", ZZ) f = x**5 +", "assert R.dup_sqf_list(-x**5 + x**4 + x - 1) == \\", "x + 1) == x**3 + x + 1 assert", "2)]) assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 + 8*x**2) ==", "+ 4 f, g = D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y))", "assert R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5)", "== [(-1, 1), (x - 1, 2)] R, x, y", "test_dup_sqf(): R, x = ring(\"x\", ZZ) assert R.dup_sqf_part(0) == 0", "DMP from sympy.polys.specialpolys import f_polys from sympy.utilities.pytest import raises f_0,", "(2, [(x, 2)]) assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)]) assert", "2*x - 1 assert R.dmp_sqf_list_include(f) == [(-1, 1), (x -", "y = ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0)", "6 D = x**6 - 5*x**4 + 5*x**2 + 4", "True assert R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7) is True assert", "assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x - 1,", "+ 1) == x**3 + x + 1 assert R.dup_sqf_p(x**3", "0, 0, 0], ZZ), 1), (DMP([1], ZZ)*x, 2)] def test_dmp_sqf():", "= ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list():", "x + y - z R, x, y, z, t", "= ring(\"x,y\", ZZ) f = -x**5 + x**4 + x", "1), (x + 1, 3), (x + 2, 6)]) R1,", "True assert R.dup_sqf_part(2*x**3 + 3*x**2) == 2*x**2 + 3*x assert", "+ 2*x**4 - x**3 - 2*x**2 assert R.dup_gff_list(f) == [(x,", "y)) res = R.dmp_resultant(f, g) h = (4*y**2 + 1).drop(x)", "1, 1), (x - 1, 2)] f = -x**2 +", "1, 1), (x - 1, 2)] R, x, y =", "1, 2)]) R, x = ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 +", "ring(\"x,y\", ZZ) A = x**4 - 3*x**2 + 6 D", "1, 2)] R, x, y = ring(\"x,y\", ZZ) f =", "[(DMP([1, 0, 0, 0], ZZ), 1), (DMP([1], ZZ)*x, 2)] def", "x + 1 assert R.dup_sqf_p(x**3 + x + 1) is", "744*x**6 + 1965*x**5 - 3132*x**4 + 2948*x**3 - 1504*x**2 +", "is False assert R.dup_sqf_list(0) == (0, []) assert R.dup_sqf_list(1) ==", "R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g) is False R, x, y", "[(x + 1, 2)]) R, x = ring(\"x\", FF(3)) assert", "0, 0], ZZ), 1), (DMP([1], ZZ)*x, 2)] def test_dmp_sqf(): R,", "x + 1) == x**3 - x - 1 assert", "+ 4, 1), (x**2 - 5*x + 4, 2), (x,", "R.dmp_sqf_p(f_5) is False assert R.dmp_sqf_p(f_5**2) is False assert R.dmp_sqf_p(f_4) is", "= ring(\"x\", QQ) assert R.dup_sqf_list(2*x**2 + 4*x + 2) ==", "import FF, ZZ, QQ from sympy.polys.polyclasses import DMP from sympy.polys.specialpolys", "== x**3 + x + 1 assert R.dup_sqf_p(x**3 + x", "1), y)) res = R.dmp_resultant(f, g) h = (4*y**2 +", "R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2) == \\ [(DMP([1, 0, 0,", "sympy.polys.domains import FF, ZZ, QQ from sympy.polys.polyclasses import DMP from", "1, 3), (x + 2, 6)]) R1, x = ring(\"x\",", "- 1 assert R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 +", "f_6 R, x = ring(\"x\", ZZ) f = -x**5 +", "0 assert R.dup_sqf_p(0) is True assert R.dup_sqf_part(7) == 1 assert", "def test_dup_gff_list(): R, x = ring(\"x\", ZZ) f = x**5", "x**4 + x - 1) == \\ (-1, [(x**3 +", "R, x, y = ring(\"x,y\", ZZ) A = x**4 -", "- x**3 - 2*x**2 assert R.dup_gff_list(f) == [(x, 1), (x", "[(x, 2), (x**2 + 2, 3)]) assert R.dup_sqf_list(2*x**2 + 4*x", "FF(2)) assert R.dup_sqf_list(x**2 + 1) == (1, [(x + 1,", "def test_dmp_sqf(): R, x, y = ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0)", "is True assert R.dup_sqf_part(2*x + 2) == x + 1", "g = x**9 - 20*x**8 + 166*x**7 - 744*x**6 +", "3*x**2) == 2*x**2 - 3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2) is", "assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 + x) == \\", "5*x + 4, 1), (x**2 - 5*x + 4, 2),", "== [(x, 1), (x + 2, 4)] g = x**9", "R.dup_sqf_p(0) is True assert R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7) is", "== (3, []) assert R.dmp_sqf_list_include(3) == [(3, 1)] R, x,", "R.dup_sqf_list(1) == (1, []) assert R.dup_sqf_list(x) == (1, [(x, 1)])", "+ x + 1 assert R.dup_sqf_p(x**3 + x + 1)", "x + 1 assert R.dup_sqf_p(2*x + 2) is True assert", "3*x assert R.dup_sqf_p(-2*x**3 + 3*x**2) is False assert R.dup_sqf_list(0) ==", "assert R.dup_sqf_list(x) == (1, [(x, 1)]) assert R.dup_sqf_list(2*x**2) == (2,", "R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 + 8*x**2) == \\ (", "+ x) == \\ (1, [(x, 1), (x + 1,", "assert R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g) is False R, x,", "(1, [(x, 1), (x + 1, 3), (x + 2,", "R.dmp_sqf_p(f_1**2) is False assert R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2) is", "3)]) assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x", "assert R2.dup_sqf_part(g) == y + 1 assert R1.dup_sqf_p(f) is True", "1 assert R.dup_sqf_p(7) is True assert R.dup_sqf_part(2*x + 2) ==", "+ 1 assert R.dup_sqf_p(2*x + 2) is True assert R.dup_sqf_part(x**3", "= f_polys() def test_dup_sqf(): R, x = ring(\"x\", ZZ) assert", "assert R.dup_sqf_p(0) is True assert R.dup_sqf_part(7) == 1 assert R.dup_sqf_p(7)", "R.dup_sqf_part(-x**3 + x + 1) == x**3 - x -", "+ 3*x assert R.dup_sqf_p(2*x**3 + 3*x**2) is False assert R.dup_sqf_part(-2*x**3", "0], ZZ)*x**2) == \\ [(DMP([1, 0, 0, 0], ZZ), 1),", "R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1) is", "R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list(): R, x = ring(\"x\", ZZ)", "ZZ) assert R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6) == f_6 R,", "ring(\"x\", ZZ) assert R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0) is True", "is True assert R2.dup_sqf_p(g) is False R, x, y =", "(-1, [(x**3 + x**2 + x + 1, 1), (x", "R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7) is", "assert R.dup_sqf_p(2*x**3 + 3*x**2) is False assert R.dup_sqf_part(-2*x**3 + 3*x**2)", "== (1, [(x + 1, 2)]) R, x = ring(\"x\",", "1), (x**2 - 5*x + 4, 2), (x, 3)] raises(ValueError,", "QQ) assert R.dup_sqf_list(2*x**2 + 4*x + 2) == (2, [(x", "R, x, y, z = ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0) is", "= ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6) ==", "(x**2 - 5*x + 4, 2), (x, 3)] raises(ValueError, lambda:", "= ring(\"x\", ZZ) f = x**5 + 2*x**4 - x**3", "5*x**4 + 5*x**2 + 4 f, g = D, R.dmp_sub(A,", "0, 0, 0], ZZ)*x**2) == \\ [(DMP([1, 0, 0, 0],", "x, y = ring(\"x,y\", ZZ) A = x**4 - 3*x**2", "1, 1), (x - 1, 2)]) assert R.dmp_sqf_list_include(f) == [(-x**3", "= D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res = R.dmp_resultant(f, g)", "y = ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1)) def", "12*x**4 + 8*x**2) == \\ ( 1, [(x, 2), (x**2", "1 assert R.dup_sqf_p(x**3 + x + 1) is True assert", "3*x assert R.dup_sqf_p(2*x**3 + 3*x**2) is False assert R.dup_sqf_part(-2*x**3 +", "== x**3 - x - 1 assert R.dup_sqf_p(-x**3 + x", "x, y = ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) == 0 assert", "x = ring(\"x\", ZZ) f = x**5 + 2*x**4 -", "D = x**6 - 5*x**4 + 5*x**2 + 4 f,", "y**3 + 1 assert R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g) ==", "assert R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3) == (3, []) assert", "R.dup_sqf_part(2*x + 2) == x + 1 assert R.dup_sqf_p(2*x +", "from sympy.polys.domains import FF, ZZ, QQ from sympy.polys.polyclasses import DMP", "f_polys from sympy.utilities.pytest import raises f_0, f_1, f_2, f_3, f_4,", "ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 + 1) == (1, [(x +", "assert R.dup_sqf_list(x**2 + 1) == (1, [(x + 1, 2)])", "f assert R2.dup_sqf_part(g) == y + 1 assert R1.dup_sqf_p(f) is", "x + 1, 1), (x - 1, 2)]) assert R.dup_sqf_list(x**8", "- 3132*x**4 + 2948*x**3 - 1504*x**2 + 320*x assert R.dup_gff_list(g)", "\\ (-1, [(x**3 + x**2 + x + 1, 1),", "R, x, y = ring(\"x,y\", ZZ) f = -x**5 +", "20*x**8 + 166*x**7 - 744*x**6 + 1965*x**5 - 3132*x**4 +", "+ 1, 1), (x - 1, 2)]) assert R.dup_sqf_list(x**8 +", "- x - 1, 1), (x - 1, 2)] R,", "x**9 - 20*x**8 + 166*x**7 - 744*x**6 + 1965*x**5 -", "R.dmp_mul(R.dmp_diff(D, 1), y)) res = R.dmp_resultant(f, g) h = (4*y**2", "True assert R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5) is False assert", "R, x, y, z, t = ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6)", "1), (x - 1, 2)]) assert R.dmp_sqf_list_include(f) == [(-x**3 -", "R, x = ring(\"x\", ZZ) f = x**5 + 2*x**4", "+ x - 1) == \\ (-1, [(x**3 + x**2", "(1, [(x + 1, 2)]) R, x = ring(\"x\", FF(3))", "True assert R.dup_sqf_part(2*x + 2) == x + 1 assert", "- 744*x**6 + 1965*x**5 - 3132*x**4 + 2948*x**3 - 1504*x**2", "(1, [(x, 1)]) assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)]) assert", "(x - 1, 2)]) assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4", "1), (x - 1, 2)] f = -x**2 + 2*x", "R.drop(x).dup_sqf_list(res) == (45796, [(h, 3)]) R, x = ring(\"x\", ZZ[\"t\"])", "+ 1, 1), (x - 1, 2)]) assert R.dmp_sqf_list_include(f) ==", "sympy.polys.rings import ring from sympy.polys.domains import FF, ZZ, QQ from", "1), (x - 1, 2)]) assert R.dup_sqf_list(x**8 + 6*x**6 +", "True assert R2.dup_sqf_p(g) is False R, x, y = ring(\"x,y\",", "+ x**4 + x - 1) == \\ (-1, [(x**3", "g = y**3 + 1 assert R1.dup_sqf_part(f) == f assert", "R.dmp_sqf_part(f_6) == f_6 R, x = ring(\"x\", ZZ) f =", "ZZ) assert R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0) is True assert", "1, 2)]) R, x = ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 +", "320*x assert R.dup_gff_list(g) == [(x**2 - 5*x + 4, 1),", "R.dup_sqf_p(-2*x**3 + 3*x**2) is False assert R.dup_sqf_list(0) == (0, [])", "False assert R.dmp_sqf_p(f_2) is True assert R.dmp_sqf_p(f_2**2) is False assert", "x - 1) == \\ (-1, [(x**3 + x**2 +", "3*x**2) is False assert R.dup_sqf_list(0) == (0, []) assert R.dup_sqf_list(1)", "assert R2.dup_sqf_p(g) is False R, x, y = ring(\"x,y\", ZZ)", "1, 1), (x - 1, 2)]) assert R.dup_sqf_list(x**8 + 6*x**6", "assert R.dmp_sqf_list_include(f) == [(-1, 1), (x - 1, 2)] R,", "2) == (2, [(x + 1, 2)]) R, x =", "+ 12*x**4 + 8*x**2) == \\ ( 1, [(x, 2),", "FF, ZZ, QQ from sympy.polys.polyclasses import DMP from sympy.polys.specialpolys import", "True assert R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1) is True assert", "raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list(): R, x =", "ZZ) assert R.dmp_sqf_p(f_0) is True assert R.dmp_sqf_p(f_0**2) is False assert", "== x + y - z R, x, y, z,", "- x - 1 assert R.dup_sqf_p(-x**3 + x + 1)", "is True assert R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5) is False", "(45796, [(h, 3)]) R, x = ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1,", "FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1)) def test_dup_gff_list(): R, x", "2)]) assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)]) assert R.dup_sqf_list(-x**5 +", "D, R.dmp_sub(A, R.dmp_mul(R.dmp_diff(D, 1), y)) res = R.dmp_resultant(f, g) h", "(3, [(x, 3)]) assert R.dup_sqf_list(-x**5 + x**4 + x -", "x**2 - x - 1, 1), (x - 1, 2)]", "- 1 assert R.dup_sqf_p(-x**3 + x + 1) is True", "= y**3 + 1 assert R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g)", "2)]) assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 - x -", "1 assert R.dup_sqf_p(-x**3 + x + 1) is True assert", "+ 1, 3), (x + 2, 6)]) R1, x =", "is True assert R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1) is True", "1) == (1, [(x + 1, 2)]) R, x =", "x, y = ring(\"x,y\", FF(2)) raises(NotImplementedError, lambda: R.dmp_sqf_list(y**2 + 1))", "assert R.dup_sqf_list(3*x**3) == (3, [(x, 3)]) assert R.dup_sqf_list(-x**5 + x**4", "R.dup_sqf_list(x) == (1, [(x, 1)]) assert R.dup_sqf_list(2*x**2) == (2, [(x,", "R2, y = ring(\"y\", FF(3)) f = x**3 + 1", "assert R.dup_sqf_part(-x**3 + x + 1) == x**3 - x", "is True assert R.dmp_sqf_p(f_2**2) is False assert R.dmp_sqf_p(f_3) is True", "(DMP([1], ZZ)*x, 2)] def test_dmp_sqf(): R, x, y = ring(\"x,y\",", "x**4 + x - 1 assert R.dmp_sqf_list(f) == (-1, [(x**3", "f = -x**2 + 2*x - 1 assert R.dmp_sqf_list_include(f) ==", "1, 2)]) assert R.dup_sqf_list(x**8 + 6*x**6 + 12*x**4 + 8*x**2)", "from sympy.polys.polyclasses import DMP from sympy.polys.specialpolys import f_polys from sympy.utilities.pytest", "ZZ), 1), (DMP([1], ZZ)*x, 2)] def test_dmp_sqf(): R, x, y", "- x**2 - x - 1, 1), (x - 1,", "R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 + x) == \\ (1,", "x - 1, 1), (x - 1, 2)] f =", "x**5 + 2*x**4 - x**3 - 2*x**2 assert R.dup_gff_list(f) ==", "x = ring(\"x\", ZZ[\"t\"]) assert R.dup_sqf_list_include(DMP([1, 0, 0, 0], ZZ)*x**2)", "True assert R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7) is True assert", "assert R.dup_sqf_p(-x**3 + x + 1) is True assert R.dup_sqf_part(2*x**3", "R.dmp_sqf_list(f) == (-1, [(x**3 + x**2 + x + 1,", "import f_polys from sympy.utilities.pytest import raises f_0, f_1, f_2, f_3,", "is True assert R.dup_sqf_part(x**3 + x + 1) == x**3", "R.dup_sqf_part(0) == 0 assert R.dup_sqf_p(0) is True assert R.dup_sqf_part(7) ==", "+ 2*x**7 + 2*x**4 + x) == \\ (1, [(x,", "x**4 - 3*x**2 + 6 D = x**6 - 5*x**4", "R, x = ring(\"x\", ZZ) assert R.dup_sqf_part(0) == 0 assert", "1)] R, x, y, z = ring(\"x,y,z\", ZZ) assert R.dmp_sqf_p(f_0)", "(x + 2, 6)]) R1, x = ring(\"x\", ZZ) R2,", "True assert R.dup_sqf_part(-x**3 + x + 1) == x**3 -", "== [(3, 1)] R, x, y, z = ring(\"x,y,z\", ZZ)", "assert R.dmp_sqf_p(f_0**2) is False assert R.dmp_sqf_p(f_1) is True assert R.dmp_sqf_p(f_1**2)", "R.dmp_sqf_part(f_5) == x + y - z R, x, y,", "R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g) == y + 1 assert", "== (0, []) assert R.dup_sqf_list(1) == (1, []) assert R.dup_sqf_list(x)", "assert R1.dup_sqf_part(f) == f assert R2.dup_sqf_part(g) == y + 1", "assert R.dmp_sqf_part(7) == 1 assert R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3)", "R.dmp_sqf_list(3) == (3, []) assert R.dmp_sqf_list_include(3) == [(3, 1)] R,", "x = ring(\"x\", ZZ) R2, y = ring(\"y\", FF(3)) f", "2, 6)]) R1, x = ring(\"x\", ZZ) R2, y =", "is False R, x, y = ring(\"x,y\", ZZ) A =", "3)]) assert R.dup_sqf_list(-x**5 + x**4 + x - 1) ==", "R.dup_sqf_list(0) == (0, []) assert R.dup_sqf_list(1) == (1, []) assert", "166*x**7 - 744*x**6 + 1965*x**5 - 3132*x**4 + 2948*x**3 -", "f_1, f_2, f_3, f_4, f_5, f_6 = f_polys() def test_dup_sqf():", "= R.dmp_resultant(f, g) h = (4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res)", "R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0) is True assert R.dmp_sqf_part(7) ==", "== [(x**2 - 5*x + 4, 1), (x**2 - 5*x", "== f assert R2.dup_sqf_part(g) == y + 1 assert R1.dup_sqf_p(f)", "y - z R, x, y, z, t = ring(\"x,y,z,t\",", "== (2, [(x + 1, 2)]) R, x = ring(\"x\",", "== [(-x**3 - x**2 - x - 1, 1), (x", "+ x + 1) is True assert R.dup_sqf_part(-x**3 + x", "assert R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5) == x + y", "[(x, 1)]) assert R.dup_sqf_list(2*x**2) == (2, [(x, 2)]) assert R.dup_sqf_list(3*x**3)", "1) is True assert R.dup_sqf_part(-x**3 + x + 1) ==", "[(x + 1, 2)]) R, x = ring(\"x\", QQ) assert", "raises f_0, f_1, f_2, f_3, f_4, f_5, f_6 = f_polys()", "f = x**3 + 1 g = y**3 + 1", "- 1, 2)]) assert R.dmp_sqf_list_include(f) == [(-x**3 - x**2 -", "= ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) == 0 assert R.dmp_sqf_p(0) is", "2*x**2 assert R.dup_gff_list(f) == [(x, 1), (x + 2, 4)]", "R.dmp_sqf_p(f_4) is True assert R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5) ==", "ring(\"x,y\", ZZ) f = -x**5 + x**4 + x -", "1 assert R.dmp_sqf_list_include(f) == [(-1, 1), (x - 1, 2)]", "decomposition algorithms and related tools. \"\"\" from sympy.polys.rings import ring", "R, x = ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7 +", "R.dup_sqf_p(-x**3 + x + 1) is True assert R.dup_sqf_part(2*x**3 +", "1 assert R1.dup_sqf_p(f) is True assert R2.dup_sqf_p(g) is False R,", "z R, x, y, z, t = ring(\"x,y,z,t\", ZZ) assert", "from sympy.utilities.pytest import raises f_0, f_1, f_2, f_3, f_4, f_5,", "[(x**2 - 5*x + 4, 1), (x**2 - 5*x +", "3*x**2) == 2*x**2 + 3*x assert R.dup_sqf_p(2*x**3 + 3*x**2) is", "+ x + 1) is True assert R.dup_sqf_part(2*x**3 + 3*x**2)", "2)] def test_dmp_sqf(): R, x, y = ring(\"x,y\", ZZ) assert", "x**2 + x + 1, 1), (x - 1, 2)])", "2) is True assert R.dup_sqf_part(x**3 + x + 1) ==", "g) h = (4*y**2 + 1).drop(x) assert R.drop(x).dup_sqf_list(res) == (45796,", "- 1, 2)] f = -x**2 + 2*x - 1", "- 1, 1), (x - 1, 2)] f = -x**2", "1)) def test_dup_gff_list(): R, x = ring(\"x\", ZZ) f =", "res = R.dmp_resultant(f, g) h = (4*y**2 + 1).drop(x) assert", "ZZ) f = -x**5 + x**4 + x - 1", "2)]) R, x = ring(\"x\", FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7", "1 assert R.dup_sqf_p(2*x + 2) is True assert R.dup_sqf_part(x**3 +", "x, y, z, t = ring(\"x,y,z,t\", ZZ) assert R.dmp_sqf_p(f_6) is", "R.dmp_sqf_part(f_4) == -f_4 assert R.dmp_sqf_part(f_5) == x + y -", "R, x = ring(\"x\", FF(2)) assert R.dup_sqf_list(x**2 + 1) ==", "ZZ) f = x**5 + 2*x**4 - x**3 - 2*x**2", "R.dmp_sqf_p(7) is True assert R.dmp_sqf_list(3) == (3, []) assert R.dmp_sqf_list_include(3)", "R.dmp_sqf_p(f_6) is True assert R.dmp_sqf_part(f_6) == f_6 R, x =", "FF(3)) assert R.dup_sqf_list(x**10 + 2*x**7 + 2*x**4 + x) ==", "assert R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2) is False assert R.dmp_sqf_p(f_5)", "2*x**4 - x**3 - 2*x**2 assert R.dup_gff_list(f) == [(x, 1),", "related tools. \"\"\" from sympy.polys.rings import ring from sympy.polys.domains import", "False assert R.dmp_sqf_p(f_3) is True assert R.dmp_sqf_p(f_3**2) is False assert", "3*x**2) is False assert R.dup_sqf_part(-2*x**3 + 3*x**2) == 2*x**2 -", "(x - 1, 2)] R, x, y = ring(\"x,y\", ZZ)", "[(x, 1), (x + 1, 3), (x + 2, 6)])", "R, x, y = ring(\"x,y\", ZZ) assert R.dmp_sqf_part(0) == 0" ]
[ "2 TextLineBreaks = 3 UnicodeText = 7 WebArchive = 9", "= 15 MP4 = 39 OpenPresentation = 35 PDF =", "= 10 FlatXML = 19 OpenDocumentText = 23 HTML =", "@enum.unique class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP", "'.pptx') @enum.unique class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4", "= 23 External = 64000 GIF = 16 JPG =", "16 JPG = 17 META = 15 MP4 = 39", "33 app = 'Powerpoint.Application' extensions = ('.ppt', '.pptx') @enum.unique class", "= 0 XPS = 1 app = 'Excel.Application' extensions =", "External = 64000 GIF = 16 JPG = 17 META", "enum from typing import Union @enum.unique class PPT(enum.Enum): # Source:", "app = 'Powerpoint.Application' extensions = ('.ppt', '.pptx') @enum.unique class WORD(enum.Enum):", "RTF = 6 SHOW = 7 Template = 5 TIF", "23 HTML = 8 RTF = 6 Template = 1", "= 64000 GIF = 16 JPG = 17 META =", "= ('.ppt', '.pptx') @enum.unique class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText", "6 Template = 1 Text = 2 TextLineBreaks = 3", "META = 15 MP4 = 39 OpenPresentation = 35 PDF", "0 XPS = 1 app = 'Excel.Application' extensions = ('.xls',", "= 'Excel.Application' extensions = ('.xls', '.xlsx') enum_types = Union[PPT, WORD,", "XPS = 33 app = 'Powerpoint.Application' extensions = ('.ppt', '.pptx')", "= 40 BMP = 19 Default = 11 EMF =", "16 PDF = 17 XPS = 18 app = 'Word.Application'", "= 4 DosTextLineBreaks = 5 FilteredHTML = 10 FlatXML =", "= 7 WebArchive = 9 XML = 11 Document97 =", "= 6 SHOW = 7 Template = 5 TIF =", "JPG = 17 META = 15 MP4 = 39 OpenPresentation", "1 Text = 2 TextLineBreaks = 3 UnicodeText = 7", "3 UnicodeText = 7 WebArchive = 9 XML = 11", "Default = 11 EMF = 23 External = 64000 GIF", "class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\" methods,", "Template = 1 Text = 2 TextLineBreaks = 3 UnicodeText", "PDF = 0 XPS = 1 app = 'Excel.Application' extensions", "RTF = 6 Template = 1 Text = 2 TextLineBreaks", "\"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS = 1", "TODO: Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS", "37 XPS = 33 app = 'Powerpoint.Application' extensions = ('.ppt',", "15 MP4 = 39 OpenPresentation = 35 PDF = 32", "39 OpenPresentation = 35 PDF = 32 PNG = 18", "UnicodeText = 7 WebArchive = 9 XML = 11 Document97", "DocumentDefault = 16 PDF = 17 XPS = 18 app", "@enum.unique class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\"", "6 SHOW = 7 Template = 5 TIF = 21", "https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks = 5 FilteredHTML = 10", "9 XML = 11 Document97 = 0 DocumentDefault = 16", "app = 'Excel.Application' extensions = ('.xls', '.xlsx') enum_types = Union[PPT,", "TIF = 21 WMV = 37 XPS = 33 app", "EMF = 23 External = 64000 GIF = 16 JPG", "18 app = 'Word.Application' extensions = ('.doc', '.docx') @enum.unique class", "= 19 OpenDocumentText = 23 HTML = 8 RTF =", "= 21 WMV = 37 XPS = 33 app =", "from typing import Union @enum.unique class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype", "PNG = 18 Presentation = 1 RTF = 6 SHOW", "= 1 Text = 2 TextLineBreaks = 3 UnicodeText =", "17 META = 15 MP4 = 39 OpenPresentation = 35", "DosText = 4 DosTextLineBreaks = 5 FilteredHTML = 10 FlatXML", "7 Template = 5 TIF = 21 WMV = 37", "typing import Union @enum.unique class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF", "PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP = 19", "= 35 PDF = 32 PNG = 18 Presentation =", "= 9 XML = 11 Document97 = 0 DocumentDefault =", "= 'Powerpoint.Application' extensions = ('.ppt', '.pptx') @enum.unique class WORD(enum.Enum): #", "= 0 DocumentDefault = 16 PDF = 17 XPS =", "import enum from typing import Union @enum.unique class PPT(enum.Enum): #", "https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF =", "# Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks = 5 FilteredHTML", "= 33 app = 'Powerpoint.Application' extensions = ('.ppt', '.pptx') @enum.unique", "= 5 FilteredHTML = 10 FlatXML = 19 OpenDocumentText =", "= 16 PDF = 17 XPS = 18 app =", "XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\" methods, see:", "Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS =", "see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS = 1 app =", "= 3 UnicodeText = 7 WebArchive = 9 XML =", "# Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP = 19 Default", "Text = 2 TextLineBreaks = 3 UnicodeText = 7 WebArchive", "('.doc', '.docx') @enum.unique class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO:", "19 Default = 11 EMF = 23 External = 64000", "= 23 HTML = 8 RTF = 6 Template =", "Union @enum.unique class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40", "10 FlatXML = 19 OpenDocumentText = 23 HTML = 8", "'Word.Application' extensions = ('.doc', '.docx') @enum.unique class XL(enum.Enum): # Source:", "= 18 app = 'Word.Application' extensions = ('.doc', '.docx') @enum.unique", "WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks = 5", "AnimatedGIF = 40 BMP = 19 Default = 11 EMF", "PDF = 17 XPS = 18 app = 'Word.Application' extensions", "32 PNG = 18 Presentation = 1 RTF = 6", "DosTextLineBreaks = 5 FilteredHTML = 10 FlatXML = 19 OpenDocumentText", "5 TIF = 21 WMV = 37 XPS = 33", "35 PDF = 32 PNG = 18 Presentation = 1", "23 External = 64000 GIF = 16 JPG = 17", "7 WebArchive = 9 XML = 11 Document97 = 0", "methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS = 1 app", "= 1 app = 'Excel.Application' extensions = ('.xls', '.xlsx') enum_types", "= 'Word.Application' extensions = ('.doc', '.docx') @enum.unique class XL(enum.Enum): #", "= 32 PNG = 18 Presentation = 1 RTF =", "Presentation = 1 RTF = 6 SHOW = 7 Template", "11 EMF = 23 External = 64000 GIF = 16", "extensions = ('.doc', '.docx') @enum.unique class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype", "OpenPresentation = 35 PDF = 32 PNG = 18 Presentation", "4 DosTextLineBreaks = 5 FilteredHTML = 10 FlatXML = 19", "'Excel.Application' extensions = ('.xls', '.xlsx') enum_types = Union[PPT, WORD, XL]", "= 39 OpenPresentation = 35 PDF = 32 PNG =", "https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP = 19 Default = 11", "PDF = 32 PNG = 18 Presentation = 1 RTF", "= 11 EMF = 23 External = 64000 GIF =", "40 BMP = 19 Default = 11 EMF = 23", "import Union @enum.unique class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF =", "= 18 Presentation = 1 RTF = 6 SHOW =", "= 7 Template = 5 TIF = 21 WMV =", "= 5 TIF = 21 WMV = 37 XPS =", "class PPT(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP =", "# TODO: Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0", "8 RTF = 6 Template = 1 Text = 2", "Source: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype AnimatedGIF = 40 BMP = 19 Default =", "= 16 JPG = 17 META = 15 MP4 =", "https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF = 0 XPS = 1 app = 'Excel.Application'", "XPS = 18 app = 'Word.Application' extensions = ('.doc', '.docx')", "XML = 11 Document97 = 0 DocumentDefault = 16 PDF", "Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas PDF", "app = 'Word.Application' extensions = ('.doc', '.docx') @enum.unique class XL(enum.Enum):", "= 19 Default = 11 EMF = 23 External =", "BMP = 19 Default = 11 EMF = 23 External", "GIF = 16 JPG = 17 META = 15 MP4", "= ('.doc', '.docx') @enum.unique class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype #", "'.docx') @enum.unique class XL(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement", "FlatXML = 19 OpenDocumentText = 23 HTML = 8 RTF", "5 FilteredHTML = 10 FlatXML = 19 OpenDocumentText = 23", "1 RTF = 6 SHOW = 7 Template = 5", "FilteredHTML = 10 FlatXML = 19 OpenDocumentText = 23 HTML", "XPS = 1 app = 'Excel.Application' extensions = ('.xls', '.xlsx')", "'Powerpoint.Application' extensions = ('.ppt', '.pptx') @enum.unique class WORD(enum.Enum): # Source:", "1 app = 'Excel.Application' extensions = ('.xls', '.xlsx') enum_types =", "18 Presentation = 1 RTF = 6 SHOW = 7", "= 6 Template = 1 Text = 2 TextLineBreaks =", "WebArchive = 9 XML = 11 Document97 = 0 DocumentDefault", "Document97 = 0 DocumentDefault = 16 PDF = 17 XPS", "= 37 XPS = 33 app = 'Powerpoint.Application' extensions =", "@enum.unique class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks", "0 DocumentDefault = 16 PDF = 17 XPS = 18", "= 1 RTF = 6 SHOW = 7 Template =", "OpenDocumentText = 23 HTML = 8 RTF = 6 Template", "21 WMV = 37 XPS = 33 app = 'Powerpoint.Application'", "64000 GIF = 16 JPG = 17 META = 15", "class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks =", "= 17 XPS = 18 app = 'Word.Application' extensions =", "extensions = ('.ppt', '.pptx') @enum.unique class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat", "= 2 TextLineBreaks = 3 UnicodeText = 7 WebArchive =", "MP4 = 39 OpenPresentation = 35 PDF = 32 PNG", "17 XPS = 18 app = 'Word.Application' extensions = ('.doc',", "= 17 META = 15 MP4 = 39 OpenPresentation =", "('.ppt', '.pptx') @enum.unique class WORD(enum.Enum): # Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText =", "HTML = 8 RTF = 6 Template = 1 Text", "19 OpenDocumentText = 23 HTML = 8 RTF = 6", "TextLineBreaks = 3 UnicodeText = 7 WebArchive = 9 XML", "Source: https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat DosText = 4 DosTextLineBreaks = 5 FilteredHTML =", "Template = 5 TIF = 21 WMV = 37 XPS", "= 11 Document97 = 0 DocumentDefault = 16 PDF =", "11 Document97 = 0 DocumentDefault = 16 PDF = 17", "# Source: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfixedformattype # TODO: Implement \"SaveAs\" methods, see: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas", "= 8 RTF = 6 Template = 1 Text =", "WMV = 37 XPS = 33 app = 'Powerpoint.Application' extensions", "SHOW = 7 Template = 5 TIF = 21 WMV" ]
[ "by Django 4.0.1 on 2022-01-19 23:58 from django.db import migrations,", "on 2022-01-19 23:58 from django.db import migrations, models class Migration(migrations.Migration):", "'0001_initial'), ] operations = [ migrations.AddField( model_name='movies', name='year', field=models.CharField(max_length=4, null=True),", "[ ('news', '0001_initial'), ] operations = [ migrations.AddField( model_name='movies', name='year',", "models class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ] operations", "dependencies = [ ('news', '0001_initial'), ] operations = [ migrations.AddField(", "<reponame>vvuri/flask_pipeline<gh_stars>0 # Generated by Django 4.0.1 on 2022-01-19 23:58 from", "] operations = [ migrations.AddField( model_name='movies', name='year', field=models.CharField(max_length=4, null=True), ),", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('news',", "= [ ('news', '0001_initial'), ] operations = [ migrations.AddField( model_name='movies',", "Django 4.0.1 on 2022-01-19 23:58 from django.db import migrations, models", "# Generated by Django 4.0.1 on 2022-01-19 23:58 from django.db", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "2022-01-19 23:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "4.0.1 on 2022-01-19 23:58 from django.db import migrations, models class", "class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ] operations =", "Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ] operations = [", "Generated by Django 4.0.1 on 2022-01-19 23:58 from django.db import", "23:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'),", "migrations, models class Migration(migrations.Migration): dependencies = [ ('news', '0001_initial'), ]", "('news', '0001_initial'), ] operations = [ migrations.AddField( model_name='movies', name='year', field=models.CharField(max_length=4,", "operations = [ migrations.AddField( model_name='movies', name='year', field=models.CharField(max_length=4, null=True), ), ]" ]
[ "param.Parameter() def __init__(self, **params): super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS)", "param.String(default=\"This is some text\") view = param.Parameter() def __init__(self, **params):", "400} } class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is some text\")", "\"sizing_mode\": \"fixed\", \"width\": 400} } class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This", "as pn import param from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS", "def __init__(self, **params): super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app", "awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS = { \"some_text\": {\"type\": FastTextInput,", "**params): super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app = ParameterizedApp()", "class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is some text\") view =", "FastTextInput WIDGETS = { \"some_text\": {\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\":", "\"width\": 400} } class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is some", "panel as pn import param from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput", "import panel as pn import param from awesome_panel_extensions.frameworks.fast import FastTemplate,", "True, \"sizing_mode\": \"fixed\", \"width\": 400} } class ParameterizedApp(param.Parameterized): some_text =", "some text\") view = param.Parameter() def __init__(self, **params): super().__init__(**params) self.view", "{\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\", \"width\": 400} } class", "is some text\") view = param.Parameter() def __init__(self, **params): super().__init__(**params)", "import param from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS = {", "self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app = ParameterizedApp() paremeterized_template =", "\"some_text\": {\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\", \"width\": 400} }", "\"readonly\": True, \"sizing_mode\": \"fixed\", \"width\": 400} } class ParameterizedApp(param.Parameterized): some_text", "view = param.Parameter() def __init__(self, **params): super().__init__(**params) self.view = pn.Param(self,", "from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS = { \"some_text\": {\"type\":", "ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is some text\") view = param.Parameter()", "__init__(self, **params): super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app =", "{ \"some_text\": {\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\", \"width\": 400}", "param from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS = { \"some_text\":", "text\") view = param.Parameter() def __init__(self, **params): super().__init__(**params) self.view =", "= param.Parameter() def __init__(self, **params): super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"],", "WIDGETS = { \"some_text\": {\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\",", "FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\", \"width\": 400} } class ParameterizedApp(param.Parameterized):", "some_text = param.String(default=\"This is some text\") view = param.Parameter() def", "= { \"some_text\": {\"type\": FastTextInput, \"readonly\": True, \"sizing_mode\": \"fixed\", \"width\":", "= param.String(default=\"This is some text\") view = param.Parameter() def __init__(self,", "= pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app = ParameterizedApp() paremeterized_template = FastTemplate(main=[parameterized_app.view])", "pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app = ParameterizedApp() paremeterized_template = FastTemplate(main=[parameterized_app.view]) paremeterized_template.servable()", "pn import param from awesome_panel_extensions.frameworks.fast import FastTemplate, FastTextInput WIDGETS =", "import FastTemplate, FastTextInput WIDGETS = { \"some_text\": {\"type\": FastTextInput, \"readonly\":", "FastTemplate, FastTextInput WIDGETS = { \"some_text\": {\"type\": FastTextInput, \"readonly\": True,", "} class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is some text\") view", "super().__init__(**params) self.view = pn.Param(self, parameters=[\"some_text\"], widgets=WIDGETS) parameterized_app = ParameterizedApp() paremeterized_template", "\"fixed\", \"width\": 400} } class ParameterizedApp(param.Parameterized): some_text = param.String(default=\"This is" ]
[ "in source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!'", "import QueueRedis conn = None def connect_db(): global conn conn", "= res[0] company['name'] = res[1] companies.append(company) return companies def main():", "from gjqyxyxxcxxt.database.my_redis import QueueRedis conn = None def connect_db(): global", "exit() time.sleep(3) global conn connect_db() source = get_req_from_db() for id_name", "sys.path.append(app_dir) from gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis import QueueRedis conn", "cursor = conn.cursor() cursor.execute('select id, entname from req where status=0", "global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global conn", "coding: utf-8 -*- import pymysql import sys, os, json, time,", "def main(): my_queue = QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print result", "= pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global conn cursor = conn.cursor()", "def get_req_from_db(): global conn cursor = conn.cursor() cursor.execute('select id, entname", "res in results: company = {} company['id'] = res[0] company['name']", "gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis import QueueRedis conn = None", "from req where status=0 order by id limit 10') results", "in results: company = {} company['id'] = res[0] company['name'] =", "import settings from gjqyxyxxcxxt.database.my_redis import QueueRedis conn = None def", "pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global conn cursor = conn.cursor() cursor.execute('select", "by id limit 10') results = cursor.fetchall() companies = []", "utf-8 -*- import pymysql import sys, os, json, time, pymongo", "= None def connect_db(): global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return", "time.sleep(3) global conn connect_db() source = get_req_from_db() for id_name in", "company['name'] = res[1] companies.append(company) return companies def main(): my_queue =", "cursor.fetchall() companies = [] for res in results: company =", "entname from req where status=0 order by id limit 10')", "companies = [] for res in results: company = {}", "{} company['id'] = res[0] company['name'] = res[1] companies.append(company) return companies", "app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis", "settings from gjqyxyxxcxxt.database.my_redis import QueueRedis conn = None def connect_db():", "res[0] company['name'] = res[1] companies.append(company) return companies def main(): my_queue", "里存在数据则,3秒后退出 if result: time.sleep(3) exit() time.sleep(3) global conn connect_db() source", "import sys, os, json, time, pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir)", "10') results = cursor.fetchall() companies = [] for res in", "result #mq 里存在数据则,3秒后退出 if result: time.sleep(3) exit() time.sleep(3) global conn", "main(): my_queue = QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print result #mq", "where status=0 order by id limit 10') results = cursor.fetchall()", "id, entname from req where status=0 order by id limit", "res[1] companies.append(company) return companies def main(): my_queue = QueueRedis() result", "= QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出 if", "get_req_from_db() for id_name in source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message)", "from gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis import QueueRedis conn =", "= cursor.fetchall() companies = [] for res in results: company", "sys, os, json, time, pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from", "-*- coding: utf-8 -*- import pymysql import sys, os, json,", "None def connect_db(): global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def", "conn.cursor() cursor.execute('select id, entname from req where status=0 order by", "= conn.cursor() cursor.execute('select id, entname from req where status=0 order", "if result: time.sleep(3) exit() time.sleep(3) global conn connect_db() source =", "def connect_db(): global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db():", "global conn connect_db() source = get_req_from_db() for id_name in source:", "= {} company['id'] = res[0] company['name'] = res[1] companies.append(company) return", "get_req_from_db(): global conn cursor = conn.cursor() cursor.execute('select id, entname from", "results: company = {} company['id'] = res[0] company['name'] = res[1]", "for res in results: company = {} company['id'] = res[0]", "gjqyxyxxcxxt.database.my_redis import QueueRedis conn = None def connect_db(): global conn", "json, time, pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import", "return def get_req_from_db(): global conn cursor = conn.cursor() cursor.execute('select id,", "pymysql import sys, os, json, time, pymongo app_dir = os.path.abspath(\"../\")", "-*- import pymysql import sys, os, json, time, pymongo app_dir", "QueueRedis conn = None def connect_db(): global conn conn =", "json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!' % len(source) if __name__", "os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis import QueueRedis", "my_queue = QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出", "time.sleep(3) exit() time.sleep(3) global conn connect_db() source = get_req_from_db() for", "message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!' % len(source)", "[] for res in results: company = {} company['id'] =", "= get_req_from_db() for id_name in source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES,", "id_name in source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print", "result = my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出 if result: time.sleep(3)", "conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global conn cursor", "company['id'] = res[0] company['name'] = res[1] companies.append(company) return companies def", "companies def main(): my_queue = QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print", "= res[1] companies.append(company) return companies def main(): my_queue = QueueRedis()", "connect_db(): global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global", "limit 10') results = cursor.fetchall() companies = [] for res", "company = {} company['id'] = res[0] company['name'] = res[1] companies.append(company)", "result: time.sleep(3) exit() time.sleep(3) global conn connect_db() source = get_req_from_db()", "conn cursor = conn.cursor() cursor.execute('select id, entname from req where", "# -*- coding: utf-8 -*- import pymysql import sys, os,", "= os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import settings from gjqyxyxxcxxt.database.my_redis import", "source = get_req_from_db() for id_name in source: message = json.dumps(id_name)", "companies.append(company) return companies def main(): my_queue = QueueRedis() result =", "connect_db() source = get_req_from_db() for id_name in source: message =", "results = cursor.fetchall() companies = [] for res in results:", "#mq 里存在数据则,3秒后退出 if result: time.sleep(3) exit() time.sleep(3) global conn connect_db()", "= [] for res in results: company = {} company['id']", "message) conn.close() print '成功添加队列%s条数据!!!' % len(source) if __name__ == '__main__':", "= json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!' % len(source) if", "req where status=0 order by id limit 10') results =", "source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!' %", "conn.close() print '成功添加队列%s条数据!!!' % len(source) if __name__ == '__main__': main()", "conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\") return def get_req_from_db(): global conn cursor =", "= my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出 if result: time.sleep(3) exit()", "for id_name in source: message = json.dumps(id_name) my_queue.send_to_queue(settings.COMPANIES, message) conn.close()", "time, pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import settings", "conn = None def connect_db(): global conn conn = pymysql.connect(host=\"172.16.16.15\",port=3306,user=\"root\",passwd=\"<PASSWORD>\",db=\"ixinnuo_sjcj\",charset=\"utf8\")", "id limit 10') results = cursor.fetchall() companies = [] for", "os, json, time, pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt", "import pymysql import sys, os, json, time, pymongo app_dir =", "cursor.execute('select id, entname from req where status=0 order by id", "my_queue.send_to_queue(settings.COMPANIES, message) conn.close() print '成功添加队列%s条数据!!!' % len(source) if __name__ ==", "pymongo app_dir = os.path.abspath(\"../\") sys.path.append(app_dir) from gjqyxyxxcxxt import settings from", "conn connect_db() source = get_req_from_db() for id_name in source: message", "print result #mq 里存在数据则,3秒后退出 if result: time.sleep(3) exit() time.sleep(3) global", "global conn cursor = conn.cursor() cursor.execute('select id, entname from req", "QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出 if result:", "status=0 order by id limit 10') results = cursor.fetchall() companies", "order by id limit 10') results = cursor.fetchall() companies =", "return companies def main(): my_queue = QueueRedis() result = my_queue.get_queue_length(settings.COMPANIES)", "my_queue.get_queue_length(settings.COMPANIES) print result #mq 里存在数据则,3秒后退出 if result: time.sleep(3) exit() time.sleep(3)" ]
[ "% check_tx_url) r = requests.get(check_tx_url) data = json.loads(r.text) print('RESPONSE: %s\\n'", "import time from http import HTTPStatus # Main if __name__", "'http://localhost:9119/%s' % set_cmd headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND:", "= json.loads(r.text) print('RESPONSE: %s\\n' % data) # Wait some seconds", "Importing section import json import requests import argparse import hashlib", "the transaction has been handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' %", "'sla04', 'start': 3000, 'end': 3900 } cmd_url = 'http://localhost:9119/%s' %", "print('PARAMS: %s' % params) r = requests.post(cmd_url, headers=headers, json=params) data", "section import json import requests import argparse import hashlib import", "time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX: %s' %", "to be sure that the transaction has been handled time.sleep(5)", "params) r = requests.post(cmd_url, headers=headers, json=params) data = json.loads(r.text) print('RESPONSE:", "% data['tx_hash'] print('CHECK TX: %s' % check_tx_url) r = requests.get(check_tx_url)", "import hashlib import time from http import HTTPStatus # Main", "set_cmd = 'updateSla' params = { 'idx': 'sla04', 'start': 3000,", "headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND: %s' % cmd_url)", "import json import requests import argparse import hashlib import time", "argparse import hashlib import time from http import HTTPStatus #", "'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX: %s' % check_tx_url) r =", "%s' % cmd_url) print('PARAMS: %s' % params) r = requests.post(cmd_url,", "'application/json'} print('COMMAND: %s' % cmd_url) print('PARAMS: %s' % params) r", "cmd_url = 'http://localhost:9119/%s' % set_cmd headers = {'Content-Type': 'application/json', 'Accept':", "time from http import HTTPStatus # Main if __name__ ==", "Wait some seconds to be sure that the transaction has", "% params) r = requests.post(cmd_url, headers=headers, json=params) data = json.loads(r.text)", "if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() args = arg_parser.parse_args()", "print('RESPONSE: %s\\n' % data) # Wait some seconds to be", "% cmd_url) print('PARAMS: %s' % params) r = requests.post(cmd_url, headers=headers,", "arg_parser = argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd = 'updateSla' params", "\"__main__\": arg_parser = argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd = 'updateSla'", "handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX: %s'", "from http import HTTPStatus # Main if __name__ == \"__main__\":", "TX: %s' % check_tx_url) r = requests.get(check_tx_url) data = json.loads(r.text)", "import argparse import hashlib import time from http import HTTPStatus", "http import HTTPStatus # Main if __name__ == \"__main__\": arg_parser", "= argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd = 'updateSla' params =", "argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd = 'updateSla' params = {", "params = { 'idx': 'sla04', 'start': 3000, 'end': 3900 }", "% set_cmd headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND: %s'", "3000, 'end': 3900 } cmd_url = 'http://localhost:9119/%s' % set_cmd headers", "data = json.loads(r.text) print('RESPONSE: %s\\n' % data) # Wait some", "r = requests.get(check_tx_url) data = json.loads(r.text) print('RESPONSE: %s\\n' % data)", "HTTPStatus # Main if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser()", "sure that the transaction has been handled time.sleep(5) check_tx_url =", "headers=headers, json=params) data = json.loads(r.text) print('RESPONSE: %s\\n' % data) #", "check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX: %s' % check_tx_url)", "data) # Wait some seconds to be sure that the", "has been handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK", "__name__ == \"__main__\": arg_parser = argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd", "{ 'idx': 'sla04', 'start': 3000, 'end': 3900 } cmd_url =", "print('COMMAND: %s' % cmd_url) print('PARAMS: %s' % params) r =", "%s\\n' % data) # Wait some seconds to be sure", "json=params) data = json.loads(r.text) print('RESPONSE: %s\\n' % data) # Wait", "check_tx_url) r = requests.get(check_tx_url) data = json.loads(r.text) print('RESPONSE: %s\\n' %", "cmd_url) print('PARAMS: %s' % params) r = requests.post(cmd_url, headers=headers, json=params)", "json.loads(r.text) print('RESPONSE: %s\\n' % data) # Wait some seconds to", "json import requests import argparse import hashlib import time from", "import HTTPStatus # Main if __name__ == \"__main__\": arg_parser =", "'idx': 'sla04', 'start': 3000, 'end': 3900 } cmd_url = 'http://localhost:9119/%s'", "that the transaction has been handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s'", "r = requests.post(cmd_url, headers=headers, json=params) data = json.loads(r.text) print('RESPONSE: %s\\n'", "== \"__main__\": arg_parser = argparse.ArgumentParser() args = arg_parser.parse_args() set_cmd =", "} cmd_url = 'http://localhost:9119/%s' % set_cmd headers = {'Content-Type': 'application/json',", "'application/json', 'Accept': 'application/json'} print('COMMAND: %s' % cmd_url) print('PARAMS: %s' %", "some seconds to be sure that the transaction has been", "%s' % params) r = requests.post(cmd_url, headers=headers, json=params) data =", "seconds to be sure that the transaction has been handled", "= { 'idx': 'sla04', 'start': 3000, 'end': 3900 } cmd_url", "= arg_parser.parse_args() set_cmd = 'updateSla' params = { 'idx': 'sla04',", "'Accept': 'application/json'} print('COMMAND: %s' % cmd_url) print('PARAMS: %s' % params)", "= 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX: %s' % check_tx_url) r", "{'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND: %s' % cmd_url) print('PARAMS: %s'", "Main if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() args =", "print('CHECK TX: %s' % check_tx_url) r = requests.get(check_tx_url) data =", "requests.post(cmd_url, headers=headers, json=params) data = json.loads(r.text) print('RESPONSE: %s\\n' % data)", "= requests.post(cmd_url, headers=headers, json=params) data = json.loads(r.text) print('RESPONSE: %s\\n' %", "= {'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND: %s' % cmd_url) print('PARAMS:", "be sure that the transaction has been handled time.sleep(5) check_tx_url", "args = arg_parser.parse_args() set_cmd = 'updateSla' params = { 'idx':", "= 'updateSla' params = { 'idx': 'sla04', 'start': 3000, 'end':", "requests import argparse import hashlib import time from http import", "% data) # Wait some seconds to be sure that", "# Wait some seconds to be sure that the transaction", "3900 } cmd_url = 'http://localhost:9119/%s' % set_cmd headers = {'Content-Type':", "'start': 3000, 'end': 3900 } cmd_url = 'http://localhost:9119/%s' % set_cmd", "# Main if __name__ == \"__main__\": arg_parser = argparse.ArgumentParser() args", "import requests import argparse import hashlib import time from http", "'end': 3900 } cmd_url = 'http://localhost:9119/%s' % set_cmd headers =", "%s' % check_tx_url) r = requests.get(check_tx_url) data = json.loads(r.text) print('RESPONSE:", "set_cmd headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} print('COMMAND: %s' %", "transaction has been handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash']", "'updateSla' params = { 'idx': 'sla04', 'start': 3000, 'end': 3900", "been handled time.sleep(5) check_tx_url = 'http://localhost:9119/checkTx/%s' % data['tx_hash'] print('CHECK TX:", "# Importing section import json import requests import argparse import", "hashlib import time from http import HTTPStatus # Main if", "= 'http://localhost:9119/%s' % set_cmd headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}", "arg_parser.parse_args() set_cmd = 'updateSla' params = { 'idx': 'sla04', 'start':", "data['tx_hash'] print('CHECK TX: %s' % check_tx_url) r = requests.get(check_tx_url) data" ]
[ "end: # Swap all positive value with last index end", "\"__main__\": arr = [-1, 2, -3, 4, 5, 6, -7,", "def sort(arr): # Start index 0. start = 0 #", "index 0. start = 0 # End index end =", "while start <= end: # Swap all positive value with", "if __name__ == \"__main__\": arr = [-1, 2, -3, 4,", "start by 1. start += 1 if __name__ == \"__main__\":", "1. start += 1 if __name__ == \"__main__\": arr =", "len(arr)-1 while start <= end: # Swap all positive value", "arr[end], arr[start] end -= 1 else: # If arr[start] is", "start <= end: # Swap all positive value with last", "[-1, 2, -3, 4, 5, 6, -7, 8, 9] sort(arr)", "# If arr[start] is not positive then increase start by", "1 else: # If arr[start] is not positive then increase", "= len(arr)-1 while start <= end: # Swap all positive", "by 1. start += 1 if __name__ == \"__main__\": arr", "decrease end by 1. if arr[start] >= 0: arr[start], arr[end]", "Swap all positive value with last index end & decrease", "0 # End index end = len(arr)-1 while start <=", "2, -3, 4, 5, 6, -7, 8, 9] sort(arr) print(arr)", "End index end = len(arr)-1 while start <= end: #", "arr = [-1, 2, -3, 4, 5, 6, -7, 8,", "index end & decrease end by 1. if arr[start] >=", "is not positive then increase start by 1. start +=", "start += 1 if __name__ == \"__main__\": arr = [-1,", "arr[end] = arr[end], arr[start] end -= 1 else: # If", "else: # If arr[start] is not positive then increase start", "1 if __name__ == \"__main__\": arr = [-1, 2, -3,", "If arr[start] is not positive then increase start by 1.", "Start index 0. start = 0 # End index end", "all positive value with last index end & decrease end", "end & decrease end by 1. if arr[start] >= 0:", "value with last index end & decrease end by 1.", "__name__ == \"__main__\": arr = [-1, 2, -3, 4, 5,", "start = 0 # End index end = len(arr)-1 while", "== \"__main__\": arr = [-1, 2, -3, 4, 5, 6,", "1. if arr[start] >= 0: arr[start], arr[end] = arr[end], arr[start]", ">= 0: arr[start], arr[end] = arr[end], arr[start] end -= 1", "last index end & decrease end by 1. if arr[start]", "with last index end & decrease end by 1. if", "end = len(arr)-1 while start <= end: # Swap all", "0. start = 0 # End index end = len(arr)-1", "if arr[start] >= 0: arr[start], arr[end] = arr[end], arr[start] end", "+= 1 if __name__ == \"__main__\": arr = [-1, 2,", "then increase start by 1. start += 1 if __name__", "<= end: # Swap all positive value with last index", "by 1. if arr[start] >= 0: arr[start], arr[end] = arr[end],", "end by 1. if arr[start] >= 0: arr[start], arr[end] =", "# Swap all positive value with last index end &", "arr[start], arr[end] = arr[end], arr[start] end -= 1 else: #", "arr[start] end -= 1 else: # If arr[start] is not", "positive then increase start by 1. start += 1 if", "positive value with last index end & decrease end by", "<reponame>jitendragangwar123/cp def sort(arr): # Start index 0. start = 0", "index end = len(arr)-1 while start <= end: # Swap", "# Start index 0. start = 0 # End index", "# End index end = len(arr)-1 while start <= end:", "sort(arr): # Start index 0. start = 0 # End", "0: arr[start], arr[end] = arr[end], arr[start] end -= 1 else:", "= arr[end], arr[start] end -= 1 else: # If arr[start]", "end -= 1 else: # If arr[start] is not positive", "-= 1 else: # If arr[start] is not positive then", "arr[start] is not positive then increase start by 1. start", "increase start by 1. start += 1 if __name__ ==", "= [-1, 2, -3, 4, 5, 6, -7, 8, 9]", "= 0 # End index end = len(arr)-1 while start", "arr[start] >= 0: arr[start], arr[end] = arr[end], arr[start] end -=", "& decrease end by 1. if arr[start] >= 0: arr[start],", "not positive then increase start by 1. start += 1" ]
[ "in enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i >", "json def __text_from_anchor_sents_file(anchor_sents_file, output_file): f = open(anchor_sents_file, encoding='utf-8') fout =", "encoding='utf-8') for line in f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file =", "sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i > 5: #", "i, line in enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if", "import json def __text_from_anchor_sents_file(anchor_sents_file, output_file): f = open(anchor_sents_file, encoding='utf-8') fout", "def __text_from_anchor_sents_file(anchor_sents_file, output_file): f = open(anchor_sents_file, encoding='utf-8') fout = open(output_file,", "encoding='utf-8', newline='\\n') for i, line in enumerate(f): sent = json.loads(line)", "output_file): f = open(anchor_sents_file, encoding='utf-8') fout = open(output_file, 'w', encoding='utf-8',", "# if i > 5: # break f.close() fout.close() def", "for filename in filenames: print(filename) f = open(filename, encoding='utf-8') for", "line in enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i", "in f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file =", "f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt'", "open(filename, encoding='utf-8') for line in f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file", "= open(output_file, 'w', encoding='utf-8', newline='\\n') for filename in filenames: print(filename)", "= open(anchor_sents_file, encoding='utf-8') fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for", "= json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i > 5: # break", "# __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)]", "'d:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt'", "= 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i", "<gh_stars>0 import json def __text_from_anchor_sents_file(anchor_sents_file, output_file): f = open(anchor_sents_file, encoding='utf-8')", "'w', encoding='utf-8', newline='\\n') for filename in filenames: print(filename) f =", "'w', encoding='utf-8', newline='\\n') for i, line in enumerate(f): sent =", "i > 5: # break f.close() fout.close() def merge_files(filenames, output_file):", "> 5: # break f.close() fout.close() def merge_files(filenames, output_file): fout", "filenames: print(filename) f = open(filename, encoding='utf-8') for line in f:", "break f.close() fout.close() def merge_files(filenames, output_file): fout = open(output_file, 'w',", "= 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files =", "output_file): fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for filename in", "wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files", "fout.write('{}\\n'.format(sent['tokens'])) # if i > 5: # break f.close() fout.close()", "for i in range(4)] pos_tag_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos.txt' # merge_files(part_pos_tag_files, pos_tag_file)", "open(anchor_sents_file, encoding='utf-8') fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for i,", "def merge_files(filenames, output_file): fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for", "merge_files(filenames, output_file): fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for filename", "f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file,", "fout.write(line) f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' #", "[f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)] pos_tag_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos.txt' # merge_files(part_pos_tag_files,", "encoding='utf-8') fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for i, line", "encoding='utf-8', newline='\\n') for filename in filenames: print(filename) f = open(filename,", "f = open(filename, encoding='utf-8') for line in f: fout.write(line) f.close()", "fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for i, line in", "for i, line in enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) #", "= open(output_file, 'w', encoding='utf-8', newline='\\n') for i, line in enumerate(f):", "in filenames: print(filename) f = open(filename, encoding='utf-8') for line in", "'d:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in", "open(output_file, 'w', encoding='utf-8', newline='\\n') for i, line in enumerate(f): sent", "anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)] pos_tag_file =", "print(filename) f = open(filename, encoding='utf-8') for line in f: fout.write(line)", "newline='\\n') for filename in filenames: print(filename) f = open(filename, encoding='utf-8')", "f = open(anchor_sents_file, encoding='utf-8') fout = open(output_file, 'w', encoding='utf-8', newline='\\n')", "# break f.close() fout.close() def merge_files(filenames, output_file): fout = open(output_file,", "part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)] pos_tag_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos.txt'", "enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i > 5:", "open(output_file, 'w', encoding='utf-8', newline='\\n') for filename in filenames: print(filename) f", "newline='\\n') for i, line in enumerate(f): sent = json.loads(line) fout.write('{}\\n'.format(sent['tokens']))", "for line in f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt'", "line in f: fout.write(line) f.close() fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file", "__text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)] pos_tag_file", "fout = open(output_file, 'w', encoding='utf-8', newline='\\n') for filename in filenames:", "fout.close() def merge_files(filenames, output_file): fout = open(output_file, 'w', encoding='utf-8', newline='\\n')", "json.loads(line) fout.write('{}\\n'.format(sent['tokens'])) # if i > 5: # break f.close()", "f.close() fout.close() def merge_files(filenames, output_file): fout = open(output_file, 'w', encoding='utf-8',", "filename in filenames: print(filename) f = open(filename, encoding='utf-8') for line", "= [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for i in range(4)] pos_tag_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos.txt' #", "= open(filename, encoding='utf-8') for line in f: fout.write(line) f.close() fout.close()", "anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file) part_pos_tag_files = [f'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts-pos-{i}.txt' for", "5: # break f.close() fout.close() def merge_files(filenames, output_file): fout =", "fout.close() wiki19_anchor_sents_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents.txt' anchor_sent_texts_file = 'd:/data/res/wiki/anchor/enwiki-20190101-anchor-sents-tok-texts.txt' # __text_from_anchor_sents_file(wiki19_anchor_sents_file, anchor_sent_texts_file)", "__text_from_anchor_sents_file(anchor_sents_file, output_file): f = open(anchor_sents_file, encoding='utf-8') fout = open(output_file, 'w',", "if i > 5: # break f.close() fout.close() def merge_files(filenames," ]
[ "import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import", "'1']) # Test openProcess by opening a Plumber process def", "return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) #", "test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1'])", "\"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) # Test openProcess by", "import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' +", "cannr import smp # Test openProcess by opening a Flask", "return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R',", "'/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) # Test countPorts def test_countPorts(): projectFilePath", "Flask process def test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr", "sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH']", "openProcess by opening a Flask process def test_openProcess1(): return smp.openProcess(", "'5001', '2']) # Test countPorts def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM", "smp # Test openProcess by opening a Flask process def", "\"\"\" import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:'", "by opening a Plumber process def test_openProcess2(): return smp.openProcess( {\"processInfo\":", "Image/test/flaskSample.py', '5000', '1']) # Test openProcess by opening a Plumber", "a Plumber process def test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript',", "Image/test/hello.R', '5001', '2']) # Test countPorts def test_countPorts(): projectFilePath =", "= '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr import smp # Test", "# Test openProcess by opening a Flask process def test_openProcess1():", "os.environ['PATH'] import cannr import smp # Test openProcess by opening", "process def test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr", "opening a Plumber process def test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"},", "os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr", "\"\"\" Test harness for smp.py \"\"\" import sys import os", "+ os.environ['PATH'] import cannr import smp # Test openProcess by", "smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) # Test", "'/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) # Test countPorts def", "by opening a Flask process def test_openProcess1(): return smp.openProcess( {\"processInfo\":", "countPorts def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json' project = cannr.readJSONFile(projectFilePath)", "def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json' project = cannr.readJSONFile(projectFilePath) return", "openProcess by opening a Plumber process def test_openProcess2(): return smp.openProcess(", "test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr", "['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) # Test openProcess by opening", "'2']) # Test countPorts def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json'", "Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) # Test countPorts def test_countPorts():", "'/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) # Test openProcess by opening a", "{\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000', '1']) # Test openProcess", "a Flask process def test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python',", "{\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2'])", "harness for smp.py \"\"\" import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib')", "opening a Flask process def test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"},", "smp.py \"\"\" import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] =", "Test countPorts def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json' project =", "def test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py', '5000',", "Test harness for smp.py \"\"\" import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr", "Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr import smp", "import cannr import smp # Test openProcess by opening a", "import smp # Test openProcess by opening a Flask process", "Test openProcess by opening a Plumber process def test_openProcess2(): return", "os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr import smp #", "# Test openProcess by opening a Plumber process def test_openProcess2():", "Test openProcess by opening a Flask process def test_openProcess1(): return", "'/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr import smp # Test openProcess", "def test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R',", "smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001',", "['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) # Test", "sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH'] = '/Library/Frameworks/Python.framework/Versions/3.7/bin:' + os.environ['PATH'] import cannr import", "'--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) # Test countPorts", "# Test countPorts def test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json' project", "test_countPorts(): projectFilePath = '/Users/ptendick/open-source-workspace/MyRTAM Service/working/project1/project.json' project = cannr.readJSONFile(projectFilePath) return smp.countPorts(project)", "process def test_openProcess1(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['python', '/Users/ptendick/open-source-workspace/cannr Image/test/flaskSample.py',", "\"processInfo\"}, ['Rscript', '--vanilla', '/Users/ptendick/open-source-workspace/cannr Image/source/cannr/runApp.R', '/Users/ptendick/open-source-workspace/cannr Image/test/hello.R', '5001', '2']) #", "Plumber process def test_openProcess2(): return smp.openProcess( {\"processInfo\": \"processInfo\"}, ['Rscript', '--vanilla',", "for smp.py \"\"\" import sys import os sys.path.append('/Users/ptendick/open-source-workspace/cannr Image/source/cannr/lib') os.environ['PATH']", "'5000', '1']) # Test openProcess by opening a Plumber process" ]
[ "# current_resnet = resnet_v1.resnet_v1_152 # else: # raise ValueError(\"Unsupported resnet", "image_input: placeholder with image :param is_training: are you using the", "or test_time :param scope: tensorflow scope :param resnet_version: 50/101/152 :param", "as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils", "arg_sc: return arg_sc def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None):", "arg_sc = inception_v1.inception_v1_arg_scope() # Pick the correct version of the", "import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1", "following config -> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc =", "the resnet # if resnet_version == 50: # current_resnet =", "# raise ValueError(\"Unsupported resnet version\") # inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out)", "= resnet_v1.resnet_v1_101 # elif resnet_version == 152: # current_resnet =", "= slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope() # Pick", "import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib import layers as layers_lib", "overidding the classic batchnorm with conditional batchnorm :param image_input: placeholder", "os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\") inception_scope = inception_out # print(\"", "with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please use the", "# print(\"--- 5\") # print(end_points) print(\" Batch \",inception_scope) out =", ":param scope: tensorflow scope :param resnet_version: 50/101/152 :param cbn: the", "# current_resnet = resnet_v1.resnet_v1_50 # elif resnet_version == 101: #", "out = end_points[scope + inception_scope] print(\"-- out Use: {},output =", "'excluded_scope_names': ['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc", "with image :param is_training: are you using the resnet at", "cbn factory :return: the resnet output \"\"\" # assert False,", "tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as", "bn_fn: cbn factory :return: tensorflow scope \"\"\" with arg_scope( [layers_lib.conv2d],", "# print(\"--- 4\") if len(scope) > 0 and not scope.endswith(\"/\"):", ":param cbn: the cbn factory :return: the resnet output \"\"\"", "factory :return: the resnet output \"\"\" # assert False, \"\\n\"", "from tensorflow.contrib.framework.python.ops import arg_scope import os def get_resnet_arg_scope(bn_fn): \"\"\" Trick", "4\") if len(scope) > 0 and not scope.endswith(\"/\"): scope +=", "# 1000 is the number of softmax class print(\"Net =", "import tensorflow as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1", "[layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return arg_sc def create_inception(image_input,", "is a bug with classic batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887).", "\"There is a bug with classic batchnorm with slim networks", "as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1", "# \"Please use the following config -> 'cbn': {'use_cbn':true, 'excluded_scope_names':", "\\n\" \\ # \"Please use the following config -> 'cbn':", "normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return arg_sc def create_inception(image_input, is_training, scope=\"\",", "inception_v1.inception_v1(image_input, 1001) # 1000 is the number of softmax class", "\",inception_scope) out = end_points[scope + inception_scope] print(\"-- out Use: {},output", "assert False, \"\\n\" \\ # \"There is a bug with", "at training_time or test_time :param scope: tensorflow scope :param resnet_version:", "tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as", "constructor with cbn :param bn_fn: cbn factory :return: tensorflow scope", "of softmax class print(\"Net = \",net) # print(\"--- 4\") if", "if len(scope) > 0 and not scope.endswith(\"/\"): scope += \"/\"", "using the resnet at training_time or test_time :param scope: tensorflow", "are you using the resnet at training_time or test_time :param", "normalizer_params=None) as arg_sc: return arg_sc def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\",", "def get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply CBN from a pretrained", "= inception_v1.inception_v1_arg_scope() # Pick the correct version of the resnet", "-> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) #", "['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc =", "correct version of the resnet # if resnet_version == 50:", "raise ValueError(\"Unsupported resnet version\") # inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) #", "inception_scope = inception_out # print(\" resnet_out = {} , resnet_scope", "import arg_scope import os def get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply", "overides the batchnorm constructor with cbn :param bn_fn: cbn factory", "as slim_utils from tensorflow.contrib import layers as layers_lib from tensorflow.contrib.framework.python.ops", "scope.endswith(\"/\"): scope += \"/\" # print(\"--- 5\") # print(end_points) print(\"", "to apply CBN from a pretrained tf network. It overides", "arg_sc def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create", "with conditional batchnorm :param image_input: placeholder with image :param is_training:", "batchnorm :param image_input: placeholder with image :param is_training: are you", "classic batchnorm with conditional batchnorm :param image_input: placeholder with image", "# arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope()", "resnet output \"\"\" # assert False, \"\\n\" \\ # \"There", "5\") # print(end_points) print(\" Batch \",inception_scope) out = end_points[scope +", "inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\") inception_scope = inception_out", "resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with slim.arg_scope(arg_sc): net, end_points", "tensorflow scope :param resnet_version: 50/101/152 :param cbn: the cbn factory", "resnet_v1.resnet_v1_50 # elif resnet_version == 101: # current_resnet = resnet_v1.resnet_v1_101", "net, end_points = inception_v1.inception_v1(image_input, 1001) # 1000 is the number", "print(\"--- 2\") inception_scope = inception_out # print(\" resnet_out = {}", "slim_utils from tensorflow.contrib import layers as layers_lib from tensorflow.contrib.framework.python.ops import", "apply CBN from a pretrained tf network. It overides the", "tensorflow as tf import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as", "as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1", "cbn factory :return: tensorflow scope \"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu,", "resnet version\") # inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\")", "resnet_version=50, cbn=None): \"\"\" Create a resnet by overidding the classic", "as arg_sc: return arg_sc def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50,", "create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create a resnet", "\"\"\" Create a resnet by overidding the classic batchnorm with", "the resnet at training_time or test_time :param scope: tensorflow scope", "not scope.endswith(\"/\"): scope += \"/\" # print(\"--- 5\") # print(end_points)", "== 152: # current_resnet = resnet_v1.resnet_v1_152 # else: # raise", "import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils", "you using the resnet at training_time or test_time :param scope:", "Pick the correct version of the resnet # if resnet_version", "from a pretrained tf network. It overides the batchnorm constructor", "1000 is the number of softmax class print(\"Net = \",net)", "the classic batchnorm with conditional batchnorm :param image_input: placeholder with", "scope: tensorflow scope :param resnet_version: 50/101/152 :param cbn: the cbn", "# else: # raise ValueError(\"Unsupported resnet version\") # inception_scope =", ":return: the resnet output \"\"\" # assert False, \"\\n\" \\", "elif resnet_version == 152: # current_resnet = resnet_v1.resnet_v1_152 # else:", "is_training: are you using the resnet at training_time or test_time", "print(\"--- 4\") if len(scope) > 0 and not scope.endswith(\"/\"): scope", "tf import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import", "(https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please use the following config ->", "import layers as layers_lib from tensorflow.contrib.framework.python.ops import arg_scope import os", "tensorflow.contrib.framework.python.ops import arg_scope import os def get_resnet_arg_scope(bn_fn): \"\"\" Trick to", "from tensorflow.contrib import layers as layers_lib from tensorflow.contrib.framework.python.ops import arg_scope", "# if resnet_version == 50: # current_resnet = resnet_v1.resnet_v1_50 #", ":param is_training: are you using the resnet at training_time or", "end_points = inception_v1.inception_v1(image_input, 1001) # 1000 is the number of", "50/101/152 :param cbn: the cbn factory :return: the resnet output", "\"\"\" Trick to apply CBN from a pretrained tf network.", "tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib import layers as layers_lib from", "conditional batchnorm :param image_input: placeholder with image :param is_training: are", "factory :return: tensorflow scope \"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn,", "with classic batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ #", "= {} , resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with", "layers_lib from tensorflow.contrib.framework.python.ops import arg_scope import os def get_resnet_arg_scope(bn_fn): \"\"\"", "with slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input, 1001) # 1000 is", "50: # current_resnet = resnet_v1.resnet_v1_50 # elif resnet_version == 101:", "if resnet_version == 50: # current_resnet = resnet_v1.resnet_v1_50 # elif", "arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope() #", "# print(end_points) print(\" Batch \",inception_scope) out = end_points[scope + inception_scope]", ":param resnet_version: 50/101/152 :param cbn: the cbn factory :return: the", "training_time or test_time :param scope: tensorflow scope :param resnet_version: 50/101/152", "1001) # 1000 is the number of softmax class print(\"Net", "resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from", "= inception_v1.inception_v1(image_input, 1001) # 1000 is the number of softmax", "softmax class print(\"Net = \",net) # print(\"--- 4\") if len(scope)", "print(\"Net = \",net) # print(\"--- 4\") if len(scope) > 0", "\"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return", "= os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\") inception_scope = inception_out #", "tensorflow.contrib import layers as layers_lib from tensorflow.contrib.framework.python.ops import arg_scope import", "batchnorm constructor with cbn :param bn_fn: cbn factory :return: tensorflow", "scope \"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc:", "slim import tensorflow.contrib.slim.python.slim.nets.resnet_v1 as resnet_v1 import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import", "== 50: # current_resnet = resnet_v1.resnet_v1_50 # elif resnet_version ==", "use the following config -> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" #", "0 and not scope.endswith(\"/\"): scope += \"/\" # print(\"--- 5\")", "Create a resnet by overidding the classic batchnorm with conditional", "placeholder with image :param is_training: are you using the resnet", "layers as layers_lib from tensorflow.contrib.framework.python.ops import arg_scope import os def", "'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"---", "version of the resnet # if resnet_version == 50: #", "the number of softmax class print(\"Net = \",net) # print(\"---", "current_resnet = resnet_v1.resnet_v1_50 # elif resnet_version == 101: # current_resnet", "cbn=None): \"\"\" Create a resnet by overidding the classic batchnorm", "inception_out) # print(\"--- 2\") inception_scope = inception_out # print(\" resnet_out", "network. It overides the batchnorm constructor with cbn :param bn_fn:", "# current_resnet = resnet_v1.resnet_v1_101 # elif resnet_version == 152: #", "and not scope.endswith(\"/\"): scope += \"/\" # print(\"--- 5\") #", "is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create a resnet by", "print(\"--- 3\") with slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input, 1001) #", "the correct version of the resnet # if resnet_version ==", "elif resnet_version == 101: # current_resnet = resnet_v1.resnet_v1_101 # elif", "class print(\"Net = \",net) # print(\"--- 4\") if len(scope) >", "\"/\" # print(\"--- 5\") # print(end_points) print(\" Batch \",inception_scope) out", "resnet # if resnet_version == 50: # current_resnet = resnet_v1.resnet_v1_50", "# print(\"--- 3\") with slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input, 1001)", "resnet_version == 101: # current_resnet = resnet_v1.resnet_v1_101 # elif resnet_version", "inception_out # print(\" resnet_out = {} , resnet_scope = {}\".format(resnet_out,resnet_scope))", "end_points[scope + inception_scope] print(\"-- out Use: {},output = {}\".format(inception_scope,out)) return", "== 101: # current_resnet = resnet_v1.resnet_v1_101 # elif resnet_version ==", "CBN from a pretrained tf network. It overides the batchnorm", ":param bn_fn: cbn factory :return: tensorflow scope \"\"\" with arg_scope(", "batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please use", "= {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with slim.arg_scope(arg_sc): net, end_points =", "import os def get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply CBN from", "tf network. It overides the batchnorm constructor with cbn :param", "bug with classic batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\", "else: # raise ValueError(\"Unsupported resnet version\") # inception_scope = os.path.join('InceptionV1/InceptionV1',", "the batchnorm constructor with cbn :param bn_fn: cbn factory :return:", "pretrained tf network. It overides the batchnorm constructor with cbn", "\"\\n\" \\ # \"There is a bug with classic batchnorm", "= \",net) # print(\"--- 4\") if len(scope) > 0 and", "with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return arg_sc", "activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return arg_sc def create_inception(image_input, is_training,", "101: # current_resnet = resnet_v1.resnet_v1_101 # elif resnet_version == 152:", "networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please use the following config", "is the number of softmax class print(\"Net = \",net) #", "Batch \",inception_scope) out = end_points[scope + inception_scope] print(\"-- out Use:", "as layers_lib from tensorflow.contrib.framework.python.ops import arg_scope import os def get_resnet_arg_scope(bn_fn):", "It overides the batchnorm constructor with cbn :param bn_fn: cbn", "current_resnet = resnet_v1.resnet_v1_101 # elif resnet_version == 152: # current_resnet", "print(\"--- 5\") # print(end_points) print(\" Batch \",inception_scope) out = end_points[scope", "# print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope() # Pick the correct", "resnet_v1.resnet_v1_101 # elif resnet_version == 152: # current_resnet = resnet_v1.resnet_v1_152", "print(\" Batch \",inception_scope) out = end_points[scope + inception_scope] print(\"-- out", "os def get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply CBN from a", "a pretrained tf network. It overides the batchnorm constructor with", "a resnet by overidding the classic batchnorm with conditional batchnorm", "scope += \"/\" # print(\"--- 5\") # print(end_points) print(\" Batch", "resnet_version == 50: # current_resnet = resnet_v1.resnet_v1_50 # elif resnet_version", "cbn :param bn_fn: cbn factory :return: tensorflow scope \"\"\" with", "resnet by overidding the classic batchnorm with conditional batchnorm :param", "resnet at training_time or test_time :param scope: tensorflow scope :param", "the cbn factory :return: the resnet output \"\"\" # assert", "test_time :param scope: tensorflow scope :param resnet_version: 50/101/152 :param cbn:", "# print(\" resnet_out = {} , resnet_scope = {}\".format(resnet_out,resnet_scope)) #", "current_resnet = resnet_v1.resnet_v1_152 # else: # raise ValueError(\"Unsupported resnet version\")", "inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib import layers as", "tensorflow scope \"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as", "slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please use the following", "resnet_version: 50/101/152 :param cbn: the cbn factory :return: the resnet", "config -> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training)", "\",net) # print(\"--- 4\") if len(scope) > 0 and not", "the following config -> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc", "= end_points[scope + inception_scope] print(\"-- out Use: {},output = {}\".format(inception_scope,out))", "as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib import layers", "resnet_version == 152: # current_resnet = resnet_v1.resnet_v1_152 # else: #", "print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope() # Pick the correct version", "import tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib", "\"Please use the following config -> 'cbn': {'use_cbn':true, 'excluded_scope_names': ['*']}\"", "number of softmax class print(\"Net = \",net) # print(\"--- 4\")", "return arg_sc def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\"", "print(end_points) print(\" Batch \",inception_scope) out = end_points[scope + inception_scope] print(\"--", "# inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\") inception_scope =", "152: # current_resnet = resnet_v1.resnet_v1_152 # else: # raise ValueError(\"Unsupported", "= inception_out # print(\" resnet_out = {} , resnet_scope =", "False, \"\\n\" \\ # \"There is a bug with classic", "= resnet_v1.resnet_v1_50 # elif resnet_version == 101: # current_resnet =", "ValueError(\"Unsupported resnet version\") # inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"---", "cbn: the cbn factory :return: the resnet output \"\"\" #", "with cbn :param bn_fn: cbn factory :return: tensorflow scope \"\"\"", "\\ # \"Please use the following config -> 'cbn': {'use_cbn':true,", "slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\") arg_sc = inception_v1.inception_v1_arg_scope() # Pick the", "{}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input,", ", resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with slim.arg_scope(arg_sc): net,", "def create_inception(image_input, is_training, scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create a", "{} , resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\") with slim.arg_scope(arg_sc):", "# elif resnet_version == 101: # current_resnet = resnet_v1.resnet_v1_101 #", "len(scope) > 0 and not scope.endswith(\"/\"): scope += \"/\" #", "# assert False, \"\\n\" \\ # \"There is a bug", "{'use_cbn':true, 'excluded_scope_names': ['*']}\" # arg_sc = slim_utils.resnet_arg_scope(is_training=is_training) # print(\"--- 1\")", "inception_v1.inception_v1_arg_scope() # Pick the correct version of the resnet #", "# print(\"--- 2\") inception_scope = inception_out # print(\" resnet_out =", "> 0 and not scope.endswith(\"/\"): scope += \"/\" # print(\"---", "# elif resnet_version == 152: # current_resnet = resnet_v1.resnet_v1_152 #", ":return: tensorflow scope \"\"\" with arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None)", "scope=\"\", inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create a resnet by overidding", "Trick to apply CBN from a pretrained tf network. It", "3\") with slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input, 1001) # 1000", "+ inception_scope] print(\"-- out Use: {},output = {}\".format(inception_scope,out)) return out,end_points", "= resnet_v1.resnet_v1_152 # else: # raise ValueError(\"Unsupported resnet version\") #", "get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply CBN from a pretrained tf", "# Pick the correct version of the resnet # if", "by overidding the classic batchnorm with conditional batchnorm :param image_input:", "+= \"/\" # print(\"--- 5\") # print(end_points) print(\" Batch \",inception_scope)", "the resnet output \"\"\" # assert False, \"\\n\" \\ #", "version\") # inception_scope = os.path.join('InceptionV1/InceptionV1', inception_out) # print(\"--- 2\") inception_scope", "batchnorm with conditional batchnorm :param image_input: placeholder with image :param", "\\ # \"There is a bug with classic batchnorm with", "resnet_v1.resnet_v1_152 # else: # raise ValueError(\"Unsupported resnet version\") # inception_scope", "inception_out=\"Mixed_5c\", resnet_version=50, cbn=None): \"\"\" Create a resnet by overidding the", "a bug with classic batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\"", "of the resnet # if resnet_version == 50: # current_resnet", "arg_scope import os def get_resnet_arg_scope(bn_fn): \"\"\" Trick to apply CBN", "tensorflow.contrib.slim.python.slim.nets.inception_v1 as inception_v1 import tensorflow.contrib.slim.python.slim.nets.resnet_utils as slim_utils from tensorflow.contrib import", "image :param is_training: are you using the resnet at training_time", "scope :param resnet_version: 50/101/152 :param cbn: the cbn factory :return:", "arg_scope( [layers_lib.conv2d], activation_fn=tf.nn.relu, normalizer_fn=bn_fn, normalizer_params=None) as arg_sc: return arg_sc def", "\"\"\" # assert False, \"\\n\" \\ # \"There is a", "output \"\"\" # assert False, \"\\n\" \\ # \"There is", "classic batchnorm with slim networks (https://github.com/tensorflow/tensorflow/issues/4887). \\n\" \\ # \"Please", "1\") arg_sc = inception_v1.inception_v1_arg_scope() # Pick the correct version of", "print(\" resnet_out = {} , resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"---", "resnet_out = {} , resnet_scope = {}\".format(resnet_out,resnet_scope)) # print(\"--- 3\")", "2\") inception_scope = inception_out # print(\" resnet_out = {} ,", "<reponame>ibrahimSouleiman/GuessWhat import tensorflow as tf import tensorflow.contrib.slim as slim import", "slim.arg_scope(arg_sc): net, end_points = inception_v1.inception_v1(image_input, 1001) # 1000 is the", ":param image_input: placeholder with image :param is_training: are you using", "# \"There is a bug with classic batchnorm with slim" ]
[ "metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing)", "operator import os import logging import torch from .model import", "self.args.model save_state['args'] = self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key]", "c in self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str) if metric", "better if True self.cmp = operator.lt if decreasing else operator.gt", "= os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path)", "0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path =", "= os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' +", "self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing #", "rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history >=", "None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file = ''", "sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in", "in to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except Exception as", "is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1)", "def save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path =", "in order of decreasing betterness self.best_epoch = None self.best_metric =", "< self.max_history or metric is None or self.cmp(metric, worst_file[1])): if", "epoch before save } if self.args is not None: save_state['arch']", "self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file = '' #", "self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None, None) if", "self.max_history >= 1 def save_checkpoint(self, epoch, metric=None): assert epoch >=", "trim if delete_index < 0 or len(self.checkpoint_files) <= delete_index: return", "os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None, None) if self.best_metric is None", "on specified intervals. Hacked together by / Copyright 2020 <NAME>", "delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try:", "from .model import unwrap_model, get_state_dict _logger = logging.getLogger(__name__) class CheckpointSaver:", "self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2 increments", "= os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path):", "save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files =", "for c in self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str) if", "None else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state", "in descending order if a lower metric is not better", "Exception as e: _logger.error(\"Exception '{}' while deleting checkpoint\".format(e)) self.checkpoint_files =", "save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path", "tuples in order of decreasing betterness self.best_epoch = None self.best_metric", "self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best'", "True self.cmp = operator.lt if decreasing else operator.gt # True", "# objects to save state_dicts of self.model = model self.optimizer", "+ self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None, None)", "<filename>timm/utils/checkpoint_saver.py \"\"\" Checkpoint Saver Track top-n training checkpoints and maintain", "os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file))", "version < 2 increments epoch before save } if self.args", "than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history", "# sort in descending order if a lower metric is", "save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler is not", ">= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path", "'-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path)", "= None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file =", "metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path)", "filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir,", "while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path", "worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) <", "to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug(\"Cleaning checkpoint:", "recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing # a lower", "decreasing # a lower metric is better if True self.cmp", "support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None", "Hacked together by / Copyright 2020 <NAME> \"\"\" import glob", "= '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path,", "if self.best_metric is None else (self.best_metric, self.best_epoch) def _save(self, save_path,", "(len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric, worst_file[1])):", "self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension) files =", "min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if delete_index <", "is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric =", "= get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric'] =", "assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) +", "files = glob.glob(recovery_path + '*' + self.extension) files = sorted(files)", "\"\"\" Checkpoint Saver Track top-n training checkpoints and maintain recovery", "2020 <NAME> \"\"\" import glob import operator import os import", "# a lower metric is better if True self.cmp =", "not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is not", "if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) +", "= '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename)", "of decreasing betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file", "self.extension) files = sorted(files) return files[0] if len(files) else ''", "' {}\\n'.format(c) _logger.info(checkpoints_str) if metric is not None and (self.best_metric", "type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version", "self.curr_recovery_file = save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files", "str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch)", "last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files)", "_logger = logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model, optimizer,", "in self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str) if metric is", "self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except", "_save(self, save_path, epoch, metric=None): save_state = { 'epoch': epoch, 'arch':", "filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda", "(filename, metric) tuples in order of decreasing betterness self.best_epoch =", "and maintain recovery checkpoints on specified intervals. Hacked together by", "better than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn assert", "self.cmp = operator.lt if decreasing else operator.gt # True if", "recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' +", "tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last'", "\"\"\" import glob import operator import os import logging import", "order of decreasing betterness self.best_epoch = None self.best_metric = None", "'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path,", "(self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric", "delete_index = self.max_history - trim if delete_index < 0 or", "operator.gt # True if lhs better than rhs self.max_history =", "def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename =", "find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*'", "self.best_metric is None else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch,", "self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path", "self.last_recovery_file = '' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir =", "sort in descending order if a lower metric is not", "checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts", "is better if True self.cmp = operator.lt if decreasing else", "checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch", "optimizer self.args = args self.model_ema = model_ema self.amp_scaler = amp_scaler", "None) if self.best_metric is None else (self.best_metric, self.best_epoch) def _save(self,", "= None self.curr_recovery_file = '' self.last_recovery_file = '' # config", "self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension", "model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files = [] #", "glob import operator import os import logging import torch from", "a lower metric is not better checkpoints_str = \"Current checkpoints:\\n\"", "if metric is not None and (self.best_metric is None or", "'version': 2, # version < 2 increments epoch before save", "= self.max_history - trim if delete_index < 0 or len(self.checkpoint_files)", "not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch", "self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path =", "filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file)", "2, # version < 2 increments epoch before save }", "by / Copyright 2020 <NAME> \"\"\" import glob import operator", "= sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort", "self.model = model self.optimizer = optimizer self.args = args self.model_ema", "+= ' {}\\n'.format(c) _logger.info(checkpoints_str) if metric is not None and", "e: _logger.error(\"Exception '{}' while deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def", "= [] # (filename, metric) tuples in order of decreasing", "= self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0", "d in to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except Exception", "os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files,", "len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in", "'-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path,", "metric is not better checkpoints_str = \"Current checkpoints:\\n\" for c", "is None else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None):", "amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects", "if metric is not None: save_state['metric'] = metric torch.save(save_state, save_path)", "metric is not None: save_state['metric'] = metric torch.save(save_state, save_path) def", "os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None if", "= save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files =", "specified intervals. Hacked together by / Copyright 2020 <NAME> \"\"\"", "is not None: save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self,", "operator.lt if decreasing else operator.gt # True if lhs better", "reverse=not self.decreasing) # sort in descending order if a lower", "self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files", "< 0 or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:]", "os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file", "Exception as e: _logger.error(\"Exception '{}' while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file", "= self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d))", "_logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error(\"Exception '{}'", "epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows support.", "self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir,", "class CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None,", "self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or", "self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric)", "str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path,", "epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension", "= unwrap_fn assert self.max_history >= 1 def save_checkpoint(self, epoch, metric=None):", "checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix", "= model self.optimizer = optimizer self.args = args self.model_ema =", "= decreasing # a lower metric is better if True", "self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch >=", "epoch, batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch),", "os.remove(d[0]) except Exception as e: _logger.error(\"Exception '{}' while deleting checkpoint\".format(e))", "self.model_ema = model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files =", "os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path)", "'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version <", "save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix,", "self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is", "# True if lhs better than rhs self.max_history = max_history", "best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path,", "metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model,", "# required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1]", "self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir,", "self.amp_scaler = amp_scaler # state self.checkpoint_files = [] # (filename,", "= self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict()", "None: save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim", "self.max_history = max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1", "self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn)", "metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim)", "if decreasing else operator.gt # True if lhs better than", "filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path = os.path.join(self.checkpoint_dir, filename)", "before save } if self.args is not None: save_state['arch'] =", "batch_idx=0): assert epoch >= 0 filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)])", "assert self.max_history >= 1 def save_checkpoint(self, epoch, metric=None): assert epoch", "assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension)", "self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not", "self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path =", "= metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files),", "get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2", "Saver Track top-n training checkpoints and maintain recovery checkpoints on", "metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path,", "top-n training checkpoints and maintain recovery checkpoints on specified intervals.", "not None: save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler", "= self.args.model save_state['args'] = self.args if self.amp_scaler is not None:", "_cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history -", "optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10,", "checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str) if metric is not None", "self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='',", "epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception", "len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension", "checkpoints on specified intervals. Hacked together by / Copyright 2020", "'{}' while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file =", "order if a lower metric is not better checkpoints_str =", "return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch)", "model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False,", "= checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix =", "epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension)", "os.remove(self.last_recovery_file) except Exception as e: _logger.error(\"Exception '{}' while removing {}\".format(e,", "= os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension)", "a lower metric is better if True self.cmp = operator.lt", "self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state = { 'epoch':", "def _save(self, save_path, epoch, metric=None): save_state = { 'epoch': epoch,", "self.max_history - trim if delete_index < 0 or len(self.checkpoint_files) <=", "as e: _logger.error(\"Exception '{}' while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file =", "save_state['args'] = self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] =", "to save state_dicts of self.model = model self.optimizer = optimizer", "if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as", "+ self.extension) files = sorted(files) return files[0] if len(files) else", "self.checkpoint_files = [] # (filename, metric) tuples in order of", "metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' +", "_logger.error(\"Exception '{}' while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file", "if self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if", "None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema']", "self.unwrap_fn) if metric is not None: save_state['metric'] = metric torch.save(save_state,", "checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to", "save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning", "= { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer':", "maintain recovery checkpoints on specified intervals. Hacked together by /", "if os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path, last_save_path)", "self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0])", "decreasing else operator.gt # True if lhs better than rhs", "required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if", "checkpoints_str = \"Current checkpoints:\\n\" for c in self.checkpoint_files: checkpoints_str +=", "_logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except Exception as e: _logger.error(\"Exception '{}'", "is not better checkpoints_str = \"Current checkpoints:\\n\" for c in", "e: _logger.error(\"Exception '{}' while removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file", "self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required for", "None and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch =", "save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir,", "self.optimizer.state_dict(), 'version': 2, # version < 2 increments epoch before", "decreasing betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file =", "removing {}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def", "checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing", ">= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path =", "self.max_history or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files)", "recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error(\"Exception '{}' while", "= \"Current checkpoints:\\n\" for c in self.checkpoint_files: checkpoints_str += '", "os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path + '*' + self.extension) files", "# state self.checkpoint_files = [] # (filename, metric) tuples in", "0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir,", "not None: save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0):", "else None if (len(self.checkpoint_files) < self.max_history or metric is None", "if (len(self.checkpoint_files) < self.max_history or metric is None or self.cmp(metric,", "unwrap_model, get_state_dict _logger = logging.getLogger(__name__) class CheckpointSaver: def __init__( self,", "= '.pth.tar' self.decreasing = decreasing # a lower metric is", "self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric is", "self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert epoch >= 0 filename", "if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema", "None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None:", "= optimizer self.args = args self.model_ema = model_ema self.amp_scaler =", "decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts of self.model", "self.best_epoch = None self.best_metric = None self.curr_recovery_file = '' self.last_recovery_file", "import operator import os import logging import torch from .model", "epoch, metric=None): assert epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp'", "save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric']", "'' self.last_recovery_file = '' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir", "self.unwrap_fn = unwrap_fn assert self.max_history >= 1 def save_checkpoint(self, epoch,", "os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e:", "self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric", "checkpoint: {}\".format(d)) os.remove(d[0]) except Exception as e: _logger.error(\"Exception '{}' while", "2 increments epoch before save } if self.args is not", "trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim", "recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save", "is not None: save_state['arch'] = self.args.model save_state['args'] = self.args if", "= max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1 def", "'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version':", "trim) delete_index = self.max_history - trim if delete_index < 0", "self.decreasing = decreasing # a lower metric is better if", "not better checkpoints_str = \"Current checkpoints:\\n\" for c in self.checkpoint_files:", "self.curr_recovery_file = '' self.last_recovery_file = '' # config self.checkpoint_dir =", "- trim if delete_index < 0 or len(self.checkpoint_files) <= delete_index:", "epoch >= 0 tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path", "checkpoints and maintain recovery checkpoints on specified intervals. Hacked together", "Checkpoint Saver Track top-n training checkpoints and maintain recovery checkpoints", "= self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir,", "self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing", "better checkpoints_str = \"Current checkpoints:\\n\" for c in self.checkpoint_files: checkpoints_str", "glob.glob(recovery_path + '*' + self.extension) files = sorted(files) return files[0]", "together by / Copyright 2020 <NAME> \"\"\" import glob import", "= epoch self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' +", "CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint',", "get_state_dict _logger = logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model,", "recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar'", "1 def save_checkpoint(self, epoch, metric=None): assert epoch >= 0 tmp_save_path", "{ 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(),", "for Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files", "def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history", "'last' + self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) #", "os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x:", "'{}' while deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch,", "[] # (filename, metric) tuples in order of decreasing betterness", "model self.optimizer = optimizer self.args = args self.model_ema = model_ema", "x[1], reverse=not self.decreasing) # sort in descending order if a", "metric is not None and (self.best_metric is None or self.cmp(metric,", "os.link(last_save_path, best_save_path) return (None, None) if self.best_metric is None else", "unwrap_fn assert self.max_history >= 1 def save_checkpoint(self, epoch, metric=None): assert", "None: save_state['arch'] = self.args.model save_state['args'] = self.args if self.amp_scaler is", "+ self.extension save_path = os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric))", "= checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension = '.pth.tar' self.decreasing =", "config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix", "= self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema,", "self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) #", "self.checkpoint_files, key=lambda x: x[1], reverse=not self.decreasing) # sort in descending", "self.extension = '.pth.tar' self.decreasing = decreasing # a lower metric", "if True self.cmp = operator.lt if decreasing else operator.gt #", "intervals. Hacked together by / Copyright 2020 <NAME> \"\"\" import", "{}\\n'.format(c) _logger.info(checkpoints_str) if metric is not None and (self.best_metric is", "self.decreasing) # sort in descending order if a lower metric", "self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required for Windows", "os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None, None) if self.best_metric is", "checkpoints:\\n\" for c in self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str)", "os.path.join(self.checkpoint_dir, 'tmp' + self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension)", "(self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state = {", "increments epoch before save } if self.args is not None:", "if self.args is not None: save_state['arch'] = self.args.model save_state['args'] =", "lhs better than rhs self.max_history = max_history self.unwrap_fn = unwrap_fn", "# version < 2 increments epoch before save } if", "logging import torch from .model import unwrap_model, get_state_dict _logger =", "save_path, epoch, metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(),", "(None, None) if self.best_metric is None else (self.best_metric, self.best_epoch) def", "self.optimizer = optimizer self.args = args self.model_ema = model_ema self.amp_scaler", "self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c) _logger.info(checkpoints_str) if metric is not", "self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path =", "save state_dicts of self.model = model self.optimizer = optimizer self.args", ">= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension save_path", "+ self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file):", "torch from .model import unwrap_model, get_state_dict _logger = logging.getLogger(__name__) class", "{}\".format(d)) os.remove(d[0]) except Exception as e: _logger.error(\"Exception '{}' while deleting", "= metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path):", "lower metric is better if True self.cmp = operator.lt if", "while deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0):", "{}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error(\"Exception '{}' while removing", "+ '*' + self.extension) files = sorted(files) return files[0] if", "if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history or metric", "self.args if self.amp_scaler is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if", ">= 1 def save_checkpoint(self, epoch, metric=None): assert epoch >= 0", "/ Copyright 2020 <NAME> \"\"\" import glob import operator import", "last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch, metric) if", "return to_delete = self.checkpoint_files[delete_index:] for d in to_delete: try: _logger.debug(\"Cleaning", "amp_scaler # state self.checkpoint_files = [] # (filename, metric) tuples", "Track top-n training checkpoints and maintain recovery checkpoints on specified", "recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts of", "= os.path.join(self.checkpoint_dir, filename) os.link(last_save_path, save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted(", "self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix,", "and (self.best_metric is None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch", "delete_index < 0 or len(self.checkpoint_files) <= delete_index: return to_delete =", "or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d", "model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model): #", "descending order if a lower metric is not better checkpoints_str", "True if lhs better than rhs self.max_history = max_history self.unwrap_fn", "is not None: save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) if metric is", "betterness self.best_epoch = None self.best_metric = None self.curr_recovery_file = ''", "+ self.extension) self._save(tmp_save_path, epoch, metric) if os.path.exists(last_save_path): os.unlink(last_save_path) # required", "self.best_metric = metric best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if", "save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None: save_state['state_dict_ema'] =", "0 or len(self.checkpoint_files) <= delete_index: return to_delete = self.checkpoint_files[delete_index:] for", "= glob.glob(recovery_path + '*' + self.extension) files = sorted(files) return", "is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)):", "{}\".format(e, self.last_recovery_file)) self.last_recovery_file = self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self):", "\"Current checkpoints:\\n\" for c in self.checkpoint_files: checkpoints_str += ' {}\\n'.format(c)", "None or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric", "trim = min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if", "unwrap_fn=unwrap_model): # objects to save state_dicts of self.model = model", "or self.cmp(metric, self.best_metric)): self.best_epoch = epoch self.best_metric = metric best_save_path", "metric) tuples in order of decreasing betterness self.best_epoch = None", "Windows support. os.rename(tmp_save_path, last_save_path) worst_file = self.checkpoint_files[-1] if self.checkpoint_files else", "state_dicts of self.model = model self.optimizer = optimizer self.args =", "epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2,", "def __init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery',", "x: x[1], reverse=not self.decreasing) # sort in descending order if", "is not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not", "not None: save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() if self.model_ema is not None:", "to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except Exception as e:", "os.path.join(self.checkpoint_dir, 'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return", "= args self.model_ema = model_ema self.amp_scaler = amp_scaler # state", "'' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix", "self.curr_recovery_file self.curr_recovery_file = save_path def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix)", "= '' self.last_recovery_file = '' # config self.checkpoint_dir = checkpoint_dir", "import os import logging import torch from .model import unwrap_model,", "except Exception as e: _logger.error(\"Exception '{}' while deleting checkpoint\".format(e)) self.checkpoint_files", "save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index =", "= recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix = recovery_prefix self.extension =", "if a lower metric is not better checkpoints_str = \"Current", "= '' # config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir", "or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename =", "'optimizer': self.optimizer.state_dict(), 'version': 2, # version < 2 increments epoch", "import glob import operator import os import logging import torch", ".model import unwrap_model, get_state_dict _logger = logging.getLogger(__name__) class CheckpointSaver: def", "lower metric is not better checkpoints_str = \"Current checkpoints:\\n\" for", "max_history=10, unwrap_fn=unwrap_model): # objects to save state_dicts of self.model =", "os import logging import torch from .model import unwrap_model, get_state_dict", "worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename = '-'.join([self.save_prefix, str(epoch)])", "if lhs better than rhs self.max_history = max_history self.unwrap_fn =", "<NAME> \"\"\" import glob import operator import os import logging", "metric is better if True self.cmp = operator.lt if decreasing", "save_state['metric'] = metric torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim =", "None self.curr_recovery_file = '' self.last_recovery_file = '' # config self.checkpoint_dir", "for d in to_delete: try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except", "self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try:", "str(batch_idx)]) + self.extension save_path = os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if", "= amp_scaler # state self.checkpoint_files = [] # (filename, metric)", "= min(len(self.checkpoint_files), trim) delete_index = self.max_history - trim if delete_index", "self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix = checkpoint_prefix self.recovery_prefix", "None if (len(self.checkpoint_files) < self.max_history or metric is None or", "= operator.lt if decreasing else operator.gt # True if lhs", "try: _logger.debug(\"Cleaning checkpoint: {}\".format(d)) os.remove(d[0]) except Exception as e: _logger.error(\"Exception", "deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self, epoch, batch_idx=0): assert", "__init__( self, model, optimizer, args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='',", "<= delete_index: return to_delete = self.checkpoint_files[delete_index:] for d in to_delete:", "state self.checkpoint_files = [] # (filename, metric) tuples in order", "objects to save state_dicts of self.model = model self.optimizer =", "recovery checkpoints on specified intervals. Hacked together by / Copyright", "= recovery_prefix self.extension = '.pth.tar' self.decreasing = decreasing # a", "epoch, metric=None): save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict':", "} if self.args is not None: save_state['arch'] = self.args.model save_state['args']", "training checkpoints and maintain recovery checkpoints on specified intervals. Hacked", "= model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files = []", "if delete_index < 0 or len(self.checkpoint_files) <= delete_index: return to_delete", "'.pth.tar' self.decreasing = decreasing # a lower metric is better", "save_path) self.checkpoint_files.append((save_path, metric)) self.checkpoint_files = sorted( self.checkpoint_files, key=lambda x: x[1],", "save_state = { 'epoch': epoch, 'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn),", "as e: _logger.error(\"Exception '{}' while deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index]", "_logger.error(\"Exception '{}' while deleting checkpoint\".format(e)) self.checkpoint_files = self.checkpoint_files[:delete_index] def save_recovery(self,", "metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history:", "torch.save(save_state, save_path) def _cleanup_checkpoints(self, trim=0): trim = min(len(self.checkpoint_files), trim) delete_index", "# config self.checkpoint_dir = checkpoint_dir self.recovery_dir = recovery_dir self.save_prefix =", "'arch': type(self.model).__name__.lower(), 'state_dict': get_state_dict(self.model, self.unwrap_fn), 'optimizer': self.optimizer.state_dict(), 'version': 2, #", "= logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model, optimizer, args=None,", "None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >= self.max_history: self._cleanup_checkpoints(1) filename", "self.args = args self.model_ema = model_ema self.amp_scaler = amp_scaler #", "import torch from .model import unwrap_model, get_state_dict _logger = logging.getLogger(__name__)", "import logging import torch from .model import unwrap_model, get_state_dict _logger", "+ self.extension) last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) self._save(tmp_save_path, epoch,", "get_state_dict(self.model_ema, self.unwrap_fn) if metric is not None: save_state['metric'] = metric", "or metric is None or self.cmp(metric, worst_file[1])): if len(self.checkpoint_files) >=", "logging.getLogger(__name__) class CheckpointSaver: def __init__( self, model, optimizer, args=None, model_ema=None,", "self.args is not None: save_state['arch'] = self.args.model save_state['args'] = self.args", "Copyright 2020 <NAME> \"\"\" import glob import operator import os", "'model_best' + self.extension) if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None,", "try: _logger.debug(\"Cleaning recovery: {}\".format(self.last_recovery_file)) os.remove(self.last_recovery_file) except Exception as e: _logger.error(\"Exception", "os.unlink(last_save_path) # required for Windows support. os.rename(tmp_save_path, last_save_path) worst_file =", "import unwrap_model, get_state_dict _logger = logging.getLogger(__name__) class CheckpointSaver: def __init__(", "args=None, model_ema=None, amp_scaler=None, checkpoint_prefix='checkpoint', recovery_prefix='recovery', checkpoint_dir='', recovery_dir='', decreasing=False, max_history=10, unwrap_fn=unwrap_model):", "if os.path.exists(best_save_path): os.unlink(best_save_path) os.link(last_save_path, best_save_path) return (None, None) if self.best_metric", "max_history self.unwrap_fn = unwrap_fn assert self.max_history >= 1 def save_checkpoint(self,", "= self.checkpoint_files[-1] if self.checkpoint_files else None if (len(self.checkpoint_files) < self.max_history", "_logger.info(checkpoints_str) if metric is not None and (self.best_metric is None", "except Exception as e: _logger.error(\"Exception '{}' while removing {}\".format(e, self.last_recovery_file))", "# (filename, metric) tuples in order of decreasing betterness self.best_epoch", "= os.path.join(self.recovery_dir, filename) self._save(save_path, epoch) if os.path.exists(self.last_recovery_file): try: _logger.debug(\"Cleaning recovery:", "args self.model_ema = model_ema self.amp_scaler = amp_scaler # state self.checkpoint_files", "of self.model = model self.optimizer = optimizer self.args = args", "save } if self.args is not None: save_state['arch'] = self.args.model", "key=lambda x: x[1], reverse=not self.decreasing) # sort in descending order", "else operator.gt # True if lhs better than rhs self.max_history", "'*' + self.extension) files = sorted(files) return files[0] if len(files)", "best_save_path) return (None, None) if self.best_metric is None else (self.best_metric,", "def find_recovery(self): recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) files = glob.glob(recovery_path +", "else (self.best_metric, self.best_epoch) def _save(self, save_path, epoch, metric=None): save_state =", "< 2 increments epoch before save } if self.args is" ]
[ "AGC004a def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a,", "import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c =", "0 or b % 2 == 0 or c %", "b, c = map(int, input().split()) if a % 2 ==", "b % 2 == 0 or c % 2 ==", "map(int, input().split()) if a % 2 == 0 or b", "input().split()) if a % 2 == 0 or b %", "2 == 0 or b % 2 == 0 or", "def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a, b,", "% 2 == 0 or b % 2 == 0", "% 2 == 0: print(0) exit(0) print(min(a*b, b*c, c*a)) if", "sys.setrecursionlimit(10**6) a, b, c = map(int, input().split()) if a %", "= sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c = map(int, input().split()) if", "or c % 2 == 0: print(0) exit(0) print(min(a*b, b*c,", "== 0 or b % 2 == 0 or c", "if a % 2 == 0 or b % 2", "main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c", "a, b, c = map(int, input().split()) if a % 2", "<filename>AGC004/AGC004a.py # AGC004a def main(): import sys input = sys.stdin.readline", "sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c = map(int, input().split()) if a", "== 0: print(0) exit(0) print(min(a*b, b*c, c*a)) if __name__ ==", "print(0) exit(0) print(min(a*b, b*c, c*a)) if __name__ == '__main__': main()", "c % 2 == 0: print(0) exit(0) print(min(a*b, b*c, c*a))", "or b % 2 == 0 or c % 2", "= map(int, input().split()) if a % 2 == 0 or", "c = map(int, input().split()) if a % 2 == 0", "sys input = sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c = map(int,", "input = sys.stdin.readline sys.setrecursionlimit(10**6) a, b, c = map(int, input().split())", "# AGC004a def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10**6)", "0 or c % 2 == 0: print(0) exit(0) print(min(a*b,", "2 == 0 or c % 2 == 0: print(0)", "a % 2 == 0 or b % 2 ==", "2 == 0: print(0) exit(0) print(min(a*b, b*c, c*a)) if __name__", "% 2 == 0 or c % 2 == 0:", "== 0 or c % 2 == 0: print(0) exit(0)", "0: print(0) exit(0) print(min(a*b, b*c, c*a)) if __name__ == '__main__':" ]
[ "self.api_port) http = httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.OK,", "{'Accept': 'unknown'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status)", "def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port", "= 'http://%s:%d/' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers =", "url % '2'}], }, { 'id': 'v2.3', 'status': 'SUPPORTED', 'links':", "an Accept: application/vnd.openstack.images-v1 Verify empty image list returned \"\"\" path", "Verify version choices returned \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1',", "= httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content", "'self', 'href': url % '2'}], }, { 'id': 'v2.4', 'status':", "= {'Accept': 'application/vnd.openstack.images-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK,", "'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\" path", "returned. \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http =", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def setUp(self):", "def test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api =", "GET /v1/versions with `no Accept:` header Verify 404 returned \"\"\"", "`Accept: application/vnd.openstack.compute-v2` header. Verify version choices returned. Verify message in", "= _generate_v2_versions(url) # Verify version choices returned. path = 'http://%s:%d'", "returned. Verify message in API log about unknown accept header.", "'id': 'v2.3', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "EXPERIMENTAL stuff in this file can be ripped out #", "[{'rel': 'self', 'href': url % '1'}], }, ]} return v1_versions", "httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content =", "import functional # TODO(rosmaita): all the EXPERIMENTAL stuff in this", "'v2.6', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}],", "= http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self):", "'self', 'href': url % '1'}], }, { 'id': 'v1.0', 'status':", "'self', 'href': url % '1'}], }, ]} return v1_versions def", "self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.OK,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode())", "self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert", "} ]) v2_versions = {'versions': version_list} return v2_versions def _generate_all_versions(url):", "self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v2_versions(url) #", "specific language governing permissions and limitations # under the License.", "# not use this file except in compliance with the", "url % '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links':", "from oslo_serialization import jsonutils from six.moves import http_client from glance.tests", "GET /v1.0/images with no Accept: header Verify version choices returned", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert", "headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self):", "{ 'id': 'v2.4', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self):", "content_json = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions,", "tests\"\"\" import httplib2 from oslo_serialization import jsonutils from six.moves import", "header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http =", "self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET /v1/images with `no Accept:` header.", "content) def test_get_versions_path(self): \"\"\"Assert GET /versions with no Accept: header", "content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v1`", "content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions,", "in compliance with the License. You may obtain # a", "with `no Accept:` header. Verify version choices returned. Bug lp:803260", "'href': url % '2'}], } ]) v2_versions = {'versions': version_list}", "GET /versions with the `Accept: application/vnd.openstack.images-v1` header. Verify version choices", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self):", "version choices returned. \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port)", "http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def", "You may obtain # a copy of the License at", "returned \"\"\" path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http =", "= {'Accept': 'unknown'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES,", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.1',", "def test_get_versions_path(self): \"\"\"Assert GET /versions with no Accept: header Verify", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET", "self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/'", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with", "'2'}], } ]) v2_versions = {'versions': version_list} return v2_versions def", "jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api =", "handled properly through all channels\"\"\" # v1 and v2 api", "content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths,", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with no Accept:", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET / with `no Accept:` header.", "self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with a `Accept:", "choices returned. Bug lp:803260 no Accept header causes a 500", "Verify version choices returned \"\"\" path = 'http://%s:%d/v1.2/images' % ('127.0.0.1',", "path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "= 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "= httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content_json = http.request(path,", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.5',", "in API log about unknown accept header. \"\"\" path =", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET", "under the License is distributed on an \"AS IS\" BASIS,", "test_get_images_path(self): \"\"\"Assert GET /images with `no Accept:` header. Verify version", "{ 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions =", "'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET", "Verify version choices returned. Bug lp:803260 no Accept header causes", "'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}], }, {", "list returned. \"\"\" path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http", "url % '2'}], } ]) v2_versions = {'versions': version_list} return", "Reserved. # # Licensed under the Apache License, Version 2.0", "v2.6 becomes CURRENT in Queens def _generate_v1_versions(url): v1_versions = {'versions':", "'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_all_versions(url) # Verify version choices", "= 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v2_versions(url) # Verify version", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert GET /versions", "content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v2`", "message in API log about unknown accept header. \"\"\" path", "'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions = _generate_all_versions(url) images = {'images': []}", "% ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json = http.request(path,", "accept header. \"\"\" path = 'http://%s:%d/' % ('127.0.0.1', self.api_port) http", "six.moves import http_client from glance.tests import functional # TODO(rosmaita): all", "functional # TODO(rosmaita): all the EXPERIMENTAL stuff in this file", "self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with Accept: unknown", "Verify version choices returned. Verify message in API log about", "self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES,", "this file except in compliance with the License. You may", "/v1.a/images with no Accept: header Verify version choices returned \"\"\"", "path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "'href': url % '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED',", "returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "version choices returned. Bug lp:803260 no Accept header causes a", "# v1 and v2 api enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/'", "% '2'}], }, { 'id': 'v2.4', 'status': 'SUPPORTED', 'links': [{'rel':", "empty images list returned. \"\"\" path = 'http://%s:%d/v1/images' % ('127.0.0.1',", "http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with `no", "Accept header causes a 500 in glance-api \"\"\" path =", "header. \"\"\" path = 'http://%s:%d/' % ('127.0.0.1', self.api_port) http =", "path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "'2'}], }, { 'id': 'v2.5', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert", "self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False", "def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with no Accept: header Verify", "= http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content)", "url % '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links':", "all the EXPERIMENTAL stuff in this file can be ripped", "log about unknown version in accept header. \"\"\" path =", "software # distributed under the License is distributed on an", "(the \"License\"); you may # not use this file except", "content) def test_get_images_path(self): \"\"\"Assert GET /images with `no Accept:` header.", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET /", "('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response,", "test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v2` header. Verify", "all channels\"\"\" # v1 and v2 api enabled self.start_servers(**self.__dict__.copy()) url", "'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], } ])", "}, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v1` header.", "% '1'}], }, ]} return v1_versions def _generate_v2_versions(url): version_list =", "'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify version", "`no Accept:` header Verify 404 returned \"\"\" path = 'http://%s:%d/v1/versions'", "path = 'http://%s:%d/' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers", "self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with no Accept:", "def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v2` header.", "version_list.extend([ { 'id': 'v2.6', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href':", "file except in compliance with the License. You may obtain", "{ 'id': 'v2.6', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url", "url % '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links':", "'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port", "test_get_root_path(self): \"\"\"Assert GET / with `no Accept:` header. Verify version", "GET / with an Accept: application/vnd.openstack.images-v1 Verify empty image list", "path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions = _generate_all_versions(url) images", "= httplib2.Http() headers = {'Accept': 'unknown'} response, content_json = http.request(path,", "'v1.1', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url % '1'}],", "OR CONDITIONS OF ANY KIND, either express or implied. See", "the specific language governing permissions and limitations # under the", "'2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert", "def test_version_configurations(self): \"\"\"Test that versioning is handled properly through all", "{'images': []} self.images_json = jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET /", "choices returned \"\"\" path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http", "= 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v1_versions(url) # Verify version", "`no Accept:` header. Verify version choices returned. \"\"\" path =", "v2_versions def _generate_all_versions(url): v1 = _generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions", "httplib2 from oslo_serialization import jsonutils from six.moves import http_client from", "under the Apache License, Version 2.0 (the \"License\"); you may", "= 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions = _generate_all_versions(url) images = {'images':", "headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers)", "Verify empty images list returned. \"\"\" path = 'http://%s:%d/v1/images' %", "application/vnd.openstack.compute-v2` header. Verify version choices returned. Verify message in API", "'application/vnd.openstack.images-v10'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content", "`Accept: application/vnd.openstack.images-v1` header. Verify version choices returned. \"\"\" path =", "http = httplib2.Http() headers = {'Accept': 'unknown'} response, content_json =", "governing permissions and limitations # under the License. \"\"\"Version-independent api", "[{'rel': 'self', 'href': url % '2'}], } ]) v2_versions =", "header. Verify version choices returned. Bug lp:803260 no Accept header", "{ 'id': 'v1.0', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with no", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY", "'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "= 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content", "'2'}], }, { 'id': 'v2.4', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "in API log about unknown version in accept header. \"\"\"", "content) class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url =", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "% '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel':", "'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "to in writing, software # distributed under the License is", "glance.tests import functional # TODO(rosmaita): all the EXPERIMENTAL stuff in", "class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that versioning is handled properly", "http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with", "version choices returned \"\"\" path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port)", "Copyright 2012 OpenStack Foundation # All Rights Reserved. # #", "or agreed to in writing, software # distributed under the", "v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that versioning", "with `no Accept:` header. Verify version choices returned. \"\"\" path", "required by applicable law or agreed to in writing, software", "}, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self):", "unknown accept header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)", "content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions,", "TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that versioning is handled properly through", "Accept:` header. Verify empty images list returned. \"\"\" path =", "self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_all_versions(url) #", "content = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET", "'application/vnd.openstack.compute-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content", "API log about unknown version in accept header. \"\"\" path", "GET / with `no Accept:` header. Verify version choices returned.", "404 returned \"\"\" path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http", "{ 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "Apache License, Version 2.0 (the \"License\"); you may # not", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with no", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert GET", "all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that versioning is handled", "\"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v1` header. Verify version", "headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json = http.request(path, 'GET', headers=headers)", "\"\"\" path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "that versioning is handled properly through all channels\"\"\" # v1", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http =", "= 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "and limitations # under the License. \"\"\"Version-independent api tests\"\"\" import", "http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content)", "self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content_json", "[]} self.images_json = jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET / with", "self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND,", "distributed under the License is distributed on an \"AS IS\"", "{'Accept': 'application/vnd.openstack.compute-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status)", "}, { 'id': 'v1.0', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href':", "= True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' %", "return v1_versions def _generate_v2_versions(url): version_list = [] version_list.extend([ { 'id':", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with", "License, Version 2.0 (the \"License\"); you may # not use", "CONDITIONS OF ANY KIND, either express or implied. See the", "class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/'", "[] version_list.extend([ { 'id': 'v2.6', 'status': 'CURRENT', 'links': [{'rel': 'self',", "'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content =", "version choices returned \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port)", "a `Accept: application/vnd.openstack.compute-v2` header. Verify version choices returned. Verify message", "test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url =", "with the `Accept: application/vnd.openstack.images-v1` header. Verify version choices returned. \"\"\"", "httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json = http.request(path, 'GET',", "False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v1_versions(url)", "\"\"\"Assert GET /versions with no Accept: header Verify version choices", "/v1.2/images with `no Accept:` header Verify version choices returned \"\"\"", "not use this file except in compliance with the License.", "/versions with no Accept: header Verify version choices returned \"\"\"", "http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def", "'DEPRECATED', 'links': [{'rel': 'self', 'href': url % '1'}], }, {", "self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/'", "= True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions =", "the `Accept: application/vnd.openstack.images-v1` header. Verify version choices returned. \"\"\" path", "writing, software # distributed under the License is distributed on", "GET /v1.2/images with `no Accept:` header Verify version choices returned", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self):", "and v2 api enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port", "in glance-api \"\"\" path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http", "def test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\" path = 'http://%s:%d/v10' %", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET /v1/images with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json =", "returned \"\"\" path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http =", "{'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status)", "v1 and v2 api enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' %", "versioning is handled properly through all channels\"\"\" # v1 and", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with", "the License. You may obtain # a copy of the", "Verify version choices returned \"\"\" path = 'http://%s:%d/v1.a/images' % ('127.0.0.1',", "'v1.0', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url % '1'}],", "an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET /v1/images with `no", "use this file except in compliance with the License. You", "http = httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status)", "= 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers =", "{ 'id': 'v2.5', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def", "setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions", "= 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content", "http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def", "headers = {'Accept': 'unknown'} response, content_json = http.request(path, 'GET', headers=headers)", "'v2.3', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self):", "content) def test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy())", "= {'versions': version_list} return v2_versions def _generate_all_versions(url): v1 = _generate_v1_versions(url)", "= {'images': []} self.images_json = jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET", "self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions = _generate_all_versions(url)", "= httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def", "'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url % '2'}], },", "_generate_v2_versions(url) # Verify version choices returned. path = 'http://%s:%d' %", "v1_versions def _generate_v2_versions(url): version_list = [] version_list.extend([ { 'id': 'v2.6',", "response, content_json = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode())", "% self.api_port versions = _generate_v1_versions(url) # Verify version choices returned.", "response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert", "= 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "API log about unknown accept header. \"\"\" path = 'http://%s:%d/'", "License is distributed on an \"AS IS\" BASIS, WITHOUT #", "KIND, either express or implied. See the # License for", "def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with `no Accept:` header Verify", "self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions", "/ with an Accept: application/vnd.openstack.images-v1 Verify empty image list returned", "with a `Accept: application/vnd.openstack.compute-v2` header. Verify version choices returned. Verify", "Accept:` header Verify version choices returned \"\"\" path = 'http://%s:%d/v1.2/images'", "jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy())", "/images with `no Accept:` header. Verify version choices returned. \"\"\"", "'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def", "\"License\"); you may # not use this file except in", "[ { 'id': 'v1.1', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href':", "IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,", "'2'}], }, { 'id': 'v2.3', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v2_versions(url) # Verify version choices", "express or implied. See the # License for the specific", "content) def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with `no Accept:` header", "'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v1_versions(url) # Verify", "def test_get_v1_images_path(self): \"\"\"GET /v1/images with `no Accept:` header. Verify empty", "}, { 'id': 'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "\"\"\" path = 'http://%s:%d/' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "url % '2'}], }, { 'id': 'v2.5', 'status': 'SUPPORTED', 'links':", "http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with", "http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content_json =", "the Apache License, Version 2.0 (the \"License\"); you may #", "unknown header Verify version choices returned. Verify message in API", "License. \"\"\"Version-independent api tests\"\"\" import httplib2 from oslo_serialization import jsonutils", "returned\"\"\" path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "= http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images", "self.api_port versions = _generate_all_versions(url) # Verify version choices returned. path", "self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def", "'links': [{'rel': 'self', 'href': url % '2'}], } ]) v2_versions", "See the # License for the specific language governing permissions", "'self', 'href': url % '2'}], }, { 'id': 'v2.1', 'status':", "% ('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path,", "/ with Accept: unknown header Verify version choices returned. Verify", "returned. Bug lp:803260 no Accept header causes a 500 in", "GET /va.1/images with no Accept: header Verify version choices returned", "Verify message in API log about unknown accept header. \"\"\"", "stuff in this file can be ripped out # when", "# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "limitations # under the License. \"\"\"Version-independent api tests\"\"\" import httplib2", "a 500 in glance-api \"\"\" path = 'http://%s:%d' % ('127.0.0.1',", "Accept: header Verify version choices returned \"\"\" path = 'http://%s:%d/va.1/images'", "the EXPERIMENTAL stuff in this file can be ripped out", "('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json = http.request(path, 'GET')", "version choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http", "/va.1/images with no Accept: header Verify version choices returned \"\"\"", "def test_get_images_path(self): \"\"\"Assert GET /images with `no Accept:` header. Verify", "self.api_port self.versions = _generate_all_versions(url) images = {'images': []} self.images_json =", "/v1.0/images with no Accept: header Verify version choices returned \"\"\"", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with an", "/v1/versions with `no Accept:` header Verify 404 returned \"\"\" path", "with a `Accept: application/vnd.openstack.compute-v1` header. Verify version choices returned. Verify", "url % '2'}], }, { 'id': 'v2.4', 'status': 'SUPPORTED', 'links':", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET", "'self', 'href': url % '2'}], }, { 'id': 'v2.2', 'status':", "header Verify version choices returned. Verify message in API log", "% ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'}", "self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content", "Verify version choices returned. \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1',", "law or agreed to in writing, software # distributed under", "'self', 'href': url % '2'}], }, { 'id': 'v2.5', 'status':", "False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port", "'GET') self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self):", "test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with an Accept: application/vnd.openstack.images-v1 Verify empty", "header Verify version choices returned \"\"\" path = 'http://%s:%d/v1.a/images' %", "{ 'id': 'v1.1', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with", "= httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json = http.request(path,", "implied. See the # License for the specific language governing", "= http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET /", "v2['versions'] + v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test", "'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], },", "= 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers =", "= jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET / with `no Accept:`", "_generate_v1_versions(url): v1_versions = {'versions': [ { 'id': 'v1.1', 'status': 'DEPRECATED',", "\"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "# when v2.6 becomes CURRENT in Queens def _generate_v1_versions(url): v1_versions", "from six.moves import http_client from glance.tests import functional # TODO(rosmaita):", "'id': 'v1.1', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url %", "message in API log about unknown version in accept header.", "be ripped out # when v2.6 becomes CURRENT in Queens", "'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "response, content = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode())", "url % '1'}], }, { 'id': 'v1.0', 'status': 'DEPRECATED', 'links':", "% ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'unknown'}", "\"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v2` header. Verify version", "'2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "through all channels\"\"\" # v1 and v2 api enabled self.start_servers(**self.__dict__.copy())", "def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with an Accept: application/vnd.openstack.images-v1 Verify", "version choices returned \"\"\" path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port)", "self.api_port versions = _generate_v2_versions(url) # Verify version choices returned. path", "= {'Accept': 'application/vnd.openstack.compute-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES,", "images list returned. \"\"\" path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port)", "http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status)", "def _generate_v1_versions(url): v1_versions = {'versions': [ { 'id': 'v1.1', 'status':", "header Verify version choices returned \"\"\" path = 'http://%s:%d/va.1/images' %", "= jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api", "httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self):", "content) def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with `no Accept:` header", "= jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api", "'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v1_versions(url) # Verify version choices", "'href': url % '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED',", "out # when v2.6 becomes CURRENT in Queens def _generate_v1_versions(url):", "'self', 'href': url % '2'}], } ]) v2_versions = {'versions':", "# TODO(rosmaita): all the EXPERIMENTAL stuff in this file can", "response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with Accept: unknown header", "when v2.6 becomes CURRENT in Queens def _generate_v1_versions(url): v1_versions =", "}, ]} return v1_versions def _generate_v2_versions(url): version_list = [] version_list.extend([", "http_client from glance.tests import functional # TODO(rosmaita): all the EXPERIMENTAL", "def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with the `Accept: application/vnd.openstack.images-v1` header.", "]) v2_versions = {'versions': version_list} return v2_versions def _generate_all_versions(url): v1", "http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with", "self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert GET /images with", "test_get_versions_path(self): \"\"\"Assert GET /versions with no Accept: header Verify version", "self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with the `Accept:", "'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert GET", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR", "'2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self',", "v2 = _generate_v2_versions(url) all_versions = {'versions': v2['versions'] + v1['versions']} return", "_generate_v2_versions(url): version_list = [] version_list.extend([ { 'id': 'v2.6', 'status': 'CURRENT',", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self):", "# # Licensed under the Apache License, Version 2.0 (the", "header Verify 404 returned \"\"\" path = 'http://%s:%d/v1/versions' % ('127.0.0.1',", "self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\" path =", "{ 'id': 'v2.3', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "= 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "Accept:` header. Verify version choices returned. \"\"\" path = 'http://%s:%d/images'", "+ v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that", "Accept:` header. Verify version choices returned. Bug lp:803260 no Accept", "= {'versions': [ { 'id': 'v1.1', 'status': 'DEPRECATED', 'links': [{'rel':", "'id': 'v2.5', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "returned \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http =", "'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept':", "'href': url % '2'}], }, { 'id': 'v2.1', 'status': 'SUPPORTED',", "response.status) def test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\" path = 'http://%s:%d/v10'", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert", "no Accept: header Verify version choices returned \"\"\" path =", "\"\"\"Assert GET /versions with the `Accept: application/vnd.openstack.images-v1` header. Verify version", "= http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions,", "obtain # a copy of the License at # #", "images = {'images': []} self.images_json = jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert", "'links': [{'rel': 'self', 'href': url % '2'}], }, { 'id':", "'1'}], }, { 'id': 'v1.0', 'status': 'DEPRECATED', 'links': [{'rel': 'self',", "\"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.4',", "\"\"\" path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with `no", "Version 2.0 (the \"License\"); you may # not use this", "'href': url % '2'}], }, { 'id': 'v2.5', 'status': 'SUPPORTED',", "_generate_all_versions(url) # Verify version choices returned. path = 'http://%s:%d' %", "'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept':", "self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with an Accept:", "return all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self): \"\"\"Test that versioning is", "{'versions': [ { 'id': 'v1.1', 'status': 'DEPRECATED', 'links': [{'rel': 'self',", "url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v2_versions(url) # Verify", "content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET", "self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert GET /images with `no Accept:`", "content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with an Accept: application/vnd.openstack.images-v1", "'id': 'v2.6', 'status': 'CURRENT', 'links': [{'rel': 'self', 'href': url %", "the License. \"\"\"Version-independent api tests\"\"\" import httplib2 from oslo_serialization import", "self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v1_versions(url) #", "GET /images with `no Accept:` header. Verify version choices returned.", "oslo_serialization import jsonutils from six.moves import http_client from glance.tests import", "self.api_port) http = httplib2.Http() headers = {'Accept': 'unknown'} response, content_json", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions", "License for the specific language governing permissions and limitations #", "import http_client from glance.tests import functional # TODO(rosmaita): all the", "def _generate_v2_versions(url): version_list = [] version_list.extend([ { 'id': 'v2.6', 'status':", "GET /images with a `Accept: application/vnd.openstack.compute-v2` header. Verify version choices", "v1_versions = {'versions': [ { 'id': 'v1.1', 'status': 'DEPRECATED', 'links':", "% '2'}], } ]) v2_versions = {'versions': version_list} return v2_versions", "= httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def", "httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET',", "http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status)", "on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS", "returned. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http =", "content) def test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy())", "test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with no Accept: header Verify version", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "in Queens def _generate_v1_versions(url): v1_versions = {'versions': [ { 'id':", "application/vnd.openstack.compute-v1` header. Verify version choices returned. Verify message in API", "'id': 'v1.0', 'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url %", "'id': 'v2.4', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "Rights Reserved. # # Licensed under the Apache License, Version", "test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with no Accept: header Verify version", "path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert", "'self', 'href': url % '2'}], }, { 'id': 'v2.3', 'status':", "self.api_port versions = _generate_v1_versions(url) # Verify version choices returned. path", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert", "response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content =", "\"\"\"Assert GET /images with `no Accept:` header. Verify version choices", "causes a 500 in glance-api \"\"\" path = 'http://%s:%d' %", "{'Accept': 'application/vnd.openstack.images-v10'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status)", "Licensed under the Apache License, Version 2.0 (the \"License\"); you", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert GET", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with no Accept:", "response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with no Accept: header", "returned. \"\"\" path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http =", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert GET", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "500 in glance-api \"\"\" path = 'http://%s:%d' % ('127.0.0.1', self.api_port)", "def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with `no Accept:` header Verify", "def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with no Accept: header Verify", "image list returned \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)", "httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content =", "version choices returned. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.3',", "OpenStack Foundation # All Rights Reserved. # # Licensed under", "headers=headers) self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self):", "% '2'}], }, { 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel':", "/ with `no Accept:` header. Verify version choices returned. Bug", "/v1/images with `no Accept:` header. Verify empty images list returned.", "_generate_all_versions(url) images = {'images': []} self.images_json = jsonutils.dumps(images) def test_get_root_path(self):", "Queens def _generate_v1_versions(url): v1_versions = {'versions': [ { 'id': 'v1.1',", "content) def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with no Accept: header", "= 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_all_versions(url) # Verify version", "compliance with the License. You may obtain # a copy", "'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "Verify version choices returned \"\"\" path = 'http://%s:%d/va.1/images' % ('127.0.0.1',", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with", "version choices returned\"\"\" path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http", "% ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.compute-v1'}", "log about unknown accept header. \"\"\" path = 'http://%s:%d/' %", "jsonutils from six.moves import http_client from glance.tests import functional #", "no Accept header causes a 500 in glance-api \"\"\" path", "= httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content_json = http.request(path,", "GET /v1.a/images with no Accept: header Verify version choices returned", "test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\" path = 'http://%s:%d/v10' % ('127.0.0.1',", "('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response,", "]} return v1_versions def _generate_v2_versions(url): version_list = [] version_list.extend([ {", "jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api =", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert", "becomes CURRENT in Queens def _generate_v1_versions(url): v1_versions = {'versions': [", "\"\"\"Version-independent api tests\"\"\" import httplib2 from oslo_serialization import jsonutils from", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api", "% '1'}], }, { 'id': 'v1.0', 'status': 'DEPRECATED', 'links': [{'rel':", "channels\"\"\" # v1 and v2 api enabled self.start_servers(**self.__dict__.copy()) url =", "the # License for the specific language governing permissions and", "a `Accept: application/vnd.openstack.compute-v1` header. Verify version choices returned. Verify message", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.2',", "accept header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http", "about unknown version in accept header. \"\"\" path = 'http://%s:%d/images'", "('127.0.0.1', self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET')", "# # Unless required by applicable law or agreed to", "= {'Accept': 'application/vnd.openstack.images-v10'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES,", "= _generate_v1_versions(url) # Verify version choices returned. path = 'http://%s:%d'", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api =", "path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "% self.api_port self.versions = _generate_all_versions(url) images = {'images': []} self.images_json", "http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content =", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert GET /versions with", "'href': url % '2'}], }, { 'id': 'v2.4', 'status': 'SUPPORTED',", "'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json =", "choices returned. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http", "('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'unknown'} response,", "('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response,", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions", "_generate_v2_versions(url) all_versions = {'versions': v2['versions'] + v1['versions']} return all_versions class", "unknown accept header. \"\"\" path = 'http://%s:%d/' % ('127.0.0.1', self.api_port)", "2.0 (the \"License\"); you may # not use this file", "def test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url", "httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self):", "'v2.1', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images", "headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content_json = http.request(path, 'GET', headers=headers)", "\"\"\" path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions", "def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with Accept: unknown header Verify", "\"\"\"Test that versioning is handled properly through all channels\"\"\" #", "choices returned \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http", "empty image list returned \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1',", "lp:803260 no Accept header causes a 500 in glance-api \"\"\"", "httplib2.Http() headers = {'Accept': 'unknown'} response, content_json = http.request(path, 'GET',", "= httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api", "by applicable law or agreed to in writing, software #", "with Accept: unknown header Verify version choices returned. Verify message", "[{'rel': 'self', 'href': url % '1'}], }, { 'id': 'v1.0',", "httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self):", "returned \"\"\" path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http =", "Verify 404 returned \"\"\" path = 'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port)", "url % '1'}], }, ]} return v1_versions def _generate_v2_versions(url): version_list", "version_list = [] version_list.extend([ { 'id': 'v2.6', 'status': 'CURRENT', 'links':", "content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v1_api_configuration(self): self.api_server.enable_v1_api = True", "= http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions,", "import jsonutils from six.moves import http_client from glance.tests import functional", "application/vnd.openstack.images-v1 Verify empty image list returned \"\"\" path = 'http://%s:%d/images'", "{ 'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url", "Accept: unknown header Verify version choices returned. Verify message in", "\"\"\"Assert GET / with an Accept: application/vnd.openstack.images-v1 Verify empty image", "BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either", "application/vnd.openstack.images-v1` header. Verify version choices returned. \"\"\" path = 'http://%s:%d/versions'", "self.versions = _generate_all_versions(url) images = {'images': []} self.images_json = jsonutils.dumps(images)", "= {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK,", "= httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def", "True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_v2_versions(url)", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert GET /images", "= _generate_all_versions(url) # Verify version choices returned. path = 'http://%s:%d'", "_generate_all_versions(url): v1 = _generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions = {'versions':", "= jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp()", "'application/vnd.openstack.images-v1'} response, content = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json,", "'href': url % '2'}], }, { 'id': 'v2.3', 'status': 'SUPPORTED',", "Accept:` header Verify 404 returned \"\"\" path = 'http://%s:%d/v1/versions' %", "\"\"\"Assert GET / with Accept: unknown header Verify version choices", "response.status) def test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with no Accept: header", "'http://%s:%d/v1/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content =", "import httplib2 from oslo_serialization import jsonutils from six.moves import http_client", "\"\"\"Assert GET / with `no Accept:` header. Verify version choices", "in accept header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port)", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET", "http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content_json =", "= False self.api_server.enable_v2_api = True self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' %", "}, { 'id': 'v2.3', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "may obtain # a copy of the License at #", "test_get_va1_images_path(self): \"\"\"Assert GET /va.1/images with no Accept: header Verify version", "test_get_v1_images_path(self): \"\"\"GET /v1/images with `no Accept:` header. Verify empty images", "header. Verify version choices returned. \"\"\" path = 'http://%s:%d/versions' %", "http = httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status)", "# All Rights Reserved. # # Licensed under the Apache", "content = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def", "headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content_json = http.request(path, 'GET', headers=headers)", "Unless required by applicable law or agreed to in writing,", "'v2.4', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content =", "\"\"\" path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "version choices returned. Verify message in API log about unknown", "response, content = http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify", "httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'} response, content_json = http.request(path, 'GET',", "path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers", "{'Accept': 'application/vnd.openstack.images-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status)", "version_list} return v2_versions def _generate_all_versions(url): v1 = _generate_v1_versions(url) v2 =", "content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with the `Accept: application/vnd.openstack.images-v1`", "with `no Accept:` header Verify 404 returned \"\"\" path =", "versions = _generate_v1_versions(url) # Verify version choices returned. path =", "applicable law or agreed to in writing, software # distributed", "# under the License. \"\"\"Version-independent api tests\"\"\" import httplib2 from", "self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api = False self.api_server.enable_v2_api = True", "content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) def test_v2_api_configuration(self): self.api_server.enable_v1_api = False", "with an Accept: application/vnd.openstack.images-v1 Verify empty image list returned \"\"\"", "under the License. \"\"\"Version-independent api tests\"\"\" import httplib2 from oslo_serialization", "headers=headers) self.assertEqual(http_client.OK, response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images", "test_v1_api_configuration(self): self.api_server.enable_v1_api = True self.api_server.enable_v2_api = False self.start_servers(**self.__dict__.copy()) url =", "choices returned. Verify message in API log about unknown accept", "def test_get_root_path(self): \"\"\"Assert GET / with `no Accept:` header. Verify", "glance-api \"\"\" path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http =", "test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with Accept: unknown header Verify version", "= http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content)", "'1'}], }, ]} return v1_versions def _generate_v2_versions(url): version_list = []", "OF ANY KIND, either express or implied. See the #", "enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_all_versions(url)", "returned. Verify message in API log about unknown version in", "test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with `no Accept:` header Verify version", "headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self):", "`no Accept:` header. Verify empty images list returned. \"\"\" path", "response, content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode())", "'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert GET / with Accept:", "GET / with Accept: unknown header Verify version choices returned.", "list returned \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http", "api enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions =", "\"\"\"Assert GET /va.1/images with no Accept: header Verify version choices", "WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express", "in writing, software # distributed under the License is distributed", "response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content =", "header. Verify version choices returned. Verify message in API log", "http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status)", "response, content = http.request(path, 'GET') self.assertEqual(http_client.OK, response.status) def test_get_root_path_with_unknown_header(self): \"\"\"Assert", "url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions = _generate_all_versions(url) # Verify", "\"\"\"Assert GET /v1.0/images with no Accept: header Verify version choices", "'href': url % '1'}], }, ]} return v1_versions def _generate_v2_versions(url):", "choices returned \"\"\" path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http", "% '2'}], }, { 'id': 'v2.0', 'status': 'SUPPORTED', 'links': [{'rel':", "'v2.0', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert GET", "Verify message in API log about unknown version in accept", "in this file can be ripped out # when v2.6", "about unknown accept header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1',", "# Verify version choices returned. path = 'http://%s:%d' % ('127.0.0.1',", "% ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v10'}", "is handled properly through all channels\"\"\" # v1 and v2", "choices returned \"\"\" path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http", "\"\"\"Assert GET /v1.a/images with no Accept: header Verify version choices", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self): \"\"\"Assert GET /images with `no", "Bug lp:803260 no Accept header causes a 500 in glance-api", "{'versions': v2['versions'] + v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest): def test_version_configurations(self):", "test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with the `Accept: application/vnd.openstack.images-v1` header. Verify", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path_with_openstack_header(self): \"\"\"Assert GET /versions with the", "'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }", "}, { 'id': 'v2.5', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "= {'versions': v2['versions'] + v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest): def", "% self.api_port versions = _generate_all_versions(url) # Verify version choices returned.", "header Verify version choices returned \"\"\" path = 'http://%s:%d/v1.2/images' %", "'status': 'DEPRECATED', 'links': [{'rel': 'self', 'href': url % '1'}], },", "= _generate_all_versions(url) images = {'images': []} self.images_json = jsonutils.dumps(images) def", "log about unknown accept header. \"\"\" path = 'http://%s:%d/images' %", "path = 'http://%s:%d/va.1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content)", "either express or implied. See the # License for the", "v1 = _generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions = {'versions': v2['versions']", "`no Accept:` header. Verify version choices returned. Bug lp:803260 no", "'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}], }, {", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "def _generate_all_versions(url): v1 = _generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions =", "may # not use this file except in compliance with", "Verify empty image list returned \"\"\" path = 'http://%s:%d/images' %", "= 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "TODO(rosmaita): all the EXPERIMENTAL stuff in this file can be", "'links': [{'rel': 'self', 'href': url % '1'}], }, { 'id':", "api tests\"\"\" import httplib2 from oslo_serialization import jsonutils from six.moves", "'application/vnd.openstack.images-v1'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content", "# License for the specific language governing permissions and limitations", "with the License. You may obtain # a copy of", "/images with a `Accept: application/vnd.openstack.compute-v1` header. Verify version choices returned.", "from glance.tests import functional # TODO(rosmaita): all the EXPERIMENTAL stuff", "you may # not use this file except in compliance", "{'versions': version_list} return v2_versions def _generate_all_versions(url): v1 = _generate_v1_versions(url) v2", "= http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content)", "header. Verify version choices returned. \"\"\" path = 'http://%s:%d/images' %", "= http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify version choices", "header causes a 500 in glance-api \"\"\" path = 'http://%s:%d'", "Accept: header Verify version choices returned \"\"\" path = 'http://%s:%d/versions'", "self.api_port) http = httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content_json", "self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert GET /versions with no Accept:", "test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with a `Accept: application/vnd.openstack.compute-v1` header. Verify", "unknown version in accept header. \"\"\" path = 'http://%s:%d/images' %", "Foundation # All Rights Reserved. # # Licensed under the", "can be ripped out # when v2.6 becomes CURRENT in", "test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with `no Accept:` header Verify 404", "self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with a `Accept:", "\"\"\" path = 'http://%s:%d/v1/images' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "with `no Accept:` header. Verify empty images list returned. \"\"\"", "# Copyright 2012 OpenStack Foundation # All Rights Reserved. #", "header. Verify empty images list returned. \"\"\" path = 'http://%s:%d/v1/images'", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "return v2_versions def _generate_all_versions(url): v1 = _generate_v1_versions(url) v2 = _generate_v2_versions(url)", "self.images_json = jsonutils.dumps(images) def test_get_root_path(self): \"\"\"Assert GET / with `no", "versions = _generate_all_versions(url) # Verify version choices returned. path =", "% '2'}], }, { 'id': 'v2.5', 'status': 'SUPPORTED', 'links': [{'rel':", "v2 api enabled self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions", "# WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "/versions with the `Accept: application/vnd.openstack.images-v1` header. Verify version choices returned.", "this file can be ripped out # when v2.6 becomes", "= http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images", "path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "= jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_root_path_with_openstack_header(self): \"\"\"Assert GET / with", "response.status) self.assertEqual(self.images_json, content.decode()) def test_get_images_path_with_openstack_header(self): \"\"\"Assert GET /images with a", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images", "def test_get_v1a_images_path(self): \"\"\"Assert GET /v1.a/images with no Accept: header Verify", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert GET /v1.0/images with no", "choices returned\"\"\" path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http =", "= [] version_list.extend([ { 'id': 'v2.6', 'status': 'CURRENT', 'links': [{'rel':", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "API log about unknown accept header. \"\"\" path = 'http://%s:%d/images'", "= 'http://%s:%d/v10' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content_json", "_generate_v1_versions(url) # Verify version choices returned. path = 'http://%s:%d' %", "content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode())", "http.request(path, 'GET') self.assertEqual(http_client.NOT_FOUND, response.status) def test_get_versions_choices(self): \"\"\"Verify version choices returned\"\"\"", "\"\"\"Assert GET /v1.2/images with `no Accept:` header Verify version choices", "version choices returned \"\"\" path = 'http://%s:%d/v1.2/images' % ('127.0.0.1', self.api_port)", "ripped out # when v2.6 becomes CURRENT in Queens def", "self.api_port) http = httplib2.Http() response, content_json = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES,", "for the specific language governing permissions and limitations # under", "'id': 'v2.2', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url %", "TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' %", "\"\"\"GET /v1/images with `no Accept:` header. Verify empty images list", "self.assertEqual(self.versions, content) def test_get_v12_images_path(self): \"\"\"Assert GET /v1.2/images with `no Accept:`", "Verify version choices returned. path = 'http://%s:%d' % ('127.0.0.1', self.api_port)", "choices returned. \"\"\" path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http", "except in compliance with the License. You may obtain #", "headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v12_images_path(self):", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET /v1/images with `no Accept:`", "\"\"\"Verify version choices returned\"\"\" path = 'http://%s:%d/v10' % ('127.0.0.1', self.api_port)", "about unknown accept header. \"\"\" path = 'http://%s:%d/' % ('127.0.0.1',", "'http://%s:%d/' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers = {'Accept':", "GET /images with a `Accept: application/vnd.openstack.compute-v1` header. Verify version choices", "Accept: header Verify version choices returned \"\"\" path = 'http://%s:%d/v1.a/images'", "GET /versions with no Accept: header Verify version choices returned", "% '2'}], }, { 'id': 'v2.3', 'status': 'SUPPORTED', 'links': [{'rel':", "with `no Accept:` header Verify version choices returned \"\"\" path", "file can be ripped out # when v2.6 becomes CURRENT", "License. You may obtain # a copy of the License", "[{'rel': 'self', 'href': url % '2'}], }, { 'id': 'v2.0',", "httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content_json = http.request(path, 'GET',", "self.assertEqual(http_client.OK, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert", "`Accept: application/vnd.openstack.compute-v1` header. Verify version choices returned. Verify message in", "% self.api_port versions = _generate_v2_versions(url) # Verify version choices returned.", "v2_versions = {'versions': version_list} return v2_versions def _generate_all_versions(url): v1 =", "# distributed under the License is distributed on an \"AS", "ANY KIND, either express or implied. See the # License", "CURRENT in Queens def _generate_v1_versions(url): v1_versions = {'versions': [ {", "= False self.start_servers(**self.__dict__.copy()) url = 'http://127.0.0.1:%d/v%%s/' % self.api_port versions =", "self.assertEqual(self.versions, content) def test_get_v1_versions_path(self): \"\"\"Assert GET /v1/versions with `no Accept:`", "self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest): def setUp(self): super(TestApiPaths, self).setUp() self.start_servers(**self.__dict__.copy()) url", "}, { 'id': 'v2.4', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href':", "# Unless required by applicable law or agreed to in", "/images with a `Accept: application/vnd.openstack.compute-v2` header. Verify version choices returned.", "choices returned. Verify message in API log about unknown version", "'links': [{'rel': 'self', 'href': url % '1'}], }, ]} return", "'v2.5', 'status': 'SUPPORTED', 'links': [{'rel': 'self', 'href': url % '2'}],", "properly through all channels\"\"\" # v1 and v2 api enabled", "with no Accept: header Verify version choices returned \"\"\" path", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(versions, content) class TestApiPaths(functional.FunctionalTest):", "permissions and limitations # under the License. \"\"\"Version-independent api tests\"\"\"", "'self', 'href': url % '2'}], }, { 'id': 'v2.0', 'status':", "is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES", "2012 OpenStack Foundation # All Rights Reserved. # # Licensed", "self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v10_images_path(self): \"\"\"Assert", "= _generate_v2_versions(url) all_versions = {'versions': v2['versions'] + v1['versions']} return all_versions", "versions = _generate_v2_versions(url) # Verify version choices returned. path =", "'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path(self):", "Verify version choices returned. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1',", "header Verify version choices returned \"\"\" path = 'http://%s:%d/versions' %", "content = http.request(path, 'GET') self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) def test_get_va1_images_path(self): \"\"\"Assert GET", "test_version_configurations(self): \"\"\"Test that versioning is handled properly through all channels\"\"\"", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_versions_path(self): \"\"\"Assert GET /versions with no", "`no Accept:` header Verify version choices returned \"\"\" path =", "path = 'http://%s:%d/versions' % ('127.0.0.1', self.api_port) http = httplib2.Http() headers", "\"\"\"Assert GET /v1/versions with `no Accept:` header Verify 404 returned", "'unknown'} response, content_json = http.request(path, 'GET', headers=headers) self.assertEqual(http_client.MULTIPLE_CHOICES, response.status) content", "= httplib2.Http() headers = {'Accept': 'application/vnd.openstack.images-v1'} response, content = http.request(path,", "'DEPRECATED', 'links': [{'rel': 'self', 'href': url % '1'}], }, ]}", "language governing permissions and limitations # under the License. \"\"\"Version-independent", "Accept: application/vnd.openstack.images-v1 Verify empty image list returned \"\"\" path =", "returned \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http =", "_generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions = {'versions': v2['versions'] + v1['versions']}", "= 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response, content", "path = 'http://%s:%d/images' % ('127.0.0.1', self.api_port) http = httplib2.Http() response,", "= _generate_v1_versions(url) v2 = _generate_v2_versions(url) all_versions = {'versions': v2['versions'] +", "jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_images_path_with_openstack_v2_header(self): \"\"\"Assert GET /images with a", "returned \"\"\" path = 'http://%s:%d/v1.a/images' % ('127.0.0.1', self.api_port) http =", "all_versions = {'versions': v2['versions'] + v1['versions']} return all_versions class TestApiVersions(functional.FunctionalTest):", "version in accept header. \"\"\" path = 'http://%s:%d/images' % ('127.0.0.1',", "content) def test_get_v1_images_path(self): \"\"\"GET /v1/images with `no Accept:` header. Verify", "response.status) content = jsonutils.loads(content_json.decode()) self.assertEqual(self.versions, content) def test_get_v1_images_path(self): \"\"\"GET /v1/images", "\"\"\" path = 'http://%s:%d' % ('127.0.0.1', self.api_port) http = httplib2.Http()", "'href': url % '1'}], }, { 'id': 'v1.0', 'status': 'DEPRECATED',", "url = 'http://127.0.0.1:%d/v%%s/' % self.api_port self.versions = _generate_all_versions(url) images =", "or implied. See the # License for the specific language" ]
[ "wrote the code. \"\"\" __all__ = [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\",", "2.0 (the \"License\"); # you may not use this file", "# Return True to suppress the Exception if the type", "# Copyright 2016 Quora, Inc. # # Licensed under the", "not start with prefix.\"\"\" assert ( (type(subject) is str) and", "actual, _assert_fail_message( message, expected, actual, \"==\", extra ) else: assert", "if left_hand < right_hand.\"\"\" assert left >= right, _assert_fail_message(message, left,", "instead of assert expected == actual include: 1 - On", "right_hand.\"\"\" assert left <= right, _assert_fail_message(message, left, right, \">\", extra)", "message, expected, actual, \"is more than %a away from\" %", "\"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\",", "the difference between expected and actual is larger than the", "!= actual, _assert_fail_message( message, expected, actual, \"==\", extra ) else:", "if substring is a substring of subject.\"\"\" assert ( (subject", "string does not end with suffix.\"\"\" assert ( (type(subject) is", "an informative message of the actual values compared (e.g. AssertionError:", "is not None: message += \" (%s)\" % self.extra else:", "message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected == actual.", "(e.g. AssertionError: 1 != 2) for free, which makes it", "start with prefix.\"\"\" assert ( (type(subject) is str) and (type(prefix)", "= list(actual) for x in expected: try: missing_in_expected.remove(x) except ValueError:", "expected and actual is larger than the tolerance. \"\"\" if", "== 0: return \"(root)\" return \"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual,", "left <= right, _assert_fail_message(message, left, right, \">\", extra) def assert_in(obj,", "an instance of\", extra ) def assert_eq(expected, actual, message=None, tolerance=None,", "License for the specific language governing permissions and # limitations", "extra=None): \"\"\"Raises an AssertionError if obj is not in seq", "of refactors, basic asserts incorrectly shift the burden of adding", "assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj is", "assert_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj is", "% (expected, comparison_str, actual) def assert_is(expected, actual, message=None, extra=None): \"\"\"Raises", "using AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found = None self.extra =", "tolerance, extra ) def _dict_path_string(path): if len(path) == 0: return", "obj not in seq, _assert_fail_message(message, obj, seq, \"is in\", extra)", "# for very long strings, provide a truncated error if", "larger than the tolerance. \"\"\" if tolerance is None: assert", "extra=\"Types don't match for %s\" % _dict_path_string(key_path), ) if isinstance(actual[k],", "- the difference between expected and actual is smaller than", "for free, which makes it faster and easier to iterate", "_assert_fail_message(message, left, right, \"<=\", extra) def assert_ge(left, right, message=None, extra=None):", "\"<=\", extra) def assert_ge(left, right, message=None, extra=None): \"\"\"Raises an AssertionError", "\"is in\", extra) def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): \"\"\"Raises", "left_hand > right_hand.\"\"\" assert left <= right, _assert_fail_message(message, left, right,", "extra=\"Types don't match for %s\" % _dict_path_string(key_path), ) assert_is_instance( expected[k],", "extra) def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an AssertionError if the", "an AssertionError if left_hand >= right_hand.\"\"\" assert left < right,", "t): self.expected_exception_found = exc_val return True expected = \", \".join(map(get_full_name,", "%a away from\" % tolerance, extra ) def _dict_path_string(path): if", "subject string does not start with prefix.\"\"\" assert ( (type(subject)", "subject string does not end with suffix.\"\"\" assert ( (type(subject)", "strings, provide a truncated error if isinstance(seq, str) and obj", "actual, \"is more than %a away from\" % tolerance, extra", "tolerance is specified: %a, %a\" % ( expected, actual, )", "tolerance, _assert_fail_message( message, expected, actual, \"is more than %a away", "- actual_keys, ) assert actual_keys <= expected_keys, \"Actual dict at", "actually throw an exception different from the expected one assert", "is missing keys: %a\" % ( _dict_path_string(dict_path), expected_keys - actual_keys,", "person who initially wrote the code. \"\"\" __all__ = [", "\"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\",", "# __unittest = 1 import traceback from .inspection import get_full_name", "def assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring", "seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj is in", "OF ANY KIND, either express or implied. # See the", "\"\"\"Raises an AssertionError if obj is not in seq.\"\"\" assert", "[k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't match for %s\" %", "See the License for the specific language governing permissions and", "to in writing, software # distributed under the License is", ") diff = abs(expected - actual) assert diff <= tolerance,", "or agreed to in writing, software # distributed under the", "dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra=\"Value doesn't", "exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs): # when you don't specify", "%a\" % ( expected, actual, ) diff = abs(expected -", "tolerance is None: assert expected == actual, _assert_fail_message( message, expected,", "dict at %s has extra keys: %a\" % ( _dict_path_string(dict_path),", "obj, seq, \"is in\", extra) def assert_in_with_tolerance(obj, seq, tolerance, message=None,", "# Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] # The unittest.py", "actual values compared (e.g. AssertionError: 1 != 2) for free,", "assert_eq prints an informative message of the actual values compared", "- 50 if start_index > 0: truncated = \"(truncated) ...\"", "AssertionError: 1 != 2) for free, which makes it faster", "is str) and (type(suffix) is str) and (subject.endswith(suffix)) ), _assert_fail_message(message,", "compliance with the License. # You may obtain a copy", "def assert_lt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand", "filter out stack frames from that module from the test", "\"%a not equal to %a; missing items: %a in expected,", "\"(root)\" return \"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts", "expected, actual, \"==\", extra ) else: assert isinstance(tolerance, _number_types), (", "fn does not raise one of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types):", "0 end_index = index + len(obj) + 50 truncated +=", "not use this file except in compliance with the License.", "is not actual, _assert_fail_message( message, expected, actual, \"is\", extra )", "message def assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError if calling fn", "% self.extra else: template = ( \"{TYPE}: {VAL} is raised,", "you may not use this file except in compliance with", "=================================================== def assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if", "string does not start with prefix.\"\"\" assert ( (type(subject) is", "left, right, \"<=\", extra) def assert_ge(left, right, message=None, extra=None): \"\"\"Raises", "== -1) ), _assert_fail_message(message, substring, subject, \"is in\", extra) def", "or - the difference between expected and actual is smaller", "actual[k], extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), tolerance=number_tolerance, )", "message=message, extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message, obj,", "is str) and (type(prefix) is str) and (subject.startswith(prefix)) ), _assert_fail_message(message,", "or actual isn't a number, or - the difference between", "right, \"<\", extra) def assert_lt(left, right, message=None, extra=None): \"\"\"Raises an", "and len(seq) > 200: index = seq.find(obj) start_index = index", "of assert expected == actual include: 1 - On failures,", "- actual) assert diff > tolerance, _assert_fail_message( message, expected, actual,", "try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass", "not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject,", "for very long strings, provide a truncated error if isinstance(seq,", "assert left < right, _assert_fail_message(message, left, right, \">=\", extra) def", "\"\" start_index = 0 end_index = index + len(obj) +", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "*expected_exception_types): \"\"\"Raises an AssertionError if calling fn does not raise", "message, expected, actual, \"is\", extra ) def assert_is_instance(value, types, message=None,", "left, right, \">=\", extra) def assert_le(left, right, message=None, extra=None): \"\"\"Raises", "extra): if message: return message if extra: return \"%a %s", "burden of adding printouts and writing good test code to", "Module with assertion helpers. The advantages of using a method", "between expected and actual is larger than the tolerance. \"\"\"", "obj, seq, \"is not in\", extra) def assert_not_in(obj, seq, message=None,", "make the output more concise. # __unittest = 1 import", "using a method like assert_eq(expected, actual) instead of assert expected", "assert expected_keys <= actual_keys, \"Actual dict at %s is missing", "does not raise one of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn()", "None: assert expected != actual, _assert_fail_message( message, expected, actual, \"==\",", "AssertionError if the subject string does not start with prefix.\"\"\"", "custom message if they are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict)", "left, right, \"<\", extra) def assert_lt(left, right, message=None, extra=None): \"\"\"Raises", "assert_eq(expected, actual) instead of assert expected == actual include: 1", "assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys", "assert ( (type(subject) is str) and (type(suffix) is str) and", "expected[k], actual[k], extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), tolerance=number_tolerance,", "assert isinstance(tolerance, _number_types), ( \"tolerance parameter to assert_eq must be", "initially wrote the code. \"\"\" __all__ = [ \"assert_is\", \"assert_is_not\",", "(subject is not None) and (substring is not None) and", "(int, float, complex) def _assert_fail_message(message, expected, actual, comparison_str, extra): if", "k in expected_keys: key_path = dict_path + [k] assert_is_instance( actual[k],", "x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual", "people refactoring code rather than the person who initially wrote", "must be numbers when tolerance is specified: %a, %a\" %", "number, or - the difference between expected and actual is", "advantages of using a method like assert_eq(expected, actual) instead of", "\"{TYPE}: {VAL} is raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message", "expected, actual, \"is more than %a away from\" % tolerance,", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "if the type matches. For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found", "EXTRA_STR=(\" (%s)\" % self.extra) if self.extra is not None else", "start with\", extra) def assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises an", "_assert_fail_message(message, obj, seq, \"is in\", extra) def assert_in_with_tolerance(obj, seq, tolerance,", "iter.\"\"\" # for very long strings, provide a truncated error", "actual, message=None): \"\"\"Raises an AssertionError if the objects contained in", "actual, _assert_fail_message( message, expected, actual, \"is\", extra ) def assert_is_instance(value,", "obj, truncated, \"is in\", extra) assert obj not in seq,", "the exception expected, it's easy to write buggy tests that", "True expected = \", \".join(map(get_full_name, self.expected_exception_types)) if exc_type is None:", "is not actual.\"\"\" assert expected is actual, _assert_fail_message( message, expected,", "in expected_keys: key_path = dict_path + [k] assert_is_instance( actual[k], type(expected[k]),", "if obj is in iter.\"\"\" # for very long strings,", "actual, \"is not\", extra ) def assert_is_not(expected, actual, message=None, extra=None):", "file except in compliance with the License. # You may", "actual, \"is\", extra ) def assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises", "( \"tolerance parameter to assert_eq must be a number: %a\"", "\"\"\"Raises an AssertionError if obj is not in seq using", "is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring,", "return \"(root)\" return \"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]):", "\"is in\", extra) def assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises an", "Return True to suppress the Exception if the type matches.", "expected == actual, _assert_fail_message( message, expected, actual, \"!=\", extra )", "\"\"\"Raises an AssertionError if the objects contained in expected are", ") else: assert_eq( expected[k], actual[k], extra=\"Value doesn't match for %s\"", "extra) def assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if", "of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context that", "dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <=", "\"is not in\", extra) def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an", "if expected is not actual.\"\"\" assert expected is actual, _assert_fail_message(", "), \"You must specify the exception type when using AssertRaises\"", "that the code within the context raises the specified exception.\"\"\"", "(expected, actual, missing_in_expected, missing_in_actual) ) assert False, message def assert_raises(fn,", "%a, %a\" % ( expected, actual, ) diff = abs(expected", "types, message=None, extra=None): \"\"\"Raises an AssertionError if value is not", "for t in self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found = exc_val", "on tests. 2 - In the context of refactors, basic", "\"Actual dict at %s is missing keys: %a\" % (", "def assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj", "and (subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix, \"does not end with\",", "test code to people refactoring code rather than the person", ") assert actual_keys <= expected_keys, \"Actual dict at %s has", "dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't match for", "not in seq.\"\"\" assert obj in seq, _assert_fail_message(message, obj, seq,", "{EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\"", "message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" %", "asserts incorrectly shift the burden of adding printouts and writing", "items: %a in expected, %a in actual.\" % (expected, actual,", "False, _assert_fail_message(message, obj, truncated, \"is in\", extra) assert obj not", "2) for free, which makes it faster and easier to", "KIND, either express or implied. # See the License for", "else: assert_eq( expected[k], actual[k], extra=\"Value doesn't match for %s\" %", "set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, \"Actual dict", "if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif", "right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand <= right_hand.\"\"\"", "and actual is larger than the tolerance. \"\"\" if tolerance", "expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k],", "abs(expected - actual) assert diff > tolerance, _assert_fail_message( message, expected,", "expected is actual.\"\"\" assert expected is not actual, _assert_fail_message( message,", "(the \"License\"); # you may not use this file except", "( \"%a not equal to %a; missing items: %a in", "\"... (truncated)\" assert False, _assert_fail_message(message, obj, truncated, \"is in\", extra)", "keys: %a\" % ( _dict_path_string(dict_path), actual_keys - expected_keys, ) for", "(type(subject) is str) and (type(suffix) is str) and (subject.endswith(suffix)) ),", "to write buggy tests that appear # to pass but", "# # Unless required by applicable law or agreed to", "def assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError if calling fn does", "not in\", extra) def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an AssertionError", "dict at %s is missing keys: %a\" % ( _dict_path_string(dict_path),", "assert ( (type(subject) is str) and (type(prefix) is str) and", "to # filter out stack frames from that module from", "throw an exception different from the expected one assert (", "long lists. \"\"\" missing_in_actual = [] missing_in_expected = list(actual) for", "values compared (e.g. AssertionError: 1 != 2) for free, which", "truncated error if isinstance(seq, str) and obj in seq and", "else: template = ( \"{TYPE}: {VAL} is raised, but expected:\"", "implied. # See the License for the specific language governing", "assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq(", "return except AssertionError: pass assert False, _assert_fail_message(message, obj, seq, \"is", "tests that appear # to pass but actually throw an", "_assert_fail_message(message, left, right, \"<\", extra) def assert_lt(left, right, message=None, extra=None):", "right, \">\", extra) def assert_in(obj, seq, message=None, extra=None): \"\"\"Raises an", "= index + len(obj) + 50 truncated += seq[start_index:end_index] if", "self.expected_exception_found = None self.extra = kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def", "diff <= tolerance, _assert_fail_message( message, expected, actual, \"is more than", "+= \"... (truncated)\" assert False, _assert_fail_message(message, obj, truncated, \"is in\",", "seq, \"is not in\", extra) def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises", "%a\" % tolerance ) assert isinstance(expected, _number_types) and isinstance( actual,", "order to # make the output more concise. # __unittest", "are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys", "makes it faster and easier to iterate on tests. 2", "< right_hand.\"\"\" assert left >= right, _assert_fail_message(message, left, right, \"<\",", "% _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance,", "i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert False,", "_number_types = (int, float, complex) def _assert_fail_message(message, expected, actual, comparison_str,", "AssertionError if expected is actual.\"\"\" assert expected is not actual,", "**kwargs): # when you don't specify the exception expected, it's", "in actual; don't use it for very long lists. \"\"\"", "VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra) if self.extra is", "assert obj not in seq, _assert_fail_message(message, obj, seq, \"is in\",", "expected or actual isn't a number, or - the difference", "\"\"\"Raises an AssertionError if the subject string does not start", "Unless required by applicable law or agreed to in writing,", "and easier to iterate on tests. 2 - In the", "message=None): \"\"\"Raises an AssertionError if the objects contained in expected", "comparison_str, extra): if message: return message if extra: return \"%a", "the specific language governing permissions and # limitations under the", "1 import traceback from .inspection import get_full_name _number_types = (int,", "_number_types), ( \"tolerance parameter to assert_eq must be a number:", "specify the exception type when using AssertRaises\" self.expected_exception_types = set(expected_exception_types)", "_number_types) and isinstance( actual, _number_types ), \"parameters must be numbers", "is None: message = \"No exception raised, but expected: %s\"", "\"\"\"Raises an AssertionError if value is not an instance of", "_assert_fail_message(message, left, right, \">\", extra) def assert_in(obj, seq, message=None, extra=None):", "type when using AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found = None", "without regard to their order. This takes quadratic time in", "_assert_fail_message( message, expected, actual, \"is not\", extra ) def assert_is_not(expected,", "\"\"\"Raises an AssertionError if expected == actual. If tolerance is", "less than %a away from\" % tolerance, extra ) def", "in seq, _assert_fail_message(message, obj, seq, \"is in\", extra) def assert_in_with_tolerance(obj,", "\"\"\"Raises an AssertionError if left_hand < right_hand.\"\"\" assert left >=", "incorrectly shift the burden of adding printouts and writing good", "assert diff > tolerance, _assert_fail_message( message, expected, actual, \"is less", "float, complex) def _assert_fail_message(message, expected, actual, comparison_str, extra): if message:", "\"\"\"Raises an AssertionError if calling fn does not raise one", "message if they are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys", "__enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type", "and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, \"is not", "def __init__(self, *expected_exception_types, **kwargs): # when you don't specify the", "isinstance(exc_val, t): self.expected_exception_found = exc_val return True expected = \",", "%a; missing items: %a in expected, %a in actual.\" %", "if obj is not in seq.\"\"\" assert obj in seq,", "-1) ), _assert_fail_message(message, substring, subject, \"is not in\", extra) def", "( (subject is not None) and (substring is not None)", "AssertionError if obj is not in seq using assert_eq cmp.\"\"\"", "permissions and # limitations under the License. \"\"\" Module with", "if isinstance(seq, str) and obj in seq and len(seq) >", "# see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return True for t", "= None self.extra = kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def __enter__(self):", "\"\"\"Raises an AssertionError if the subject string does not end", "= \"\" start_index = 0 end_index = index + len(obj)", "actual.\" % (expected, actual, missing_in_expected, missing_in_actual) ) assert False, message", "AssertionError if calling fn does not raise one of the", ") diff = abs(expected - actual) assert diff > tolerance,", "== actual. If tolerance is specified, raises an AssertionError if", "\"Actual dict at %s has extra keys: %a\" % (", "*expected_exception_types, **kwargs): # when you don't specify the exception expected,", "actual) instead of assert expected == actual include: 1 -", "None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, \"is", "either - expected or actual isn't a number, or -", "= (int, float, complex) def _assert_fail_message(message, expected, actual, comparison_str, extra):", "expected, actual, \"is\", extra ) def assert_is_instance(value, types, message=None, extra=None):", "\"assert_endswith\", ] # The unittest.py testing framework checks for this", "- expected or actual isn't a number, or - the", "more than %a away from\" % tolerance, extra ) def", "prefix.\"\"\" assert ( (type(subject) is str) and (type(prefix) is str)", "\"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\",", "the Exception if the type matches. For details, # see:", "prefix, \"does not start with\", extra) def assert_endswith(suffix, subject, message=None,", "( \"{TYPE}: {VAL} is raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" )", "informative message of the actual values compared (e.g. AssertionError: 1", "subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring is a", "is specified: %a, %a\" % ( expected, actual, ) diff", "% _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't match for", "__all__ = [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\",", "in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or", "expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected,", "assert False, _assert_fail_message(message, obj, truncated, \"is in\", extra) assert obj", "than the person who initially wrote the code. \"\"\" __all__", "tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected != actual. If", "actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected ==", "extra ) def assert_gt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError", "%a (%s)\" % (expected, comparison_str, actual, extra) return \"%a %s", "assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys())", "\"is not in\", extra) def assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises", "concise. # __unittest = 1 import traceback from .inspection import", "%s has extra keys: %a\" % ( _dict_path_string(dict_path), actual_keys -", "== actual include: 1 - On failures, assert_eq prints an", "and (subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix, \"does not start with\",", "tolerance, _assert_fail_message( message, expected, actual, \"is less than %a away", "in\", extra) def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an AssertionError if", "= exc_val return True for t in self.expected_exception_types: if isinstance(exc_val,", "You may obtain a copy of the License at #", "\"is\", extra ) def assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises an", "( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys <= expected_keys,", "(subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix, \"does not start with\", extra)", "in seq and len(seq) > 200: index = seq.find(obj) start_index", "with prefix.\"\"\" assert ( (type(subject) is str) and (type(prefix) is", "assert_eq(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected", "_assert_fail_message( message, expected, actual, \"==\", extra ) else: assert isinstance(tolerance,", "for %s\" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k],", "and actual is smaller than the tolerance. \"\"\" if tolerance", "\"\"\"Raises an AssertionError if substring is a substring of subject.\"\"\"", "expected if self.extra is not None: message += \" (%s)\"", "if extra: return \"%a %s %a (%s)\" % (expected, comparison_str,", "takes quadratic time in the umber of elements in actual;", "# The unittest.py testing framework checks for this variable in", "lists. \"\"\" missing_in_actual = [] missing_in_expected = list(actual) for x", "not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys =", "% _dict_path_string(key_path), ) def assert_ne(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises", "that appear # to pass but actually throw an exception", "away from\" % tolerance, extra ) def assert_gt(left, right, message=None,", "suppress the Exception if the type matches. For details, #", "actual without regard to their order. This takes quadratic time", "_assert_fail_message( message, expected, actual, \"is\", extra ) def assert_is_instance(value, types,", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "diff = abs(expected - actual) assert diff <= tolerance, _assert_fail_message(", "equal to %a; missing items: %a in expected, %a in", "dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert", "diff > tolerance, _assert_fail_message( message, expected, actual, \"is less than", "message, expected, actual, \"==\", extra ) else: assert isinstance(tolerance, _number_types),", "expected, actual, \"is less than %a away from\" % tolerance,", "for this variable in a module to # filter out", "one of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context", "a truncated error if isinstance(seq, str) and obj in seq", "( _dict_path_string(dict_path), actual_keys - expected_keys, ) for k in expected_keys:", "context of refactors, basic asserts incorrectly shift the burden of", "under the License. \"\"\" Module with assertion helpers. The advantages", "- In the context of refactors, basic asserts incorrectly shift", "subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring is not", "return \"%a %s %a (%s)\" % (expected, comparison_str, actual, extra)", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "License. # You may obtain a copy of the License", "<= actual_keys, \"Actual dict at %s is missing keys: %a\"", "assert_eq cmp.\"\"\" for i in seq: try: assert_eq(obj, i, tolerance=tolerance,", "self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type in self.expected_exception_types:", "that asserts that the code within the context raises the", "actual, \"is less than %a away from\" % tolerance, extra", "must be a number: %a\" % tolerance ) assert isinstance(expected,", "extra ) else: assert isinstance(tolerance, _number_types), ( \"tolerance parameter to", "quadratic time in the umber of elements in actual; don't", "to # make the output more concise. # __unittest =", "assert_eq must be a number: %a\" % tolerance ) assert", "message=None, extra=None): \"\"\"Raises an AssertionError if expected is not actual.\"\"\"", "not equal to %a; missing items: %a in expected, %a", "-1) ), _assert_fail_message(message, substring, subject, \"is in\", extra) def assert_startswith(prefix,", "isinstance(value, types), _assert_fail_message( message, value, types, \"is not an instance", "(type(prefix) is str) and (subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix, \"does", ") assert isinstance(expected, _number_types) and isinstance( actual, _number_types ), \"parameters", "%s\" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra=\"Value", "_assert_fail_message(message, left, right, \">=\", extra) def assert_le(left, right, message=None, extra=None):", "< len(seq): truncated += \"... (truncated)\" assert False, _assert_fail_message(message, obj,", "return \"%a %s %a\" % (expected, comparison_str, actual) def assert_is(expected,", "= [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\",", "missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message: message =", "the expected one assert ( len(expected_exception_types) >= 1 ), \"You", "end with suffix.\"\"\" assert ( (type(subject) is str) and (type(suffix)", "don't use it for very long lists. \"\"\" missing_in_actual =", "message=None, extra=None): \"\"\"Raises an AssertionError if substring is a substring", "%a\" % ( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys", "difference between expected and actual is larger than the tolerance.", "\"is more than %a away from\" % tolerance, extra )", "AssertionError if value is not an instance of type(s).\"\"\" assert", "seq, \"is not in\", extra) def assert_not_in(obj, seq, message=None, extra=None):", "missing_in_expected, missing_in_actual) ) assert False, message def assert_raises(fn, *expected_exception_types): \"\"\"Raises", "the objects contained in actual without regard to their order.", "raises the specified exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs): # when", "an exception different from the expected one assert ( len(expected_exception_types)", "True for t in self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found =", "right_hand.\"\"\" assert left > right, _assert_fail_message(message, left, right, \"<=\", extra)", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "if end_index < len(seq): truncated += \"... (truncated)\" assert False,", "message=None, extra=None): \"\"\"Raises an AssertionError if expected is actual.\"\"\" assert", "AssertionError if expected != actual. If tolerance is specified, raises", "an AssertionError if left_hand <= right_hand.\"\"\" assert left > right,", "in self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found = exc_val return True", "= index - 50 if start_index > 0: truncated =", "the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context that asserts", "is not None) and (substring is not None) and (subject.find(substring)", "missing items: %a in expected, %a in actual.\" % (expected,", "%s\" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't match", "required by applicable law or agreed to in writing, software", "<= tolerance, _assert_fail_message( message, expected, actual, \"is more than %a", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "assert ( (subject is not None) and (substring is not", "very long lists. \"\"\" missing_in_actual = [] missing_in_expected = list(actual)", "umber of elements in actual; don't use it for very", "number_tolerance=None, dict_path=[]): \"\"\"Asserts that two dictionaries are equal, producing a", "extra=None): \"\"\"Raises an AssertionError if substring is a substring of", "actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k],", "of adding printouts and writing good test code to people", "agreed to in writing, software # distributed under the License", "+= \" (%s)\" % self.extra else: template = ( \"{TYPE}:", "distributed under the License is distributed on an \"AS IS\"", "_assert_fail_message( message, expected, actual, \"is less than %a away from\"", "type(s).\"\"\" assert isinstance(value, types), _assert_fail_message( message, value, types, \"is not", "at %s is missing keys: %a\" % ( _dict_path_string(dict_path), expected_keys", "1 ), \"You must specify the exception type when using", "complex) def _assert_fail_message(message, expected, actual, comparison_str, extra): if message: return", "expected is not actual.\"\"\" assert expected is actual, _assert_fail_message( message,", "expected is actual, _assert_fail_message( message, expected, actual, \"is not\", extra", "% tolerance, extra ) def assert_gt(left, right, message=None, extra=None): \"\"\"Raises", "when using AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found = None self.extra", "AssertionError if substring is not a substring of subject.\"\"\" assert", "expected[k], type(actual[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path), )", "seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError:", "output more concise. # __unittest = 1 import traceback from", "not in\", extra) def assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises an", ") assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't match for %s\" %", "is raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format(", "actual, _number_types ), \"parameters must be numbers when tolerance is", "if missing_in_actual or missing_in_expected: if not message: message = (", "assert left > right, _assert_fail_message(message, left, right, \"<=\", extra) def", "an AssertionError if substring is a substring of subject.\"\"\" assert", "actual include: 1 - On failures, assert_eq prints an informative", "actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that two dictionaries are equal, producing", "extra) def assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if", "truncated = \"(truncated) ...\" else: truncated = \"\" start_index =", "self.extra else: template = ( \"{TYPE}: {VAL} is raised, but", "who initially wrote the code. \"\"\" __all__ = [ \"assert_is\",", "[] missing_in_expected = list(actual) for x in expected: try: missing_in_expected.remove(x)", "+ 50 truncated += seq[start_index:end_index] if end_index < len(seq): truncated", "seq, _assert_fail_message(message, obj, seq, \"is in\", extra) def assert_in_with_tolerance(obj, seq,", "assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring is", "right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand >= right_hand.\"\"\"", "not\", extra ) def assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises an", "self.expected_exception_found = exc_val return True for t in self.expected_exception_types: if", "In the context of refactors, basic asserts incorrectly shift the", "= abs(expected - actual) assert diff > tolerance, _assert_fail_message( message,", "is not in seq using assert_eq cmp.\"\"\" for i in", "dictionaries are equal, producing a custom message if they are", "%a in expected, %a in actual.\" % (expected, actual, missing_in_expected,", "for k in expected_keys: key_path = dict_path + [k] assert_is_instance(", "for x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if", "actual, extra) return \"%a %s %a\" % (expected, comparison_str, actual)", "match for %s\" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k],", "i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return", ") def assert_ne(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError", "OR CONDITIONS OF ANY KIND, either express or implied. #", "using assert_eq cmp.\"\"\" for i in seq: try: assert_eq(obj, i,", "expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected:", "the License is distributed on an \"AS IS\" BASIS, #", "truncated, \"is in\", extra) assert obj not in seq, _assert_fail_message(message,", "expected: %s\" % expected if self.extra is not None: message", "actual_keys, ) assert actual_keys <= expected_keys, \"Actual dict at %s", "message=None, extra=None): \"\"\"Raises an AssertionError if left_hand <= right_hand.\"\"\" assert", "one assert ( len(expected_exception_types) >= 1 ), \"You must specify", "0: return \"(root)\" return \"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual, number_tolerance=None,", "left, right, \">\", extra) def assert_in(obj, seq, message=None, extra=None): \"\"\"Raises", "def _dict_path_string(path): if len(path) == 0: return \"(root)\" return \"->\".join(map(ascii,", "law or agreed to in writing, software # distributed under", "\"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\",", "substring is not a substring of subject.\"\"\" assert ( (subject", "\"!=\", extra ) else: assert isinstance(tolerance, _number_types), ( \"tolerance parameter", "it faster and easier to iterate on tests. 2 -", "module to # filter out stack frames from that module", "# filter out stack frames from that module from the", "if exc_type in self.expected_exception_types: # Return True to suppress the", "\">\", extra) def assert_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError", "assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path),", "an AssertionError if obj is in iter.\"\"\" # for very", "may obtain a copy of the License at # #", "len(seq): truncated += \"... (truncated)\" assert False, _assert_fail_message(message, obj, truncated,", "the subject string does not end with suffix.\"\"\" assert (", "if substring is not a substring of subject.\"\"\" assert (", "assert expected is actual, _assert_fail_message( message, expected, actual, \"is not\",", "does not end with suffix.\"\"\" assert ( (type(subject) is str)", "import traceback from .inspection import get_full_name _number_types = (int, float,", "...\" else: truncated = \"\" start_index = 0 end_index =", "may not use this file except in compliance with the", "> right_hand.\"\"\" assert left <= right, _assert_fail_message(message, left, right, \">\",", "True to suppress the Exception if the type matches. For", "this file except in compliance with the License. # You", "> tolerance, _assert_fail_message( message, expected, actual, \"is less than %a", "# to pass but actually throw an exception different from", "start_index = 0 end_index = index + len(obj) + 50", "def assert_ne(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if", "= ( \"%a not equal to %a; missing items: %a", "not actual.\"\"\" assert expected is actual, _assert_fail_message( message, expected, actual,", "not in seq using assert_eq cmp.\"\"\" for i in seq:", "# # Licensed under the Apache License, Version 2.0 (the", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "), _assert_fail_message(message, substring, subject, \"is in\", extra) def assert_startswith(prefix, subject,", "\"\"\"Raises an AssertionError if expected is actual.\"\"\" assert expected is", "None: message = \"No exception raised, but expected: %s\" %", "seq using assert_eq cmp.\"\"\" for i in seq: try: assert_eq(obj,", "regard to their order. This takes quadratic time in the", "On failures, assert_eq prints an informative message of the actual", "missing_in_expected: if not message: message = ( \"%a not equal", "dict_path=[]): \"\"\"Asserts that two dictionaries are equal, producing a custom", "you don't specify the exception expected, it's easy to write", "an AssertionError if the objects contained in expected are not", "_assert_fail_message(message, substring, subject, \"is in\", extra) def assert_startswith(prefix, subject, message=None,", "set(actual.keys()) assert expected_keys <= actual_keys, \"Actual dict at %s is", "specified, raises an AssertionError if either - expected or actual", "assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path),", "\"%a %s %a (%s)\" % (expected, comparison_str, actual, extra) return", "\"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] # The unittest.py testing framework checks", "a custom message if they are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual,", "details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return True for", "extra=None): \"\"\"Raises an AssertionError if the subject string does not", "tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message,", "<= right_hand.\"\"\" assert left > right, _assert_fail_message(message, left, right, \"<=\",", "of\", extra ) def assert_eq(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises", "in expected are not equal to the objects contained in", "within the context raises the specified exception.\"\"\" def __init__(self, *expected_exception_types,", "_dict_path_string(path): if len(path) == 0: return \"(root)\" return \"->\".join(map(ascii, path))", "or implied. # See the License for the specific language", "in\", extra) def assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError", "extra=None): \"\"\"Raises an AssertionError if substring is not a substring", "right, \"<=\", extra) def assert_ge(left, right, message=None, extra=None): \"\"\"Raises an", "assert_gt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand <=", "for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra)", "len(path) == 0: return \"(root)\" return \"->\".join(map(ascii, path)) def assert_dict_eq(expected,", "the tolerance. \"\"\" if tolerance is None: assert expected ==", "actual_keys - expected_keys, ) for k in expected_keys: key_path =", "_assert_fail_message(message, subject, prefix, \"does not start with\", extra) def assert_endswith(suffix,", "the objects contained in expected are not equal to the", "fn() class AssertRaises(object): \"\"\"With-context that asserts that the code within", "- expected_keys, ) for k in expected_keys: key_path = dict_path", "= dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't match", "__unittest = 1 import traceback from .inspection import get_full_name _number_types", "elements in actual; don't use it for very long lists.", "actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, \"Actual dict at", "variable in a module to # filter out stack frames", "an AssertionError if substring is not a substring of subject.\"\"\"", "tests. 2 - In the context of refactors, basic asserts", "start_index = index - 50 if start_index > 0: truncated", "exc_val return True expected = \", \".join(map(get_full_name, self.expected_exception_types)) if exc_type", "actual[k], type(expected[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path), )", "assert isinstance(expected, _number_types) and isinstance( actual, _number_types ), \"parameters must", "Copyright 2016 Quora, Inc. # # Licensed under the Apache", "assert_ge(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand <", "type(expected[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path), ) assert_is_instance(", "subject, message=None, extra=None): \"\"\"Raises an AssertionError if the subject string", "expected, actual, \"!=\", extra ) else: assert isinstance(tolerance, _number_types), (", "types, \"is not an instance of\", extra ) def assert_eq(expected,", "def assert_le(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand", "isinstance(seq, str) and obj in seq and len(seq) > 200:", "self.expected_exception_found = exc_val return True expected = \", \".join(map(get_full_name, self.expected_exception_types))", "= kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def __enter__(self): return self def", "message: message = ( \"%a not equal to %a; missing", ") assert False, message def assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError", "= \"(truncated) ...\" else: truncated = \"\" start_index = 0", "write buggy tests that appear # to pass but actually", "an instance of type(s).\"\"\" assert isinstance(value, types), _assert_fail_message( message, value,", "message=None, extra=None): \"\"\"Raises an AssertionError if value is not an", "None) and (substring is not None) and (subject.find(substring) != -1)", "if expected == actual. If tolerance is specified, raises an", "raise AssertionError(message) # =================================================== # Strings # =================================================== def assert_is_substring(substring,", ">= 1 ), \"You must specify the exception type when", "assert_is(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected is", "the type matches. For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found =", "printouts and writing good test code to people refactoring code", ">= right, _assert_fail_message(message, left, right, \"<\", extra) def assert_lt(left, right,", "\"\"\"Asserts that two dictionaries are equal, producing a custom message", "if left_hand > right_hand.\"\"\" assert left <= right, _assert_fail_message(message, left,", "http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return True for t in self.expected_exception_types:", "+ len(obj) + 50 truncated += seq[start_index:end_index] if end_index <", "basic asserts incorrectly shift the burden of adding printouts and", "def assert_ge(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand", "seq, \"is in\", extra) def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None):", "an AssertionError if left_hand > right_hand.\"\"\" assert left <= right,", "exc_val, exc_tb): if exc_type in self.expected_exception_types: # Return True to", "an AssertionError if obj is not in seq using assert_eq", "_assert_fail_message(message, obj, seq, \"is not in\", extra) def assert_unordered_list_eq(expected, actual,", "extra=None): \"\"\"Raises an AssertionError if expected is not actual.\"\"\" assert", "AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context that asserts that the code", "an AssertionError if either - expected or actual isn't a", "AssertionError if expected is not actual.\"\"\" assert expected is actual,", "AssertionError if left_hand > right_hand.\"\"\" assert left <= right, _assert_fail_message(message,", "extra ) def _dict_path_string(path): if len(path) == 0: return \"(root)\"", "is actual.\"\"\" assert expected is not actual, _assert_fail_message( message, expected,", "in writing, software # distributed under the License is distributed", "expected, actual, ) diff = abs(expected - actual) assert diff", "%s\" % _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k],", "assert_le(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand >", "framework checks for this variable in a module to #", "extra) def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): \"\"\"Raises an AssertionError", "does not start with prefix.\"\"\" assert ( (type(subject) is str)", "def assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring", "if self.extra is not None: message += \" (%s)\" %", "include: 1 - On failures, assert_eq prints an informative message", "message=None, extra=None): \"\"\"Raises an AssertionError if the subject string does", "tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected == actual. If", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "+ [k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't match for %s\"", "extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), tolerance=number_tolerance, ) else:", "expected_keys, \"Actual dict at %s has extra keys: %a\" %", "\" (%s)\" % self.extra else: template = ( \"{TYPE}: {VAL}", "right_hand.\"\"\" assert left >= right, _assert_fail_message(message, left, right, \"<\", extra)", "actual, \"!=\", extra ) else: assert isinstance(tolerance, _number_types), ( \"tolerance", "obj, seq, \"is not in\", extra) def assert_unordered_list_eq(expected, actual, message=None):", "and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, \"is in\",", "assert expected == actual, _assert_fail_message( message, expected, actual, \"!=\", extra", "expected != actual, _assert_fail_message( message, expected, actual, \"==\", extra )", "str) and (subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix, \"does not start", "the License for the specific language governing permissions and #", "AssertionError(message) # =================================================== # Strings # =================================================== def assert_is_substring(substring, subject,", "(expected, comparison_str, actual) def assert_is(expected, actual, message=None, extra=None): \"\"\"Raises an", "the test output, in order to # make the output", "\"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\",", "except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "None else \"\", ) raise AssertionError(message) # =================================================== # Strings", ") def assert_eq(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "refactoring code rather than the person who initially wrote the", "len(obj) + 50 truncated += seq[start_index:end_index] if end_index < len(seq):", "if expected != actual. If tolerance is specified, raises an", "# limitations under the License. \"\"\" Module with assertion helpers.", "message, expected, actual, \"is not\", extra ) def assert_is_not(expected, actual,", "missing_in_actual) ) assert False, message def assert_raises(fn, *expected_exception_types): \"\"\"Raises an", "assert False, message def assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError if", "specified: %a, %a\" % ( expected, actual, ) diff =", "not raise one of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class", "extra=None): \"\"\"Raises an AssertionError if value is not an instance", "and writing good test code to people refactoring code rather", "_dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys <= expected_keys, \"Actual", "STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra) if self.extra is not None", "% ( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert actual_keys <=", "_assert_fail_message(message, substring, subject, \"is not in\", extra) def assert_is_not_substring(substring, subject,", "), _assert_fail_message(message, substring, subject, \"is not in\", extra) def assert_is_not_substring(substring,", "\"\"\"Raises an AssertionError if expected is not actual.\"\"\" assert expected", "assert ( len(expected_exception_types) >= 1 ), \"You must specify the", "- actual) assert diff <= tolerance, _assert_fail_message( message, expected, actual,", "checks for this variable in a module to # filter", "extra) def assert_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if", "# distributed under the License is distributed on an \"AS", "missing keys: %a\" % ( _dict_path_string(dict_path), expected_keys - actual_keys, )", "message=None, extra=None): \"\"\"Raises an AssertionError if left_hand > right_hand.\"\"\" assert", "# Unless required by applicable law or agreed to in", "see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return True for t in", "message, expected, actual, \"is less than %a away from\" %", "expected_keys - actual_keys, ) assert actual_keys <= expected_keys, \"Actual dict", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "message = ( \"%a not equal to %a; missing items:", "isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra=\"Value doesn't match for %s\"", "# =================================================== # Strings # =================================================== def assert_is_substring(substring, subject, message=None,", "1 != 2) for free, which makes it faster and", "extra ) def assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError", "\"\"\" missing_in_actual = [] missing_in_expected = list(actual) for x in", "[ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\",", "match for %s\" % _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq(", "len(expected_exception_types) >= 1 ), \"You must specify the exception type", "the Apache License, Version 2.0 (the \"License\"); # you may", "in self.expected_exception_types: # Return True to suppress the Exception if", "a module to # filter out stack frames from that", "extra=extra) return except AssertionError: pass assert False, _assert_fail_message(message, obj, seq,", "if either - expected or actual isn't a number, or", "parameter to assert_eq must be a number: %a\" % tolerance", "extra=None): \"\"\"Raises an AssertionError if left_hand <= right_hand.\"\"\" assert left", "def __exit__(self, exc_type, exc_val, exc_tb): if exc_type in self.expected_exception_types: #", "comparison_str, actual, extra) return \"%a %s %a\" % (expected, comparison_str,", "expected and actual is smaller than the tolerance. \"\"\" if", "\"\"\" Module with assertion helpers. The advantages of using a", "of using a method like assert_eq(expected, actual) instead of assert", "\"parameters must be numbers when tolerance is specified: %a, %a\"", "else: assert isinstance(tolerance, _number_types), ( \"tolerance parameter to assert_eq must", "# Strings # =================================================== def assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises", "but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val,", "= seq.find(obj) start_index = index - 50 if start_index >", "not start with\", extra) def assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises", "% tolerance ) assert isinstance(expected, _number_types) and isinstance( actual, _number_types", "Strings # =================================================== def assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises an", "exc_type is None: message = \"No exception raised, but expected:", "> right, _assert_fail_message(message, left, right, \"<=\", extra) def assert_ge(left, right,", "None: message += \" (%s)\" % self.extra else: template =", "specified exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs): # when you don't", "subject.\"\"\" assert ( (subject is not None) and (substring is", "code to people refactoring code rather than the person who", "This takes quadratic time in the umber of elements in", "if value is not an instance of type(s).\"\"\" assert isinstance(value,", "under the License is distributed on an \"AS IS\" BASIS,", "), \"parameters must be numbers when tolerance is specified: %a,", "objects contained in actual without regard to their order. This", "if the objects contained in expected are not equal to", "don't match for %s\" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]),", "expected, it's easy to write buggy tests that appear #", "def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that two dictionaries are", "AssertionError if substring is a substring of subject.\"\"\" assert (", "t in self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found = exc_val return", "assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an AssertionError if the objects contained", "0: truncated = \"(truncated) ...\" else: truncated = \"\" start_index", "comparison_str, actual) def assert_is(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError", "in seq, _assert_fail_message(message, obj, seq, \"is not in\", extra) def", "not a substring of subject.\"\"\" assert ( (subject is not", "more concise. # __unittest = 1 import traceback from .inspection", "actual, _assert_fail_message( message, expected, actual, \"is not\", extra ) def", "if expected is actual.\"\"\" assert expected is not actual, _assert_fail_message(", "and (substring is not None) and (subject.find(substring) != -1) ),", "%s\" % _dict_path_string(key_path), ) def assert_ne(expected, actual, message=None, tolerance=None, extra=None):", "elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra=\"Value doesn't match for", "AssertionError if left_hand <= right_hand.\"\"\" assert left > right, _assert_fail_message(message,", "instance of type(s).\"\"\" assert isinstance(value, types), _assert_fail_message( message, value, types,", "isinstance(tolerance, _number_types), ( \"tolerance parameter to assert_eq must be a", "limitations under the License. \"\"\" Module with assertion helpers. The", "expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context that asserts that", "\"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", #", "adding printouts and writing good test code to people refactoring", "refactors, basic asserts incorrectly shift the burden of adding printouts", "<= expected_keys, \"Actual dict at %s has extra keys: %a\"", "not None else \"\", ) raise AssertionError(message) # =================================================== #", "else: truncated = \"\" start_index = 0 end_index = index", "compared (e.g. AssertionError: 1 != 2) for free, which makes", "right, _assert_fail_message(message, left, right, \"<=\", extra) def assert_ge(left, right, message=None,", "extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), ) def assert_ne(expected,", "between expected and actual is smaller than the tolerance. \"\"\"", "None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, \"is", "to suppress the Exception if the type matches. For details,", "ANY KIND, either express or implied. # See the License", "the License. # You may obtain a copy of the", "assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises an AssertionError if value is", "rather than the person who initially wrote the code. \"\"\"", "# See the License for the specific language governing permissions", "\"\"\" __all__ = [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\",", "_number_types ), \"parameters must be numbers when tolerance is specified:", "# make the output more concise. # __unittest = 1", "else \"\", ) raise AssertionError(message) # =================================================== # Strings #", "match for %s\" % _dict_path_string(key_path), ) def assert_ne(expected, actual, message=None,", "( expected, actual, ) diff = abs(expected - actual) assert", "_assert_fail_message(message, obj, truncated, \"is in\", extra) assert obj not in", "list(actual) for x in expected: try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x)", "_assert_fail_message( message, expected, actual, \"!=\", extra ) else: assert isinstance(tolerance,", "end_index = index + len(obj) + 50 truncated += seq[start_index:end_index]", "] # The unittest.py testing framework checks for this variable", "- the difference between expected and actual is larger than", "appear # to pass but actually throw an exception different", "For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return True", "assert_lt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand >=", "template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra) if", "AssertionError if obj is not in seq.\"\"\" assert obj in", "if len(path) == 0: return \"(root)\" return \"->\".join(map(ascii, path)) def", "pass but actually throw an exception different from the expected", "difference between expected and actual is smaller than the tolerance.", "and isinstance( actual, _number_types ), \"parameters must be numbers when", "than %a away from\" % tolerance, extra ) def _dict_path_string(path):", "in\", extra) def assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError", "message, value, types, \"is not an instance of\", extra )", "actual. If tolerance is specified, raises an AssertionError if either", "to people refactoring code rather than the person who initially", "not an instance of\", extra ) def assert_eq(expected, actual, message=None,", "extra=None): \"\"\"Raises an AssertionError if left_hand > right_hand.\"\"\" assert left", "objects contained in expected are not equal to the objects", "assert_eq( expected[k], actual[k], extra=\"Value doesn't match for %s\" % _dict_path_string(key_path),", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "if tolerance is None: assert expected == actual, _assert_fail_message( message,", "left_hand >= right_hand.\"\"\" assert left < right, _assert_fail_message(message, left, right,", "writing, software # distributed under the License is distributed on", "\"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings", "assert False, _assert_fail_message(message, obj, seq, \"is not in\", extra) def", "an AssertionError if left_hand < right_hand.\"\"\" assert left >= right,", "has extra keys: %a\" % ( _dict_path_string(dict_path), actual_keys - expected_keys,", "exception different from the expected one assert ( len(expected_exception_types) >=", "like assert_eq(expected, actual) instead of assert expected == actual include:", "if left_hand <= right_hand.\"\"\" assert left > right, _assert_fail_message(message, left,", "good test code to people refactoring code rather than the", "to assert_eq must be a number: %a\" % tolerance )", "doesn't match for %s\" % _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq(", "= set(actual.keys()) assert expected_keys <= actual_keys, \"Actual dict at %s", "the difference between expected and actual is smaller than the", "If tolerance is specified, raises an AssertionError if either -", "assert expected != actual, _assert_fail_message( message, expected, actual, \"==\", extra", "def assert_is(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected", "Quora, Inc. # # Licensed under the Apache License, Version", "left < right, _assert_fail_message(message, left, right, \">=\", extra) def assert_le(left,", "\"is less than %a away from\" % tolerance, extra )", "!= 2) for free, which makes it faster and easier", "is larger than the tolerance. \"\"\" if tolerance is None:", "substring is a substring of subject.\"\"\" assert ( (subject is", "expected == actual include: 1 - On failures, assert_eq prints", "dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types):", "+= seq[start_index:end_index] if end_index < len(seq): truncated += \"... (truncated)\"", "< right, _assert_fail_message(message, left, right, \">=\", extra) def assert_le(left, right,", "in seq using assert_eq cmp.\"\"\" for i in seq: try:", "AssertionError if the objects contained in expected are not equal", "actual, comparison_str, extra): if message: return message if extra: return", "AssertionError if obj is in iter.\"\"\" # for very long", "very long strings, provide a truncated error if isinstance(seq, str)", "import get_full_name _number_types = (int, float, complex) def _assert_fail_message(message, expected,", "False, message def assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError if calling", "% expected if self.extra is not None: message += \"", "self.expected_exception_types)) if exc_type is None: message = \"No exception raised,", "assert left >= right, _assert_fail_message(message, left, right, \"<\", extra) def", "the context raises the specified exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs):", "not None) and (subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject,", "exc_type in self.expected_exception_types: # Return True to suppress the Exception", "for very long lists. \"\"\" missing_in_actual = [] missing_in_expected =", "language governing permissions and # limitations under the License. \"\"\"", "with suffix.\"\"\" assert ( (type(subject) is str) and (type(suffix) is", "isinstance( actual, _number_types ), \"parameters must be numbers when tolerance", "AssertionError if left_hand >= right_hand.\"\"\" assert left < right, _assert_fail_message(message,", "if obj is not in seq using assert_eq cmp.\"\"\" for", "suffix.\"\"\" assert ( (type(subject) is str) and (type(suffix) is str)", "error if isinstance(seq, str) and obj in seq and len(seq)", "out stack frames from that module from the test output,", ") else: assert isinstance(tolerance, _number_types), ( \"tolerance parameter to assert_eq", "\"\"\"Raises an AssertionError if expected != actual. If tolerance is", "faster and easier to iterate on tests. 2 - In", "\"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\",", "in\", extra) assert obj not in seq, _assert_fail_message(message, obj, seq,", "assert expected is not actual, _assert_fail_message( message, expected, actual, \"is\",", "!= actual. If tolerance is specified, raises an AssertionError if", "instance of\", extra ) def assert_eq(expected, actual, message=None, tolerance=None, extra=None):", "def assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if the", "of type(s).\"\"\" assert isinstance(value, types), _assert_fail_message( message, value, types, \"is", "in expected, %a in actual.\" % (expected, actual, missing_in_expected, missing_in_actual)", "assert left <= right, _assert_fail_message(message, left, right, \">\", extra) def", "is None: assert expected == actual, _assert_fail_message( message, expected, actual,", "if tolerance is None: assert expected != actual, _assert_fail_message( message,", "extra: return \"%a %s %a (%s)\" % (expected, comparison_str, actual,", "Inc. # # Licensed under the Apache License, Version 2.0", "not message: message = ( \"%a not equal to %a;", "the code. \"\"\" __all__ = [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\",", "easier to iterate on tests. 2 - In the context", "and (type(prefix) is str) and (subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix,", "the tolerance. \"\"\" if tolerance is None: assert expected !=", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with assertion helpers. The advantages of using a method like", "exc_val return True for t in self.expected_exception_types: if isinstance(exc_val, t):", "a number, or - the difference between expected and actual", "in the umber of elements in actual; don't use it", "seq and len(seq) > 200: index = seq.find(obj) start_index =", "%s %a (%s)\" % (expected, comparison_str, actual, extra) return \"%a", "\"\"\" if tolerance is None: assert expected == actual, _assert_fail_message(", "assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if the subject", "extra) def assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if", "assert obj in seq, _assert_fail_message(message, obj, seq, \"is not in\",", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "1 - On failures, assert_eq prints an informative message of", "right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand > right_hand.\"\"\"", "__exit__(self, exc_type, exc_val, exc_tb): if exc_type in self.expected_exception_types: # Return", "time in the umber of elements in actual; don't use", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "def assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected", "( (type(subject) is str) and (type(suffix) is str) and (subject.endswith(suffix))", "don't match for %s\" % _dict_path_string(key_path), ) if isinstance(actual[k], dict):", "actual.\"\"\" assert expected is not actual, _assert_fail_message( message, expected, actual,", "actual, missing_in_expected, missing_in_actual) ) assert False, message def assert_raises(fn, *expected_exception_types):", "= ( \"{TYPE}: {VAL} is raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\"", "The unittest.py testing framework checks for this variable in a", "the burden of adding printouts and writing good test code", "expected, %a in actual.\" % (expected, actual, missing_in_expected, missing_in_actual) )", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "tolerance. \"\"\" if tolerance is None: assert expected == actual,", "actual, ) diff = abs(expected - actual) assert diff <=", "def assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if the", "% ( expected, actual, ) diff = abs(expected - actual)", "class AssertRaises(object): \"\"\"With-context that asserts that the code within the", "in seq.\"\"\" assert obj in seq, _assert_fail_message(message, obj, seq, \"is", "specific language governing permissions and # limitations under the License.", "\"(truncated) ...\" else: truncated = \"\" start_index = 0 end_index", "actual is larger than the tolerance. \"\"\" if tolerance is", "extra) return \"%a %s %a\" % (expected, comparison_str, actual) def", ") def _dict_path_string(path): if len(path) == 0: return \"(root)\" return", "message=None, extra=None): \"\"\"Raises an AssertionError if obj is not in", "is str) and (subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix, \"does not", "tolerance ) assert isinstance(expected, _number_types) and isinstance( actual, _number_types ),", "_number_types): assert_eq( expected[k], actual[k], extra=\"Value doesn't match for %s\" %", "assert diff <= tolerance, _assert_fail_message( message, expected, actual, \"is more", "shift the burden of adding printouts and writing good test", "assert isinstance(value, types), _assert_fail_message( message, value, types, \"is not an", "subject, \"is not in\", extra) def assert_is_not_substring(substring, subject, message=None, extra=None):", "if they are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys =", "# you may not use this file except in compliance", "are equal, producing a custom message if they are not.\"\"\"", "expected = \", \".join(map(get_full_name, self.expected_exception_types)) if exc_type is None: message", "not None) and (substring is not None) and (subject.find(substring) !=", "obj is not in seq using assert_eq cmp.\"\"\" for i", "but expected: %s\" % expected if self.extra is not None:", "\"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\",", "= exc_val return True expected = \", \".join(map(get_full_name, self.expected_exception_types)) if", "and (type(suffix) is str) and (subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix,", "or missing_in_expected: if not message: message = ( \"%a not", "end_index < len(seq): truncated += \"... (truncated)\" assert False, _assert_fail_message(message,", "code rather than the person who initially wrote the code.", "not equal to the objects contained in actual without regard", "def _assert_fail_message(message, expected, actual, comparison_str, extra): if message: return message", ") for k in expected_keys: key_path = dict_path + [k]", "expected_keys, ) for k in expected_keys: key_path = dict_path +", "extra keys: %a\" % ( _dict_path_string(dict_path), actual_keys - expected_keys, )", "= 1 import traceback from .inspection import get_full_name _number_types =", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "of elements in actual; don't use it for very long", "an AssertionError if the subject string does not start with", "\"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] # The unittest.py testing framework", "\"%a %s %a\" % (expected, comparison_str, actual) def assert_is(expected, actual,", "is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message, substring,", "expected, actual, \"is not\", extra ) def assert_is_not(expected, actual, message=None,", "under the Apache License, Version 2.0 (the \"License\"); # you", "the person who initially wrote the code. \"\"\" __all__ =", "extra) def assert_ge(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if", "kwargs) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb):", "None: assert expected == actual, _assert_fail_message( message, expected, actual, \"!=\",", "for %s\" % _dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k],", "if exc_type is None: message = \"No exception raised, but", "message=None, extra=None): \"\"\"Raises an AssertionError if obj is in iter.\"\"\"", "provide a truncated error if isinstance(seq, str) and obj in", "is not None else \"\", ) raise AssertionError(message) # ===================================================", "AssertionError if the subject string does not end with suffix.\"\"\"", "expected_keys = set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys,", "start_index > 0: truncated = \"(truncated) ...\" else: truncated =", "None) assert_eq({}, kwargs) def __enter__(self): return self def __exit__(self, exc_type,", "(subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix, \"does not end with\", extra)", "from .inspection import get_full_name _number_types = (int, float, complex) def", "writing good test code to people refactoring code rather than", "tolerance is specified, raises an AssertionError if either - expected", "# when you don't specify the exception expected, it's easy", "def assert_unordered_list_eq(expected, actual, message=None): \"\"\"Raises an AssertionError if the objects", "an AssertionError if expected is actual.\"\"\" assert expected is not", "and obj in seq and len(seq) > 200: index =", "actual_keys <= expected_keys, \"Actual dict at %s has extra keys:", "subject, prefix, \"does not start with\", extra) def assert_endswith(suffix, subject,", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "extra=None): \"\"\"Raises an AssertionError if left_hand < right_hand.\"\"\" assert left", "self.expected_exception_types: # Return True to suppress the Exception if the", "from\" % tolerance, extra ) def assert_gt(left, right, message=None, extra=None):", "actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected is actual.\"\"\"", "type(actual[k]), extra=\"Types don't match for %s\" % _dict_path_string(key_path), ) if", "def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): \"\"\"Raises an AssertionError if", "(substring is not None) and (subject.find(substring) != -1) ), _assert_fail_message(message,", "obj in seq, _assert_fail_message(message, obj, seq, \"is not in\", extra)", "abs(expected - actual) assert diff <= tolerance, _assert_fail_message( message, expected,", "AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found = None self.extra = kwargs.pop(\"extra\",", "left_hand <= right_hand.\"\"\" assert left > right, _assert_fail_message(message, left, right,", "AssertRaises(object): \"\"\"With-context that asserts that the code within the context", "\", \".join(map(get_full_name, self.expected_exception_types)) if exc_type is None: message = \"No", "truncated = \"\" start_index = 0 end_index = index +", "when you don't specify the exception expected, it's easy to", "(truncated)\" assert False, _assert_fail_message(message, obj, truncated, \"is in\", extra) assert", "but actually throw an exception different from the expected one", "if start_index > 0: truncated = \"(truncated) ...\" else: truncated", "the umber of elements in actual; don't use it for", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "exc_tb): if exc_type in self.expected_exception_types: # Return True to suppress", "output, in order to # make the output more concise.", "message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected != actual.", "in actual without regard to their order. This takes quadratic", "\" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)),", "\"==\", extra ) else: assert isinstance(tolerance, _number_types), ( \"tolerance parameter", "AssertionError: pass assert False, _assert_fail_message(message, obj, seq, \"is not in\",", "Apache License, Version 2.0 (the \"License\"); # you may not", "_assert_fail_message(message, expected, actual, comparison_str, extra): if message: return message if", "either express or implied. # See the License for the", "= 0 end_index = index + len(obj) + 50 truncated", "extra ) def assert_eq(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an", "of subject.\"\"\" assert ( (subject is not None) and (substring", "raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message = template.format( TYPE=get_full_name(exc_type),", "be a number: %a\" % tolerance ) assert isinstance(expected, _number_types)", "% _dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra=\"Value doesn't", "is specified, raises an AssertionError if either - expected or", "it's easy to write buggy tests that appear # to", "assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected is", "_assert_fail_message( message, value, types, \"is not an instance of\", extra", "_dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't match for %s\"", "actual, ) diff = abs(expected - actual) assert diff >", "The advantages of using a method like assert_eq(expected, actual) instead", "AssertionError if left_hand < right_hand.\"\"\" assert left >= right, _assert_fail_message(message,", "50 if start_index > 0: truncated = \"(truncated) ...\" else:", "% (expected, actual, missing_in_expected, missing_in_actual) ) assert False, message def", "different from the expected one assert ( len(expected_exception_types) >= 1", "%a in actual.\" % (expected, actual, missing_in_expected, missing_in_actual) ) assert", "expected, actual, comparison_str, extra): if message: return message if extra:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "keys: %a\" % ( _dict_path_string(dict_path), expected_keys - actual_keys, ) assert", "in a module to # filter out stack frames from", "set(expected_exception_types) self.expected_exception_found = None self.extra = kwargs.pop(\"extra\", None) assert_eq({}, kwargs)", "an AssertionError if expected == actual. If tolerance is specified,", ") def assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises an AssertionError if", ") message = template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\"", "the code within the context raises the specified exception.\"\"\" def", "is not a substring of subject.\"\"\" assert ( (subject is", "(subject.find(substring) != -1) ), _assert_fail_message(message, substring, subject, \"is not in\",", "\".join(map(get_full_name, self.expected_exception_types)) if exc_type is None: message = \"No exception", "# =================================================== def assert_is_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError", "template = ( \"{TYPE}: {VAL} is raised, but expected:\" \"", "200: index = seq.find(obj) start_index = index - 50 if", "method like assert_eq(expected, actual) instead of assert expected == actual", "actual) assert diff > tolerance, _assert_fail_message( message, expected, actual, \"is", "% (expected, comparison_str, actual, extra) return \"%a %s %a\" %", "in\", extra) def assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): \"\"\"Raises an", "extra=None): \"\"\"Raises an AssertionError if expected != actual. If tolerance", "tolerance. \"\"\" if tolerance is None: assert expected != actual,", "use it for very long lists. \"\"\" missing_in_actual = []", "\"is in\", extra) assert obj not in seq, _assert_fail_message(message, obj,", "in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except", "% self.extra) if self.extra is not None else \"\", )", "License. \"\"\" Module with assertion helpers. The advantages of using", "missing_in_actual = [] missing_in_expected = list(actual) for x in expected:", "which makes it faster and easier to iterate on tests.", "equal, producing a custom message if they are not.\"\"\" assert_is_instance(expected,", "message=None, extra=None): \"\"\"Raises an AssertionError if left_hand < right_hand.\"\"\" assert", "assert_eq(obj, i, tolerance=tolerance, message=message, extra=extra) return except AssertionError: pass assert", "the output more concise. # __unittest = 1 import traceback", "be numbers when tolerance is specified: %a, %a\" % (", "left > right, _assert_fail_message(message, left, right, \"<=\", extra) def assert_ge(left,", "message = \"No exception raised, but expected: %s\" % expected", "\"\"\"With-context that asserts that the code within the context raises", "that two dictionaries are equal, producing a custom message if", "use this file except in compliance with the License. #", "extra=None): \"\"\"Raises an AssertionError if expected is actual.\"\"\" assert expected", "substring of subject.\"\"\" assert ( (subject is not None) and", "expected[k], actual[k], extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), )", "left_hand < right_hand.\"\"\" assert left >= right, _assert_fail_message(message, left, right,", "(subject.find(substring) == -1) ), _assert_fail_message(message, substring, subject, \"is in\", extra)", "to iterate on tests. 2 - In the context of", "the exception type when using AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found", "50 truncated += seq[start_index:end_index] if end_index < len(seq): truncated +=", "def assert_eq(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if", "free, which makes it faster and easier to iterate on", "\"\"\"Raises an AssertionError if left_hand <= right_hand.\"\"\" assert left >", "is actual, _assert_fail_message( message, expected, actual, \"is not\", extra )", "with AssertRaises(*expected_exception_types): fn() class AssertRaises(object): \"\"\"With-context that asserts that the", "assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that two dictionaries are equal,", "message += \" (%s)\" % self.extra else: template = (", "in order to # make the output more concise. #", "def assert_gt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand", "\"\"\"Raises an AssertionError if left_hand > right_hand.\"\"\" assert left <=", "this variable in a module to # filter out stack", "seq.\"\"\" assert obj in seq, _assert_fail_message(message, obj, seq, \"is not", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "_dict_path_string(dict_path), actual_keys - expected_keys, ) for k in expected_keys: key_path", "actual; don't use it for very long lists. \"\"\" missing_in_actual", ") raise AssertionError(message) # =================================================== # Strings # =================================================== def", "index = seq.find(obj) start_index = index - 50 if start_index", "assert_ne(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected", "\"You must specify the exception type when using AssertRaises\" self.expected_exception_types", "Exception if the type matches. For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html", "> 200: index = seq.find(obj) start_index = index - 50", "message, expected, actual, \"!=\", extra ) else: assert isinstance(tolerance, _number_types),", "raise one of the expected_exception-types.\"\"\" with AssertRaises(*expected_exception_types): fn() class AssertRaises(object):", "must specify the exception type when using AssertRaises\" self.expected_exception_types =", "to the objects contained in actual without regard to their", "from that module from the test output, in order to", "TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra) if self.extra", "the subject string does not start with prefix.\"\"\" assert (", "contained in actual without regard to their order. This takes", "_dict_path_string(key_path), tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra=\"Value doesn't match", "subject, \"is in\", extra) def assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises", "left >= right, _assert_fail_message(message, left, right, \"<\", extra) def assert_lt(left,", ">= right_hand.\"\"\" assert left < right, _assert_fail_message(message, left, right, \">=\",", "away from\" % tolerance, extra ) def _dict_path_string(path): if len(path)", "number: %a\" % tolerance ) assert isinstance(expected, _number_types) and isinstance(", "%s\" % expected if self.extra is not None: message +=", "truncated += \"... (truncated)\" assert False, _assert_fail_message(message, obj, truncated, \"is", "index - 50 if start_index > 0: truncated = \"(truncated)", "\"is not\", extra ) def assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises", "test output, in order to # make the output more", "None self.extra = kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def __enter__(self): return", "equal to the objects contained in actual without regard to", "raises an AssertionError if either - expected or actual isn't", "__init__(self, *expected_exception_types, **kwargs): # when you don't specify the exception", "to pass but actually throw an exception different from the", "expected is not actual, _assert_fail_message( message, expected, actual, \"is\", extra", "= \", \".join(map(get_full_name, self.expected_exception_types)) if exc_type is None: message =", "( (type(subject) is str) and (type(prefix) is str) and (subject.startswith(prefix))", "str) and obj in seq and len(seq) > 200: index", "(substring is not None) and (subject.find(substring) == -1) ), _assert_fail_message(message,", "asserts that the code within the context raises the specified", "extra) assert obj not in seq, _assert_fail_message(message, obj, seq, \"is", "\"\"\"Raises an AssertionError if left_hand >= right_hand.\"\"\" assert left <", "with the License. # You may obtain a copy of", "right, _assert_fail_message(message, left, right, \">=\", extra) def assert_le(left, right, message=None,", "are not equal to the objects contained in actual without", ".inspection import get_full_name _number_types = (int, float, complex) def _assert_fail_message(message,", "\"\", ) raise AssertionError(message) # =================================================== # Strings # ===================================================", "at %s has extra keys: %a\" % ( _dict_path_string(dict_path), actual_keys", ") def assert_is_not(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if", "obj in seq and len(seq) > 200: index = seq.find(obj)", "pass assert False, _assert_fail_message(message, obj, seq, \"is not in\", extra)", "helpers. The advantages of using a method like assert_eq(expected, actual)", "easy to write buggy tests that appear # to pass", "iterate on tests. 2 - In the context of refactors,", "an AssertionError if expected is not actual.\"\"\" assert expected is", "not in\", extra) def assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises an", "exception raised, but expected: %s\" % expected if self.extra is", "missing_in_expected = list(actual) for x in expected: try: missing_in_expected.remove(x) except", "expected_keys: key_path = dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types", "number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra=\"Value", "\"\"\"Raises an AssertionError if obj is in iter.\"\"\" # for", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "doesn't match for %s\" % _dict_path_string(key_path), ) def assert_ne(expected, actual,", "long strings, provide a truncated error if isinstance(seq, str) and", "def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if", "\"<\", extra) def assert_lt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError", "diff = abs(expected - actual) assert diff > tolerance, _assert_fail_message(", "extra ) def assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises an AssertionError", "missing_in_actual or missing_in_expected: if not message: message = ( \"%a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "stack frames from that module from the test output, in", "\"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\", \"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\",", "= \"No exception raised, but expected: %s\" % expected if", "assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises an AssertionError if the subject", "the specified exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs): # when you", "= template.format( TYPE=get_full_name(exc_type), VAL=exc_val, EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra)", "not None: message += \" (%s)\" % self.extra else: template", "order. This takes quadratic time in the umber of elements", "to their order. This takes quadratic time in the umber", "CONDITIONS OF ANY KIND, either express or implied. # See", "=================================================== # Strings # =================================================== def assert_is_substring(substring, subject, message=None, extra=None):", "is a substring of subject.\"\"\" assert ( (subject is not", "actual) assert diff <= tolerance, _assert_fail_message( message, expected, actual, \"is", "of the actual values compared (e.g. AssertionError: 1 != 2)", "in\", extra) def assert_startswith(prefix, subject, message=None, extra=None): \"\"\"Raises an AssertionError", "extra=None): \"\"\"Raises an AssertionError if expected == actual. If tolerance", "if the subject string does not start with prefix.\"\"\" assert", "don't specify the exception expected, it's easy to write buggy", "they are not.\"\"\" assert_is_instance(expected, dict) assert_is_instance(actual, dict) expected_keys = set(expected.keys())", "message=None, extra=None): \"\"\"Raises an AssertionError if left_hand >= right_hand.\"\"\" assert", "{VAL} is raised, but expected:\" \" {EXPECTED}{EXTRA_STR}\\n\\n{STACK}\" ) message =", "index + len(obj) + 50 truncated += seq[start_index:end_index] if end_index", "!= -1) ), _assert_fail_message(message, substring, subject, \"is not in\", extra)", "(type(subject) is str) and (type(prefix) is str) and (subject.startswith(prefix)) ),", "seq, _assert_fail_message(message, obj, seq, \"is not in\", extra) def assert_not_in(obj,", "self.extra is not None else \"\", ) raise AssertionError(message) #", "not None) and (substring is not None) and (subject.find(substring) ==", "from the test output, in order to # make the", "= abs(expected - actual) assert diff <= tolerance, _assert_fail_message( message,", "- On failures, assert_eq prints an informative message of the", "the actual values compared (e.g. AssertionError: 1 != 2) for", "\"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] #", "from the expected one assert ( len(expected_exception_types) >= 1 ),", "message of the actual values compared (e.g. AssertionError: 1 !=", "\"does not start with\", extra) def assert_endswith(suffix, subject, message=None, extra=None):", "assert_eq({}, kwargs) def __enter__(self): return self def __exit__(self, exc_type, exc_val,", "numbers when tolerance is specified: %a, %a\" % ( expected,", "(type(suffix) is str) and (subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix, \"does", "False, _assert_fail_message(message, obj, seq, \"is not in\", extra) def assert_unordered_list_eq(expected,", "ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not message: message", "tolerance, extra ) def assert_gt(left, right, message=None, extra=None): \"\"\"Raises an", "assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if substring is", "_assert_fail_message(message, obj, seq, \"is not in\", extra) def assert_not_in(obj, seq,", "return True expected = \", \".join(map(get_full_name, self.expected_exception_types)) if exc_type is", "actual, \"==\", extra ) else: assert isinstance(tolerance, _number_types), ( \"tolerance", "value, types, \"is not an instance of\", extra ) def", "or - the difference between expected and actual is larger", "extra=None): \"\"\"Raises an AssertionError if obj is not in seq.\"\"\"", "\"\"\"Raises an AssertionError if substring is not a substring of", "seq, tolerance, message=None, extra=None): \"\"\"Raises an AssertionError if obj is", "self.extra is not None: message += \" (%s)\" % self.extra", "cmp.\"\"\" for i in seq: try: assert_eq(obj, i, tolerance=tolerance, message=message,", "failures, assert_eq prints an informative message of the actual values", "assert expected == actual include: 1 - On failures, assert_eq", "two dictionaries are equal, producing a custom message if they", "code. \"\"\" __all__ = [ \"assert_is\", \"assert_is_not\", \"assert_is_instance\", \"assert_eq\", \"assert_dict_eq\",", "self.extra) if self.extra is not None else \"\", ) raise", "an AssertionError if value is not an instance of type(s).\"\"\"", "in iter.\"\"\" # for very long strings, provide a truncated", "extra) def assert_is_not_substring(substring, subject, message=None, extra=None): \"\"\"Raises an AssertionError if", "seq.find(obj) start_index = index - 50 if start_index > 0:", "an AssertionError if expected != actual. If tolerance is specified,", "\"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\",", ") if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, )", "exc_type, exc_val, exc_tb): if exc_type in self.expected_exception_types: # Return True", "governing permissions and # limitations under the License. \"\"\" Module", "2016 Quora, Inc. # # Licensed under the Apache License,", "\"\"\" if tolerance is None: assert expected != actual, _assert_fail_message(", "kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def __enter__(self): return self def __exit__(self,", "<= right, _assert_fail_message(message, left, right, \">\", extra) def assert_in(obj, seq,", "producing a custom message if they are not.\"\"\" assert_is_instance(expected, dict)", "a number: %a\" % tolerance ) assert isinstance(expected, _number_types) and", "is None: assert expected != actual, _assert_fail_message( message, expected, actual,", "not an instance of type(s).\"\"\" assert isinstance(value, types), _assert_fail_message( message,", ") elif isinstance(actual[k], _number_types): assert_eq( expected[k], actual[k], extra=\"Value doesn't match", "len(seq) > 200: index = seq.find(obj) start_index = index -", "not in seq, _assert_fail_message(message, obj, seq, \"is in\", extra) def", "assert actual_keys <= expected_keys, \"Actual dict at %s has extra", "from\" % tolerance, extra ) def _dict_path_string(path): if len(path) ==", "% ( _dict_path_string(dict_path), actual_keys - expected_keys, ) for k in", "return message if extra: return \"%a %s %a (%s)\" %", "(%s)\" % self.extra) if self.extra is not None else \"\",", "message=None, extra=None): \"\"\"Raises an AssertionError if substring is not a", "expected_keys <= actual_keys, \"Actual dict at %s is missing keys:", "it for very long lists. \"\"\" missing_in_actual = [] missing_in_expected", "actual_keys, \"Actual dict at %s is missing keys: %a\" %", "for %s\" % _dict_path_string(key_path), ) def assert_ne(expected, actual, message=None, tolerance=None,", "actual) def assert_is(expected, actual, message=None, extra=None): \"\"\"Raises an AssertionError if", "actual, message=None, extra=None): \"\"\"Raises an AssertionError if expected is not", "_dict_path_string(key_path), ) def assert_ne(expected, actual, message=None, tolerance=None, extra=None): \"\"\"Raises an", "with\", extra) def assert_endswith(suffix, subject, message=None, extra=None): \"\"\"Raises an AssertionError", "types), _assert_fail_message( message, value, types, \"is not an instance of\",", "right_hand.\"\"\" assert left < right, _assert_fail_message(message, left, right, \">=\", extra)", "is not an instance of type(s).\"\"\" assert isinstance(value, types), _assert_fail_message(", "isinstance(expected, _number_types) and isinstance( actual, _number_types ), \"parameters must be", "than the tolerance. \"\"\" if tolerance is None: assert expected", "str) and (subject.endswith(suffix)) ), _assert_fail_message(message, subject, suffix, \"does not end", "if calling fn does not raise one of the expected_exception-types.\"\"\"", "missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if not", "%a\" % (expected, comparison_str, actual) def assert_is(expected, actual, message=None, extra=None):", "AssertionError if expected == actual. If tolerance is specified, raises", "assert_raises(fn, *expected_exception_types): \"\"\"Raises an AssertionError if calling fn does not", "None) and (substring is not None) and (subject.find(substring) == -1)", "expected are not equal to the objects contained in actual", "right, message=None, extra=None): \"\"\"Raises an AssertionError if left_hand < right_hand.\"\"\"", "expected one assert ( len(expected_exception_types) >= 1 ), \"You must", "message if extra: return \"%a %s %a (%s)\" % (expected,", "the context of refactors, basic asserts incorrectly shift the burden", "obj is in iter.\"\"\" # for very long strings, provide", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "\"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] # The", "exception type when using AssertRaises\" self.expected_exception_types = set(expected_exception_types) self.expected_exception_found =", "right, _assert_fail_message(message, left, right, \"<\", extra) def assert_lt(left, right, message=None,", "= [] missing_in_expected = list(actual) for x in expected: try:", "not actual, _assert_fail_message( message, expected, actual, \"is\", extra ) def", "code within the context raises the specified exception.\"\"\" def __init__(self,", "contained in expected are not equal to the objects contained", "expected != actual. If tolerance is specified, raises an AssertionError", "traceback from .inspection import get_full_name _number_types = (int, float, complex)", "tolerance is None: assert expected != actual, _assert_fail_message( message, expected,", "if self.extra is not None else \"\", ) raise AssertionError(message)", "_dict_path_string(key_path), ) if isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path,", "actual is smaller than the tolerance. \"\"\" if tolerance is", "\"is not an instance of\", extra ) def assert_eq(expected, actual,", "extra) def assert_le(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if", "\">=\", extra) def assert_le(left, right, message=None, extra=None): \"\"\"Raises an AssertionError", "(%s)\" % self.extra else: template = ( \"{TYPE}: {VAL} is", "frames from that module from the test output, in order", "if message: return message if extra: return \"%a %s %a", "right, \">=\", extra) def assert_le(left, right, message=None, extra=None): \"\"\"Raises an", "message: return message if extra: return \"%a %s %a (%s)\"", "EXPECTED=expected, STACK=\"\".join(traceback.format_tb(exc_tb)), EXTRA_STR=(\" (%s)\" % self.extra) if self.extra is not", "Version 2.0 (the \"License\"); # you may not use this", "return True for t in self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found", "), _assert_fail_message(message, subject, prefix, \"does not start with\", extra) def", "a method like assert_eq(expected, actual) instead of assert expected ==", "smaller than the tolerance. \"\"\" if tolerance is None: assert", "isinstance(actual[k], dict): assert_dict_eq( expected[k], actual[k], number_tolerance=number_tolerance, dict_path=key_path, ) elif isinstance(actual[k],", "prints an informative message of the actual values compared (e.g.", "\"No exception raised, but expected: %s\" % expected if self.extra", "%s is missing keys: %a\" % ( _dict_path_string(dict_path), expected_keys -", "2 - In the context of refactors, basic asserts incorrectly", "\"assert_ne\", \"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\",", "by applicable law or agreed to in writing, software #", "is not in seq.\"\"\" assert obj in seq, _assert_fail_message(message, obj,", "(expected, comparison_str, actual, extra) return \"%a %s %a\" % (expected,", "= set(expected_exception_types) self.expected_exception_found = None self.extra = kwargs.pop(\"extra\", None) assert_eq({},", "assertion helpers. The advantages of using a method like assert_eq(expected,", "match for %s\" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra=\"Types", "type matches. For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val", "if left_hand >= right_hand.\"\"\" assert left < right, _assert_fail_message(message, left,", "expected == actual. If tolerance is specified, raises an AssertionError", "actual.\"\"\" assert expected is actual, _assert_fail_message( message, expected, actual, \"is", "except AssertionError: pass assert False, _assert_fail_message(message, obj, seq, \"is not", "== actual, _assert_fail_message( message, expected, actual, \"!=\", extra ) else:", "assert_in_with_tolerance(obj, seq, tolerance, message=None, extra=None): \"\"\"Raises an AssertionError if obj", "exception expected, it's easy to write buggy tests that appear", "substring, subject, \"is in\", extra) def assert_startswith(prefix, subject, message=None, extra=None):", "actual isn't a number, or - the difference between expected", "an AssertionError if calling fn does not raise one of", "unittest.py testing framework checks for this variable in a module", "Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ] # The unittest.py testing", "not end with suffix.\"\"\" assert ( (type(subject) is str) and", "value is not an instance of type(s).\"\"\" assert isinstance(value, types),", "def assert_is_instance(value, types, message=None, extra=None): \"\"\"Raises an AssertionError if value", "applicable law or agreed to in writing, software # distributed", "for %s\" % _dict_path_string(key_path), ) assert_is_instance( expected[k], type(actual[k]), extra=\"Types don't", "substring, subject, \"is not in\", extra) def assert_is_not_substring(substring, subject, message=None,", "(%s)\" % (expected, comparison_str, actual, extra) return \"%a %s %a\"", "specify the exception expected, it's easy to write buggy tests", "actual, _assert_fail_message( message, expected, actual, \"!=\", extra ) else: assert", "their order. This takes quadratic time in the umber of", "key_path = dict_path + [k] assert_is_instance( actual[k], type(expected[k]), extra=\"Types don't", "and # limitations under the License. \"\"\" Module with assertion", "is str) and (subject.startswith(prefix)) ), _assert_fail_message(message, subject, prefix, \"does not", "extra=None): \"\"\"Raises an AssertionError if obj is in iter.\"\"\" #", "right, _assert_fail_message(message, left, right, \">\", extra) def assert_in(obj, seq, message=None,", "actual[k], extra=\"Value doesn't match for %s\" % _dict_path_string(key_path), ) def", "str) and (type(suffix) is str) and (subject.endswith(suffix)) ), _assert_fail_message(message, subject,", "try: missing_in_expected.remove(x) except ValueError: missing_in_actual.append(x) if missing_in_actual or missing_in_expected: if", "_assert_fail_message( message, expected, actual, \"is more than %a away from\"", "\"assert_gt\", \"assert_ge\", \"assert_lt\", \"assert_le\", \"assert_in\", \"assert_not_in\", \"assert_in_with_tolerance\", \"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\",", "than %a away from\" % tolerance, extra ) def assert_gt(left,", "module from the test output, in order to # make", "\"is not in\", extra) def assert_not_in(obj, seq, message=None, extra=None): \"\"\"Raises", "get_full_name _number_types = (int, float, complex) def _assert_fail_message(message, expected, actual,", "tolerance, message=None, extra=None): \"\"\"Raises an AssertionError if obj is not", "# You may obtain a copy of the License at", "the License. \"\"\" Module with assertion helpers. The advantages of", "matches. For details, # see: http://docs.python.org/release/2.5.2/lib/typecontextmanager.html self.expected_exception_found = exc_val return", "if isinstance(exc_val, t): self.expected_exception_found = exc_val return True expected =", "and (substring is not None) and (subject.find(substring) == -1) ),", "raised, but expected: %s\" % expected if self.extra is not", "def assert_in(obj, seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj", "( len(expected_exception_types) >= 1 ), \"You must specify the exception", "truncated += seq[start_index:end_index] if end_index < len(seq): truncated += \"...", "AssertionError if either - expected or actual isn't a number,", "\"tolerance parameter to assert_eq must be a number: %a\" %", "%s %a\" % (expected, comparison_str, actual) def assert_is(expected, actual, message=None,", "extra=None): \"\"\"Raises an AssertionError if left_hand >= right_hand.\"\"\" assert left", "an AssertionError if obj is not in seq.\"\"\" assert obj", "if not message: message = ( \"%a not equal to", "to %a; missing items: %a in expected, %a in actual.\"", "an AssertionError if the subject string does not end with", "obj is not in seq.\"\"\" assert obj in seq, _assert_fail_message(message,", "%a\" % ( _dict_path_string(dict_path), actual_keys - expected_keys, ) for k", "when tolerance is specified: %a, %a\" % ( expected, actual,", "seq, message=None, extra=None): \"\"\"Raises an AssertionError if obj is not", "%a away from\" % tolerance, extra ) def assert_gt(left, right,", "extra) def assert_lt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if", "\"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that two", "buggy tests that appear # to pass but actually throw", "return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type in", "\"assert_startswith\", \"assert_endswith\", ] # The unittest.py testing framework checks for", "self.extra = kwargs.pop(\"extra\", None) assert_eq({}, kwargs) def __enter__(self): return self", "return \"->\".join(map(ascii, path)) def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that", "is smaller than the tolerance. \"\"\" if tolerance is None:", "\"License\"); # you may not use this file except in", "if the subject string does not end with suffix.\"\"\" assert", "calling fn does not raise one of the expected_exception-types.\"\"\" with", "% tolerance, extra ) def _dict_path_string(path): if len(path) == 0:", "that module from the test output, in order to #", "str) and (type(prefix) is str) and (subject.startswith(prefix)) ), _assert_fail_message(message, subject,", "> 0: truncated = \"(truncated) ...\" else: truncated = \"\"", "context raises the specified exception.\"\"\" def __init__(self, *expected_exception_types, **kwargs): #", ") def assert_gt(left, right, message=None, extra=None): \"\"\"Raises an AssertionError if", "seq[start_index:end_index] if end_index < len(seq): truncated += \"... (truncated)\" assert", "= set(expected.keys()) actual_keys = set(actual.keys()) assert expected_keys <= actual_keys, \"Actual", "testing framework checks for this variable in a module to", "actual, message=None, tolerance=None, extra=None): \"\"\"Raises an AssertionError if expected !=", "a substring of subject.\"\"\" assert ( (subject is not None)", "isn't a number, or - the difference between expected and", "is in iter.\"\"\" # for very long strings, provide a", "\"assert_unordered_list_eq\", \"assert_raises\", \"AssertRaises\", # Strings \"assert_is_substring\", \"assert_is_not_substring\", \"assert_startswith\", \"assert_endswith\", ]", "path)) def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]): \"\"\"Asserts that two dictionaries", "in actual.\" % (expected, actual, missing_in_expected, missing_in_actual) ) assert False,", "self.expected_exception_types: if isinstance(exc_val, t): self.expected_exception_found = exc_val return True expected", "tolerance=number_tolerance, ) else: assert_eq( expected[k], actual[k], extra=\"Value doesn't match for", "self.expected_exception_types = set(expected_exception_types) self.expected_exception_found = None self.extra = kwargs.pop(\"extra\", None)" ]
[ "expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous,", "'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous', 'legacy_expose_api_raw',", "legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__ = ('FormBuilder', 'do_not_cache', 'error',", "\"\"\" from .framework import url_for from .framework.base import httpexceptions from", "Galaxy web application framework \"\"\" from .framework import url_for from", "<gh_stars>1-10 \"\"\" The Galaxy web application framework \"\"\" from .framework", "httpexceptions from .framework.decorators import ( do_not_cache, error, expose, expose_api, expose_api_anonymous,", "expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous,", "require_login, ) __all__ = ('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous',", "import httpexceptions from .framework.decorators import ( do_not_cache, error, expose, expose_api,", "json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__ =", "'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form',", "'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous',", ".framework.decorators import ( do_not_cache, error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw,", "'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous', 'legacy_expose_api_raw', 'legacy_expose_api_raw_anonymous', 'require_admin', 'require_login', 'url_for')", "The Galaxy web application framework \"\"\" from .framework import url_for", "expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty,", "framework \"\"\" from .framework import url_for from .framework.base import httpexceptions", "'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous', 'legacy_expose_api_raw', 'legacy_expose_api_raw_anonymous', 'require_admin',", "json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__", "'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous', 'legacy_expose_api_raw', 'legacy_expose_api_raw_anonymous',", "import url_for from .framework.base import httpexceptions from .framework.decorators import (", "expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin,", "format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, )", "error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json,", "'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty',", "'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api',", "application framework \"\"\" from .framework import url_for from .framework.base import", "do_not_cache, error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json,", "legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__ = ('FormBuilder', 'do_not_cache',", "__all__ = ('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw',", "legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__ = ('FormBuilder',", "'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json',", "\"\"\" The Galaxy web application framework \"\"\" from .framework import", "legacy_expose_api_raw_anonymous, require_admin, require_login, ) __all__ = ('FormBuilder', 'do_not_cache', 'error', 'expose',", "'format_return_as_json', 'httpexceptions', 'json', 'json_pretty', 'legacy_expose_api', 'legacy_expose_api_anonymous', 'legacy_expose_api_raw', 'legacy_expose_api_raw_anonymous', 'require_admin', 'require_login',", "expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw,", "expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api, legacy_expose_api_anonymous, legacy_expose_api_raw, legacy_expose_api_raw_anonymous, require_admin, require_login,", "from .framework.base import httpexceptions from .framework.decorators import ( do_not_cache, error,", "url_for from .framework.base import httpexceptions from .framework.decorators import ( do_not_cache,", "web application framework \"\"\" from .framework import url_for from .framework.base", "= ('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous',", "from .framework.decorators import ( do_not_cache, error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless,", "require_admin, require_login, ) __all__ = ('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api',", "( do_not_cache, error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless,", ") __all__ = ('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless',", "import ( do_not_cache, error, expose, expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous,", "expose_api, expose_api_anonymous, expose_api_anonymous_and_sessionless, expose_api_raw, expose_api_raw_anonymous, expose_api_raw_anonymous_and_sessionless, format_return_as_json, json, json_pretty, legacy_expose_api,", "('FormBuilder', 'do_not_cache', 'error', 'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless',", ".framework.base import httpexceptions from .framework.decorators import ( do_not_cache, error, expose,", "'expose', 'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions',", ".framework import url_for from .framework.base import httpexceptions from .framework.decorators import", "'expose_api', 'expose_api_anonymous', 'expose_api_anonymous_and_sessionless', 'expose_api_raw', 'expose_api_raw_anonymous', 'expose_api_raw_anonymous_and_sessionless', 'form', 'format_return_as_json', 'httpexceptions', 'json',", "from .framework import url_for from .framework.base import httpexceptions from .framework.decorators" ]
[ "None) -> Target: if address is None: address = Address(\"\",", "= Address(\"\", target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\") exit_code, stderr =", "address = Address(\"\", target_name=\"tests\") return MockTarget({}, address) def run_typecheck_rule( *,", "run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], )", "== dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed. -", "= [config.address for config in self.field_sets] return CheckResults( [ CheckResult(", "CheckResult, CheckResults, check from pants.core.util_rules.distdir import DistDir from pants.engine.addresses import", "rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet(", "test_streaming_output_partitions() -> None: results = CheckResults( [ CheckResult(21, \"\", \"\",", "\"typechecker skipped.\" def test_streaming_output_success() -> None: results = CheckResults([CheckResult(0, \"stdout\",", "return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses:", "CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR assert results.message()", "= None) -> Target: if address is None: address =", "check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[", "textwrap import dedent from typing import ClassVar, Iterable, List, Optional,", "RuleRunner() result: Check = run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False),", "ClassVar, Iterable, List, Optional, Tuple, Type from pants.core.goals.check import Check,", "int: if any(address.target_name == \"bad\" for address in addresses): return", "Address(\"\", target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\") exit_code, stderr = run_typecheck_rule(", "(console, stdio_reader): rule_runner = RuleRunner() result: Check = run_rule_with_mocks( check,", "= \"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return 1", "run_rule_with_mocks from pants.util.logging import LogLevel class MockTarget(Target): alias = \"mock_target\"", "pants.core.goals.check import Check, CheckRequest, CheckResult, CheckResults, check from pants.core.util_rules.distdir import", "== \"typechecker skipped.\" def test_streaming_output_success() -> None: results = CheckResults([CheckResult(0,", "import DistDir from pants.engine.addresses import Address from pants.engine.fs import Workspace", "request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], ) assert", ") def test_streaming_output_failure() -> None: results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")],", "the Apache License, Version 2.0 (see LICENSE). from abc import", "return 0 class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod def exit_code(_:", "dedent( \"\"\"\\ typechecker succeeded. stdout stderr \"\"\" ) def test_streaming_output_failure()", "partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert results.level()", "= (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name = \"InvalidChecker\"", "int: return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod def", "mock=lambda field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership, ) assert not stdio_reader.get_stdout()", "addresses = [config.address for config in self.field_sets] return CheckResults( [", "-> int: if any(address.target_name == \"bad\" for address in addresses):", "return 127 return 0 class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) ->", "-> CheckResults: addresses = [config.address for config in self.field_sets] return", "MockTarget(Target): alias = \"mock_target\" core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields", "stderr == dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed.", "def run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets: List[Target] ) -> Tuple[int,", "targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code == FailingRequest.exit_code([bad_address]) assert stderr ==", "Workspace from pants.engine.target import FieldSet, MultipleSourcesField, Target, Targets from pants.engine.unions", "-> None: results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level()", "target_name=\"tests\") return MockTarget({}, address) def run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets:", "LogLevel.ERROR assert results.message() == dedent( \"\"\"\\ typechecker failed (exit code", "def exit_code(_) -> int: return 0 @property def check_results(self) ->", "pathlib import Path from textwrap import dedent from typing import", "results.level() == LogLevel.ERROR assert results.message() == dedent( \"\"\"\\ typechecker failed", "\"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR assert results.message() == dedent(", "\"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return -1 def", "class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type =", "checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class", "exit_code(_) -> int: return 0 @property def check_results(self) -> CheckResults:", "Path from textwrap import dedent from typing import ClassVar, Iterable,", "under the Apache License, Version 2.0 (see LICENSE). from abc", "results.level() == LogLevel.INFO assert results.message() == dedent( \"\"\"\\ typechecker succeeded.", "dedent from typing import ClassVar, Iterable, List, Optional, Tuple, Type", "from pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner import MockGet, RuleRunner, mock_console,", "make_target(bad_address)], ) assert exit_code == FailingRequest.exit_code([bad_address]) assert stderr == dedent(", "FieldSet, MultipleSourcesField, Target, Targets from pants.engine.unions import UnionMembership from pants.testutil.option_util", "assert stderr == \"\" def test_summary() -> None: good_address =", "import Check, CheckRequest, CheckResult, CheckResults, check from pants.core.util_rules.distdir import DistDir", "import Workspace from pants.engine.target import FieldSet, MultipleSourcesField, Target, Targets from", "assert stderr == dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker", "return MockTarget({}, address) def run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets: List[Target]", "skipped.\" def test_streaming_output_success() -> None: results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")],", "def test_streaming_output_success() -> None: results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\")", ") class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address])", "class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet", "0 assert stderr == \"\" def test_summary() -> None: good_address", "[ CheckResult( self.exit_code(addresses), \"\", \"\", ) ], checker_name=self.checker_name, ) class", "project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License,", "results.level() == LogLevel.DEBUG assert results.message() == \"typechecker skipped.\" def test_streaming_output_success()", "Licensed under the Apache License, Version 2.0 (see LICENSE). from", "- ghc8.1: Partition #2 - ghc9.2: stdout stderr \"\"\" )", "\"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert results.level() == LogLevel.ERROR", "MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership, )", "@staticmethod def exit_code(_: Iterable[Address]) -> int: return 0 class FailingRequest(MockCheckRequest):", "test_summary() -> None: good_address = Address(\"\", target_name=\"good\") bad_address = Address(\"\",", "CheckResults( [ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"),", "results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.INFO", "-> None: results = CheckResults([], checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG", "MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod def exit_code(_: Iterable[Address]) -> int:", "-> int: pass @property def check_results(self) -> CheckResults: addresses =", "UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner = RuleRunner()", "List[Target] ) -> Tuple[int, str]: union_membership = UnionMembership({CheckRequest: request_types}) with", "\"\", ) ], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\"", "check_results(self) -> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class", "\"\" def test_summary() -> None: good_address = Address(\"\", target_name=\"good\") bad_address", "DistDir from pants.engine.addresses import Address from pants.engine.fs import Workspace from", "field_set_collection.check_results, ), ], union_membership=union_membership, ) assert not stdio_reader.get_stdout() return result.exit_code,", "Address(\"\", target_name=\"bad\") exit_code, stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest,", "(InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod", "return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() -> None: exit_code, stderr =", "= CheckResults( [ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\",", "Check = run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")),", "], checker_name=\"typechecker\", ) assert results.level() == LogLevel.ERROR assert results.message() ==", "RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging import LogLevel class MockTarget(Target): alias", "checker_name=\"typechecker\") assert results.level() == LogLevel.INFO assert results.message() == dedent( \"\"\"\\", "run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code == 0 assert stderr == \"\"", "-> int: return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod", "request_types: List[Type[CheckRequest]], targets: List[Target] ) -> Tuple[int, str]: union_membership =", ") -> Tuple[int, str]: union_membership = UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper())", "FailingRequest.exit_code([bad_address]) assert stderr == dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂", "core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest,", "InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name", "CheckResults, check from pants.core.util_rules.distdir import DistDir from pants.engine.addresses import Address", "\"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.INFO assert results.message() == dedent(", "\"mock_target\" core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class", "CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.INFO assert results.message()", "def test_streaming_output_failure() -> None: results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\")", "CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert results.level() ==", "Targets from pants.engine.unions import UnionMembership from pants.testutil.option_util import create_options_bootstrapper from", "exit_code(_: Iterable[Address]) -> int: return -1 def make_target(address: Optional[Address] =", "assert results.message() == dedent( \"\"\"\\ typechecker failed (exit code 18).", "@staticmethod def exit_code(_) -> int: return 0 @property def check_results(self)", "CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see", "2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the", "check_results(self) -> CheckResults: addresses = [config.address for config in self.field_sets]", "console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet( output_type=CheckResults,", "test_invalid_target_noops() -> None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code", "✓ SuccessfulChecker succeeded. \"\"\" ) def test_streaming_output_skip() -> None: results", "import UnionMembership from pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner import MockGet,", ") assert exit_code == FailingRequest.exit_code([bad_address]) assert stderr == dedent( \"\"\"\\", "def test_invalid_target_noops() -> None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert", "SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code == FailingRequest.exit_code([bad_address]) assert", "None: address = Address(\"\", target_name=\"tests\") return MockTarget({}, address) def run_typecheck_rule(", "Address from pants.engine.fs import Workspace from pants.engine.target import FieldSet, MultipleSourcesField,", "make_target(address: Optional[Address] = None) -> Target: if address is None:", "], union_membership=union_membership, ) assert not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def", "def test_summary() -> None: good_address = Address(\"\", target_name=\"good\") bad_address =", "Iterable[Address]) -> int: pass @property def check_results(self) -> CheckResults: addresses", "@staticmethod def exit_code(_: Iterable[Address]) -> int: return -1 def make_target(address:", "𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed. - SkippedChecker skipped. ✓", "= run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)],", "\"\"\"\\ typechecker failed (exit code 21). Partition #1 - ghc8.1:", "\"\"\"\\ typechecker failed (exit code 18). stdout stderr \"\"\" )", "MockTarget({}, address) def run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets: List[Target] )", "List, Optional, Tuple, Type from pants.core.goals.check import Check, CheckRequest, CheckResult,", "(MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type", "test_streaming_output_skip() -> None: results = CheckResults([], checker_name=\"typechecker\") assert results.level() ==", "from textwrap import dedent from typing import ClassVar, Iterable, List,", "-1 def make_target(address: Optional[Address] = None) -> Target: if address", "CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\",", "results.message() == dedent( \"\"\"\\ typechecker succeeded. stdout stderr \"\"\" )", "in addresses): return 127 return 0 class SkippedRequest(MockCheckRequest): @staticmethod def", "ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed. - SkippedChecker skipped. ✓ SuccessfulChecker", "results.message() == dedent( \"\"\"\\ typechecker failed (exit code 18). stdout", "dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed. - SkippedChecker", "pants.engine.addresses import Address from pants.engine.fs import Workspace from pants.engine.target import", "= Address(\"\", target_name=\"bad\") exit_code, stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest,", "Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection:", "-> Target: if address is None: address = Address(\"\", target_name=\"tests\")", "def check_results(self) -> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass", "None: results = CheckResults([], checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG assert", "= \"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return -1", "checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod def exit_code(_:", "Optional, Tuple, Type from pants.core.goals.check import Check, CheckRequest, CheckResult, CheckResults,", "_enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda", "== dedent( \"\"\"\\ typechecker failed (exit code 18). stdout stderr", "stdout stderr \"\"\" ) def test_streaming_output_failure() -> None: results =", "def make_target(address: Optional[Address] = None) -> Target: if address is", "code 18). stdout stderr \"\"\" ) def test_streaming_output_partitions() -> None:", "from pathlib import Path from textwrap import dedent from typing", "checker_name=\"typechecker\", ) assert results.level() == LogLevel.ERROR assert results.message() == dedent(", "exit_code(addresses: Iterable[Address]) -> int: if any(address.target_name == \"bad\" for address", "from abc import ABCMeta, abstractmethod from pathlib import Path from", "from pants.engine.target import FieldSet, MultipleSourcesField, Target, Targets from pants.engine.unions import", "int: pass @property def check_results(self) -> CheckResults: addresses = [config.address", "= (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name: ClassVar[str]", "FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int:", "def exit_code(_: Iterable[Address]) -> int: return -1 def make_target(address: Optional[Address]", "test_streaming_output_failure() -> None: results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert", "int: return 0 @property def check_results(self) -> CheckResults: return CheckResults([],", "from pants.engine.fs import Workspace from pants.engine.target import FieldSet, MultipleSourcesField, Target,", "result: Check = run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets),", "import MockGet, RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging import LogLevel class", "\"\"\" ) def test_streaming_output_failure() -> None: results = CheckResults([CheckResult(18, \"stdout\",", "Partition #1 - ghc8.1: Partition #2 - ghc9.2: stdout stderr", "CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields", "metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod def exit_code(_:", "SkippedChecker skipped. ✓ SuccessfulChecker succeeded. \"\"\" ) def test_streaming_output_skip() ->", "@staticmethod @abstractmethod def exit_code(_: Iterable[Address]) -> int: pass @property def", "typechecker succeeded. stdout stderr \"\"\" ) def test_streaming_output_failure() -> None:", "== LogLevel.DEBUG assert results.message() == \"typechecker skipped.\" def test_streaming_output_success() ->", "(MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name: ClassVar[str] @staticmethod", "CheckRequest, CheckResult, CheckResults, check from pants.core.util_rules.distdir import DistDir from pants.engine.addresses", "\"\", \"\", ) ], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name =", "with mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner = RuleRunner() result: Check", "def exit_code(addresses: Iterable[Address]) -> int: if any(address.target_name == \"bad\" for", "typechecker failed (exit code 21). Partition #1 - ghc8.1: Partition", "abc import ABCMeta, abstractmethod from pathlib import Path from textwrap", "pants.testutil.rule_runner import MockGet, RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging import LogLevel", "Address(\"\", target_name=\"tests\") return MockTarget({}, address) def run_typecheck_rule( *, request_types: List[Type[CheckRequest]],", "str]: union_membership = UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as (console, stdio_reader):", "class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) -> int: return 0 @property", "FailingChecker failed. - SkippedChecker skipped. ✓ SuccessfulChecker succeeded. \"\"\" )", "== \"\" def test_summary() -> None: good_address = Address(\"\", target_name=\"good\")", "= RuleRunner() result: Check = run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler,", "field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership, ) assert not stdio_reader.get_stdout() return", "class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address]) ->", "(see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0", ") assert not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() ->", "None: good_address = Address(\"\", target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\") exit_code,", "@property def check_results(self) -> CheckResults: addresses = [config.address for config", "import create_options_bootstrapper from pants.testutil.rule_runner import MockGet, RuleRunner, mock_console, run_rule_with_mocks from", "Iterable[Address]) -> int: return -1 def make_target(address: Optional[Address] = None)", "\"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.INFO assert results.message() ==", "targets=[make_target()]) assert exit_code == 0 assert stderr == \"\" def", "[ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ],", "CheckResults( [ CheckResult( self.exit_code(addresses), \"\", \"\", ) ], checker_name=self.checker_name, )", "def exit_code(_: Iterable[Address]) -> int: return 0 class FailingRequest(MockCheckRequest): checker_name", "= UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner =", "== LogLevel.INFO assert results.message() == dedent( \"\"\"\\ typechecker succeeded. stdout", "1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address])", "= CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR assert", "targets: List[Target] ) -> Tuple[int, str]: union_membership = UnionMembership({CheckRequest: request_types})", "CheckResult( self.exit_code(addresses), \"\", \"\", ) ], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest):", "bad_address = Address(\"\", target_name=\"bad\") exit_code, stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest,", "SuccessfulChecker succeeded. \"\"\" ) def test_streaming_output_skip() -> None: results =", "not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() -> None: exit_code,", "config in self.field_sets] return CheckResults( [ CheckResult( self.exit_code(addresses), \"\", \"\",", "InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod def exit_code(_:", "LogLevel.DEBUG assert results.message() == \"typechecker skipped.\" def test_streaming_output_success() -> None:", "stderr == \"\" def test_summary() -> None: good_address = Address(\"\",", "List[Type[CheckRequest]], targets: List[Target] ) -> Tuple[int, str]: union_membership = UnionMembership({CheckRequest:", "-> int: return -1 def make_target(address: Optional[Address] = None) ->", "= \"mock_target\" core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,)", "\"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return 0 class", "union_membership, ], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ),", "field_set_type = MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod def exit_code(_: Iterable[Address])", "exit_code == FailingRequest.exit_code([bad_address]) assert stderr == dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker", "import dedent from typing import ClassVar, Iterable, List, Optional, Tuple,", "SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code == FailingRequest.exit_code([bad_address])", "checker_name: ClassVar[str] @staticmethod @abstractmethod def exit_code(_: Iterable[Address]) -> int: pass", "output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership, ) assert", "-> int: return 0 @property def check_results(self) -> CheckResults: return", "\"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert results.level() == LogLevel.ERROR assert", "result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() -> None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest],", "= (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta):", "= CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.INFO assert", "required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name:", "stderr \"\"\" ) def test_streaming_output_failure() -> None: results = CheckResults([CheckResult(18,", "Iterable[Address]) -> int: return 0 class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\"", "\"\"\" ) def test_streaming_output_skip() -> None: results = CheckResults([], checker_name=\"typechecker\")", "LogLevel.INFO assert results.message() == dedent( \"\"\"\\ typechecker succeeded. stdout stderr", "results.message() == \"typechecker skipped.\" def test_streaming_output_success() -> None: results =", "required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name =", "union_membership=union_membership, ) assert not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops()", "Target: if address is None: address = Address(\"\", target_name=\"tests\") return", "import LogLevel class MockTarget(Target): alias = \"mock_target\" core_fields = (MultipleSourcesField,)", "class InvalidRequest(MockCheckRequest): field_set_type = InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod def", "], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod def", "address in addresses): return 127 return 0 class SkippedRequest(MockCheckRequest): @staticmethod", "#1 - ghc8.1: Partition #2 - ghc9.2: stdout stderr \"\"\"", "mock_console, run_rule_with_mocks from pants.util.logging import LogLevel class MockTarget(Target): alias =", "= MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod def exit_code(_: Iterable[Address]) ->", "= \"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return 0", "(exit code 18). stdout stderr \"\"\" ) def test_streaming_output_partitions() ->", "-> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet):", "class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address]) ->", "in self.field_sets] return CheckResults( [ CheckResult( self.exit_code(addresses), \"\", \"\", )", "assert results.message() == \"typechecker skipped.\" def test_streaming_output_success() -> None: results", "stdout stderr \"\"\" ) def test_streaming_output_partitions() -> None: results =", "results = CheckResults([], checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG assert results.message()", "Apache License, Version 2.0 (see LICENSE). from abc import ABCMeta,", "Check, CheckRequest, CheckResult, CheckResults, check from pants.core.util_rules.distdir import DistDir from", "== dedent( \"\"\"\\ typechecker succeeded. stdout stderr \"\"\" ) def", "exit_code(_: Iterable[Address]) -> int: return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name =", "code 21). Partition #1 - ghc8.1: Partition #2 - ghc9.2:", "import ABCMeta, abstractmethod from pathlib import Path from textwrap import", "checker_name = \"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return", "exit_code, stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ],", "pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner import MockGet, RuleRunner, mock_console, run_rule_with_mocks", "checker_name = \"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return", "Tuple, Type from pants.core.goals.check import Check, CheckRequest, CheckResult, CheckResults, check", "assert results.message() == dedent( \"\"\"\\ typechecker failed (exit code 21).", "LICENSE). from abc import ABCMeta, abstractmethod from pathlib import Path", "target_name=\"bad\") exit_code, stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest,", "\"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", )", "alias = \"mock_target\" core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet): required_fields =", "field_set_type = InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address])", "SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) -> int: return 0 @property def", "failed (exit code 18). stdout stderr \"\"\" ) def test_streaming_output_partitions()", "InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int:", "Type from pants.core.goals.check import Check, CheckRequest, CheckResult, CheckResults, check from", "assert results.level() == LogLevel.DEBUG assert results.message() == \"typechecker skipped.\" def", "from pants.engine.unions import UnionMembership from pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner", "contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version", "exit_code(_: Iterable[Address]) -> int: return 0 class FailingRequest(MockCheckRequest): checker_name =", "from pants.testutil.rule_runner import MockGet, RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging import", "assert results.level() == LogLevel.INFO assert results.message() == dedent( \"\"\"\\ typechecker", "2.0 (see LICENSE). from abc import ABCMeta, abstractmethod from pathlib", "failed (exit code 21). Partition #1 - ghc8.1: Partition #2", "pants.core.util_rules.distdir import DistDir from pants.engine.addresses import Address from pants.engine.fs import", "return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields =", "def exit_code(_: Iterable[Address]) -> int: pass @property def check_results(self) ->", "def test_streaming_output_partitions() -> None: results = CheckResults( [ CheckResult(21, \"\",", "int: return -1 def make_target(address: Optional[Address] = None) -> Target:", "pants.engine.target import FieldSet, MultipleSourcesField, Target, Targets from pants.engine.unions import UnionMembership", "ABCMeta, abstractmethod from pathlib import Path from textwrap import dedent", "def test_streaming_output_skip() -> None: results = CheckResults([], checker_name=\"typechecker\") assert results.level()", "Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache", "check from pants.core.util_rules.distdir import DistDir from pants.engine.addresses import Address from", "# Licensed under the Apache License, Version 2.0 (see LICENSE).", "Target, Targets from pants.engine.unions import UnionMembership from pants.testutil.option_util import create_options_bootstrapper", ") ], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod", "stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code == 0 assert stderr", "pass @property def check_results(self) -> CheckResults: addresses = [config.address for", "checker_name = \"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return", "is None: address = Address(\"\", target_name=\"tests\") return MockTarget({}, address) def", "skipped. ✓ SuccessfulChecker succeeded. \"\"\" ) def test_streaming_output_skip() -> None:", "checker_name = \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address]) -> int: if", "= run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership,", "0 class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address])", "@abstractmethod def exit_code(_: Iterable[Address]) -> int: pass @property def check_results(self)", "results.message() == dedent( \"\"\"\\ typechecker failed (exit code 21). Partition", "[config.address for config in self.field_sets] return CheckResults( [ CheckResult( self.exit_code(addresses),", "Tuple[int, str]: union_membership = UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as (console,", "class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest):", "-> int: return 0 class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod", "dedent( \"\"\"\\ typechecker failed (exit code 18). stdout stderr \"\"\"", "-> None: results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level()", "-> Tuple[int, str]: union_membership = UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as", "None: results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() ==", "succeeded. \"\"\" ) def test_streaming_output_skip() -> None: results = CheckResults([],", "addresses): return 127 return 0 class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_)", "Iterable[Address]) -> int: if any(address.target_name == \"bad\" for address in", "rule_runner = RuleRunner() result: Check = run_rule_with_mocks( check, rule_args=[ console,", "mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner = RuleRunner() result: Check =", "== 0 assert stderr == \"\" def test_summary() -> None:", "failed. 𐄂 FailingChecker failed. - SkippedChecker skipped. ✓ SuccessfulChecker succeeded.", "InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type", "𐄂 FailingChecker failed. - SkippedChecker skipped. ✓ SuccessfulChecker succeeded. \"\"\"", "== LogLevel.ERROR assert results.message() == dedent( \"\"\"\\ typechecker failed (exit", "0 @property def check_results(self) -> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class", "int: return 0 class FailingRequest(MockCheckRequest): checker_name = \"FailingChecker\" @staticmethod def", "\"FailingChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int: return 1 class", "Iterable, List, Optional, Tuple, Type from pants.core.goals.check import Check, CheckRequest,", "assert results.message() == dedent( \"\"\"\\ typechecker succeeded. stdout stderr \"\"\"", "LogLevel class MockTarget(Target): alias = \"mock_target\" core_fields = (MultipleSourcesField,) class", "from pants.core.goals.check import Check, CheckRequest, CheckResult, CheckResults, check from pants.core.util_rules.distdir", "Optional[Address] = None) -> Target: if address is None: address", "as (console, stdio_reader): rule_runner = RuleRunner() result: Check = run_rule_with_mocks(", "ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address]) -> int:", "@property def check_results(self) -> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField):", "DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results,", "class MockTarget(Target): alias = \"mock_target\" core_fields = (MultipleSourcesField,) class MockCheckFieldSet(FieldSet):", "CheckResults([], checker_name=\"SkippedChecker\") class InvalidField(MultipleSourcesField): pass class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,)", "pants.engine.fs import Workspace from pants.engine.target import FieldSet, MultipleSourcesField, Target, Targets", "MockCheckFieldSet(FieldSet): required_fields = (MultipleSourcesField,) class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet", "None: results = CheckResults( [ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0,", "== FailingRequest.exit_code([bad_address]) assert stderr == dedent( \"\"\"\\ 𐄂 ConditionallySucceedsChecker failed.", "stderr = run_typecheck_rule( request_types=[ ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address),", "import FieldSet, MultipleSourcesField, Target, Targets from pants.engine.unions import UnionMembership from", "return 0 @property def check_results(self) -> CheckResults: return CheckResults([], checker_name=\"SkippedChecker\")", "typechecker failed (exit code 18). stdout stderr \"\"\" ) def", "from pants.core.util_rules.distdir import DistDir from pants.engine.addresses import Address from pants.engine.fs", "\"\"\"\\ 𐄂 ConditionallySucceedsChecker failed. 𐄂 FailingChecker failed. - SkippedChecker skipped.", "MultipleSourcesField, Target, Targets from pants.engine.unions import UnionMembership from pants.testutil.option_util import", "stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() -> None: exit_code, stderr", "CheckResults: addresses = [config.address for config in self.field_sets] return CheckResults(", "import Path from textwrap import dedent from typing import ClassVar,", "input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership, ) assert not", "def check_results(self) -> CheckResults: addresses = [config.address for config in", "return -1 def make_target(address: Optional[Address] = None) -> Target: if", "return CheckResults( [ CheckResult( self.exit_code(addresses), \"\", \"\", ) ], checker_name=self.checker_name,", "assert results.level() == LogLevel.ERROR assert results.message() == dedent( \"\"\"\\ typechecker", "-> None: good_address = Address(\"\", target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\")", "\"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address]) -> int: if any(address.target_name ==", "pass class InvalidFieldSet(MockCheckFieldSet): required_fields = (InvalidField,) class InvalidRequest(MockCheckRequest): field_set_type =", "run_rule_with_mocks( check, rule_args=[ console, Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ],", "0 class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) -> int: return 0", "None: results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() ==", "class MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod", "abstractmethod from pathlib import Path from textwrap import dedent from", "\"\"\" ) def test_streaming_output_partitions() -> None: results = CheckResults( [", "request_types}) with mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner = RuleRunner() result:", "checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR assert results.message() == dedent( \"\"\"\\", "pants.util.logging import LogLevel class MockTarget(Target): alias = \"mock_target\" core_fields =", "], targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code == FailingRequest.exit_code([bad_address]) assert stderr", "SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address]) -> int:", "FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code ==", ") assert results.level() == LogLevel.ERROR assert results.message() == dedent( \"\"\"\\", "None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code == 0", "\"bad\" for address in addresses): return 127 return 0 class", "License, Version 2.0 (see LICENSE). from abc import ABCMeta, abstractmethod", "address is None: address = Address(\"\", target_name=\"tests\") return MockTarget({}, address)", "mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ), ], union_membership=union_membership,", ") def test_streaming_output_partitions() -> None: results = CheckResults( [ CheckResult(21,", "= run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code == 0 assert stderr ==", "= Address(\"\", target_name=\"tests\") return MockTarget({}, address) def run_typecheck_rule( *, request_types:", "exit_code == 0 assert stderr == \"\" def test_summary() ->", "ConditionallySucceedsRequest, FailingRequest, SkippedRequest, SuccessfulRequest, ], targets=[make_target(good_address), make_target(bad_address)], ) assert exit_code", "= InvalidFieldSet checker_name = \"InvalidChecker\" @staticmethod def exit_code(_: Iterable[Address]) ->", "== dedent( \"\"\"\\ typechecker failed (exit code 21). Partition #1", "from pants.util.logging import LogLevel class MockTarget(Target): alias = \"mock_target\" core_fields", "CheckResults([], checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG assert results.message() == \"typechecker", "pants.engine.unions import UnionMembership from pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner import", "from pants.engine.addresses import Address from pants.engine.fs import Workspace from pants.engine.target", "for config in self.field_sets] return CheckResults( [ CheckResult( self.exit_code(addresses), \"\",", "= \"ConditionallySucceedsChecker\" @staticmethod def exit_code(addresses: Iterable[Address]) -> int: if any(address.target_name", "import ClassVar, Iterable, List, Optional, Tuple, Type from pants.core.goals.check import", "run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets: List[Target] ) -> Tuple[int, str]:", "Version 2.0 (see LICENSE). from abc import ABCMeta, abstractmethod from", "exit_code(_: Iterable[Address]) -> int: pass @property def check_results(self) -> CheckResults:", "def exit_code(_: Iterable[Address]) -> int: return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name", "], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest, mock=lambda field_set_collection: field_set_collection.check_results, ), ],", "Workspace(rule_runner.scheduler, _enforce_effects=False), Targets(targets), DistDir(relpath=Path(\"dist\")), union_membership, ], mock_gets=[ MockGet( output_type=CheckResults, input_type=CheckRequest,", "typing import ClassVar, Iterable, List, Optional, Tuple, Type from pants.core.goals.check", "\"\"\"\\ typechecker succeeded. stdout stderr \"\"\" ) def test_streaming_output_failure() ->", "\"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR assert results.message() ==", "good_address = Address(\"\", target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\") exit_code, stderr", "@staticmethod def exit_code(_: Iterable[Address]) -> int: return 1 class ConditionallySucceedsRequest(MockCheckRequest):", "Iterable[Address]) -> int: return 1 class ConditionallySucceedsRequest(MockCheckRequest): checker_name = \"ConditionallySucceedsChecker\"", "UnionMembership from pants.testutil.option_util import create_options_bootstrapper from pants.testutil.rule_runner import MockGet, RuleRunner,", "self.exit_code(addresses), \"\", \"\", ) ], checker_name=self.checker_name, ) class SuccessfulRequest(MockCheckRequest): checker_name", "from typing import ClassVar, Iterable, List, Optional, Tuple, Type from", "partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert results.level() == LogLevel.ERROR assert results.message()", "if address is None: address = Address(\"\", target_name=\"tests\") return MockTarget({},", "*, request_types: List[Type[CheckRequest]], targets: List[Target] ) -> Tuple[int, str]: union_membership", "- SkippedChecker skipped. ✓ SuccessfulChecker succeeded. \"\"\" ) def test_streaming_output_skip()", "-> None: results = CheckResults( [ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"),", "exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code == 0 assert", "assert exit_code == FailingRequest.exit_code([bad_address]) assert stderr == dedent( \"\"\"\\ 𐄂", "== \"bad\" for address in addresses): return 127 return 0", "18). stdout stderr \"\"\" ) def test_streaming_output_partitions() -> None: results", "union_membership = UnionMembership({CheckRequest: request_types}) with mock_console(create_options_bootstrapper()) as (console, stdio_reader): rule_runner", "@staticmethod def exit_code(addresses: Iterable[Address]) -> int: if any(address.target_name == \"bad\"", "import Address from pants.engine.fs import Workspace from pants.engine.target import FieldSet,", "MockCheckRequest(CheckRequest, metaclass=ABCMeta): field_set_type = MockCheckFieldSet checker_name: ClassVar[str] @staticmethod @abstractmethod def", "\"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\", \"stderr\", partition_description=\"ghc9.2\"), ], checker_name=\"typechecker\", ) assert", "= CheckResults([], checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG assert results.message() ==", "assert exit_code == 0 assert stderr == \"\" def test_summary()", "failed. - SkippedChecker skipped. ✓ SuccessfulChecker succeeded. \"\"\" ) def", "address) def run_typecheck_rule( *, request_types: List[Type[CheckRequest]], targets: List[Target] ) ->", "(see LICENSE). from abc import ABCMeta, abstractmethod from pathlib import", "MockGet, RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging import LogLevel class MockTarget(Target):", "if any(address.target_name == \"bad\" for address in addresses): return 127", "target_name=\"good\") bad_address = Address(\"\", target_name=\"bad\") exit_code, stderr = run_typecheck_rule( request_types=[", "results = CheckResults( [ CheckResult(21, \"\", \"\", partition_description=\"ghc8.1\"), CheckResult(0, \"stdout\",", "-> None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()]) assert exit_code ==", "stderr \"\"\" ) def test_streaming_output_partitions() -> None: results = CheckResults(", "(exit code 21). Partition #1 - ghc8.1: Partition #2 -", "Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under", "<reponame>yoav-orca/pants # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). #", "# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed", ") def test_streaming_output_skip() -> None: results = CheckResults([], checker_name=\"typechecker\") assert", "checker_name=\"typechecker\") assert results.level() == LogLevel.DEBUG assert results.message() == \"typechecker skipped.\"", "self.field_sets] return CheckResults( [ CheckResult( self.exit_code(addresses), \"\", \"\", ) ],", "succeeded. stdout stderr \"\"\" ) def test_streaming_output_failure() -> None: results", "127 return 0 class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) -> int:", "21). Partition #1 - ghc8.1: Partition #2 - ghc9.2: stdout", "test_streaming_output_success() -> None: results = CheckResults([CheckResult(0, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert", "stdio_reader.get_stderr() def test_invalid_target_noops() -> None: exit_code, stderr = run_typecheck_rule(request_types=[InvalidRequest], targets=[make_target()])", "stdio_reader): rule_runner = RuleRunner() result: Check = run_rule_with_mocks( check, rule_args=[", "for address in addresses): return 127 return 0 class SkippedRequest(MockCheckRequest):", "create_options_bootstrapper from pants.testutil.rule_runner import MockGet, RuleRunner, mock_console, run_rule_with_mocks from pants.util.logging", "assert not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr() def test_invalid_target_noops() -> None:", "), ], union_membership=union_membership, ) assert not stdio_reader.get_stdout() return result.exit_code, stdio_reader.get_stderr()", "return 0 class SkippedRequest(MockCheckRequest): @staticmethod def exit_code(_) -> int: return", "dedent( \"\"\"\\ typechecker failed (exit code 21). Partition #1 -", "class SuccessfulRequest(MockCheckRequest): checker_name = \"SuccessfulChecker\" @staticmethod def exit_code(_: Iterable[Address]) ->", "any(address.target_name == \"bad\" for address in addresses): return 127 return", "results = CheckResults([CheckResult(18, \"stdout\", \"stderr\")], checker_name=\"typechecker\") assert results.level() == LogLevel.ERROR", "ClassVar[str] @staticmethod @abstractmethod def exit_code(_: Iterable[Address]) -> int: pass @property" ]
[ "scores conflate other things like recall on these metrics and", "} def get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any,", "= simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels) label_names = [\"O\", \"TERM\",", "{\"intent_acc\": acc} def read_prediction_text(args: Any) -> List[str]: return [ text.strip()", "= \"TERM\" in simple_label_sent and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label)", "get_slot_labels(args: Any) -> List[str]: return [ label.strip() for label in", "# Get the intent comparison result intent_result = intent_preds ==", "the first word in a definition differently from skipping the", "def get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) -> Dict[Any, Any]: assert len(preds)", "= [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r, f, s", "M such pairs. Say a ‘partial match’ happens when the", "count_exact_matches = sum(exact_matches) # E partial_precision = count_partial_matches / count_both_in_preds", "for label in open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" ) ]", "= precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r", "# print(per_class) return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1,", "sum(both_in_preds) # N count_both_in_labels = sum(both_in_labels) # M count_partial_matches =", "preds_flattened, average=None, labels=label_names ) s = [int(si) for si in", "match and \"DEF\" in match: partial_match = True if False", "exact_precision = count_exact_matches / count_both_in_preds exact_recall = count_exact_matches / count_both_in_labels", "= False break slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc = np.multiply(intent_result,", "# New metrics added following Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds,", "= recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names", "def get_pos_labels(args: Any) -> List[str]: return [ label.strip() for label", "if p != l: one_sent_result = False break slot_result.append(one_sent_result) slot_result", "+ exact_recall) return { \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore,", "[\"O\", \"TERM\", \"DEF\"] p, r, f, s = score(simple_labels, simple_preds,", "because users may just care about accuracy of term and", ") -> Dict[Any, Any]: \"\"\" Conceptually, define the following new", "\"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def", "term spans AND there is some overlap between the predicted", "for label in open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" ) ]", "micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\":", "the slot comparision result slot_result = [] for preds, labels", "[round(float(pi), 3) for pi in f] per_class = {\"p\": list(p),", "and DEF? (I think these matter because users may just", "slot_result = [] for preds, labels in zip(slot_preds, slot_labels): assert", "sum(partial_matches) # P count_exact_matches = sum(exact_matches) # E partial_precision =", "macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\":", "= get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc(", "by replacing {B,I}-TERM to TERM and {B,I}-DEF to DEF simple_preds", "per_class = {\"p\": list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)}", "count_both_in_preds exact_recall = count_exact_matches / count_both_in_labels exact_fscore = 2 *", "Dict[Any, Any]: \"\"\" Conceptually, define the following new types of", "\"TERM\", \"DEF\"] p, r, f, s = score(simple_labels, simple_preds, average=None,", "\"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def", "about accuracy of term and defn matching and the macro", "for text in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" ) ]", "following new types of ‘virtual tags’ TERM = B-term OR", "return [ label.strip() for label in open( os.path.join(args.data_dir, args.pos_label_file), \"r\",", "def read_prediction_text(args: Any) -> List[str]: return [ text.strip() for text", ") -> Dict[Any, Any]: \"\"\" Suppose there are N such", "Conceptually, define the following new types of ‘virtual tags’ TERM", "list(r), \"f\": list(f), \"s\": list(s)} # print(per_class) return { \"slot_precision_macro\":", "get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], )", "\"r\", encoding=\"utf-8\" ) ] def get_slot_labels(args: Any) -> List[str]: return", "label.strip() for label in open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" )", "p, r, f, s = score(simple_labels, simple_preds, average=None, labels=label_names) s", "p != l: one_sent_result = False break slot_result.append(one_sent_result) slot_result =", "List[List[str]] ) -> Dict[Any, Any]: \"\"\" Conceptually, define the following", "partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) # N count_both_in_labels = sum(both_in_labels)", "count_partial_matches / count_both_in_labels partial_fscore = ( 2 * partial_precision *", "for pi in p] r = [round(float(pi), 3) for pi", "together both_in_pred = \"TERM\" in simple_pred_sent and \"DEF\" in simple_pred_sent", "def get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]:", "== len(intent_labels) == len(slot_preds) == len(slot_labels) ) results: Dict[Any, Any]", "os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" ) ] def get_pos_labels(args: Any) ->", "sentence)\"\"\" # Get the intent comparison result intent_result = intent_preds", "in open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" ) ] def get_pos_labels(args:", "[ label.strip() for label in open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\"", "numbers for TERM and DEF? (I think these matter because", "= intent_preds == intent_labels # Get the slot comparision result", "+ partial_recall) ) exact_precision = count_exact_matches / count_both_in_preds exact_recall =", "assert len(simple_preds) == len(simple_labels) label_names = [\"O\", \"TERM\", \"DEF\"] p,", "\"DEF\"] p, r, f, s = score(simple_labels, simple_preds, average=None, labels=label_names)", "slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results def simplify_tokens(preds:", "Get the slot comparision result slot_result = [] for preds,", "\"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]] )", "TERM = B-term OR I-Term (ie the union of those", "preds_flattened = [p for ps in preds for p in", "pi in r] f = [round(float(pi), 3) for pi in", "\"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics( preds:", "= sum(both_in_preds) # N count_both_in_labels = sum(both_in_labels) # M count_partial_matches", "B-Def OR I-Def Now, what are the P,R & F1", "ps] labels_flattened = [l for ls in labels for l", "def get_intent_acc(preds: List[str], labels: List[str]) -> Dict[Any, Any]: acc =", "like recall on these metrics and precision on O. Likewise", "si in s] p = [round(float(pi), 3) for pi in", "== len(labels) # flatten preds_flattened = [p for ps in", "one_sent_result = False break slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc =", "labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) # check whether", "label.strip() for label in open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" )", "data and the system predicts M such pairs. Say a", "open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" ) ] def get_sentence_frame_acc( intent_preds:", "average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names = [\"O\", \"B-TERM\",", "2 * exact_precision * exact_recall / (exact_precision + exact_recall) return", "between the predicted and gold definition spans. Let X be", "List[str]: return [ label.strip() for label in open( os.path.join(args.data_dir, args.slot_label_file),", "Let X be the number of partial matches. What are", "\"f\": list(f), \"s\": list(s)} # print(per_class) return { \"slot_precision_macro\": macro_p,", "all the slots are correct (in one sentence)\"\"\" # Get", "both_in_label: for p, l in zip(simple_pred_sent, simple_label_sent): if p ==", "Style.RESET_ALL) def get_intent_labels(args: Any) -> List[str]: return [ label.strip() for", "is some overlap (at least one token) between the predicted", "tags’ TERM = B-term OR I-Term (ie the union of", "-> Dict[Any, Any]: assert ( len(intent_preds) == len(intent_labels) == len(slot_preds)", "r, f, s = score( labels_flattened, preds_flattened, average=None, labels=label_names )", "Dict[Any, Any] = {} intent_result = get_intent_acc(intent_preds, intent_labels) slot_result =", "DEF? (I think these matter because users may just care", "labels_flattened = [l for ls in labels for l in", "def highlight(input_: Any) -> str: input_ = str(input_) return str(Fore.YELLOW", "-> Dict[Any, Any]: \"\"\" Conceptually, define the following new types", "len(slot_labels) ) results: Dict[Any, Any] = {} intent_result = get_intent_acc(intent_preds,", "DEF simple_preds = simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds) ==", "label_names = [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r, f,", "for TERM and DEF? (I think these matter because users", "= [] for preds, labels in zip(slot_preds, slot_labels): assert len(preds)", "= get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result)", "N such pairs in the gold data and the system", "[], [] for pred_sent, label_sent in zip(preds, labels): simple_pred_sent =", "new types of ‘virtual tags’ TERM = B-term OR I-Term", "!= l: one_sent_result = False break slot_result.append(one_sent_result) slot_result = np.array(slot_result)", "the system predicts M such pairs. Say a ‘partial match’", "not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore def compute_metrics(", "are Partial match precision = P/M Partial match recall =", "= count_partial_matches / count_both_in_preds partial_recall = count_partial_matches / count_both_in_labels partial_fscore", "type: ignore if not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type:", "slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc( intent_preds, intent_labels, slot_preds,", ") s = [int(si) for si in s] p =", "# type: ignore if not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) #", "results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results def simplify_tokens(preds: List[str]) ->", "spans. Let X be the number of partial matches. What", "simple_label_sent = simplify_tokens(label_sent) # check whether term/def exist together both_in_pred", "(in one sentence)\"\"\" # Get the intent comparison result intent_result", "P,R & F1 numbers for TERM and DEF? (I think", "per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], }", "List[str]: return [ text.strip() for text in open( os.path.join(args.pred_dir, args.pred_input_file),", "break slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc = np.multiply(intent_result, slot_result).mean() return", "preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened,", "sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support as score from", "torch.cuda.manual_seed_all(seed) # type: ignore def compute_metrics( intent_preds: List[str], intent_labels: List[str],", "the following new types of ‘virtual tags’ TERM = B-term", "preds_flattened, average=\"micro\") label_names = [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p,", "l in ls] # simplify by replacing {B,I}-TERM to TERM", "ls] # simplify by replacing {B,I}-TERM to TERM and {B,I}-DEF", "partial_match = False exact_match = False match: List[Union[str, bool]] =", "len(intent_preds) == len(intent_labels) == len(slot_preds) == len(slot_labels) ) results: Dict[Any,", "the number of partial matches. What are Partial match precision", "simple_preds, average=None, labels=label_names) s = [int(si) for si in s]", "average=\"micro\") label_names = [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r,", "gold data and the system predicts M such pairs. Say", "p == l: match.append(p) else: match.append(False) if \"TERM\" in match", "set_torch_seed(seed: Any, no_cuda: bool) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) #", "label_sent in zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent)", "False break slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc = np.multiply(intent_result, slot_result).mean()", "def set_torch_seed(seed: Any, no_cuda: bool) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed)", "= [], [] for pred_sent, label_sent in zip(preds, labels): simple_pred_sent", "-> List[str]: simple_preds = [] for p in preds: if", "f, s = score(simple_labels, simple_preds, average=None, labels=label_names) s = [int(si)", "* exact_recall / (exact_precision + exact_recall) return { \"partial_match_precision\": partial_precision,", "exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) # N", "ps in preds for p in ps] labels_flattened = [l", "\"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds: List[str], labels: List[str]) -> Dict[Any,", "torch from colorama import Fore, Style from sklearn.metrics import f1_score", "\"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"],", "number of partial matches. What are Partial match precision =", "count_partial_matches = sum(partial_matches) # P count_exact_matches = sum(exact_matches) # E", "= [int(si) for si in s] p = [round(float(pi), 3)", "partial_recall) ) exact_precision = count_exact_matches / count_both_in_preds exact_recall = count_exact_matches", "open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" ) ] def get_pos_labels(args: Any)", "per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds: List[str], labels: List[str]) ->", "for pi in r] f = [round(float(pi), 3) for pi", "correct (in one sentence)\"\"\" # Get the intent comparison result", "intent_labels, slot_preds, slot_labels ) # New metrics added following Dan's", "l: match.append(p) else: match.append(False) if \"TERM\" in match and \"DEF\"", "\"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"],", "per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds:", "\"DEF\" in match: partial_match = True if False not in", "-> Dict[Any, Any]: assert len(preds) == len(labels) # flatten preds_flattened", "List, Union import numpy as np import torch from colorama", "return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p,", "= simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) # check whether term/def exist", "len(preds) == len(labels) both_in_preds, both_in_labels = [], [] partial_matches, exact_matches", "are N such pairs in the gold data and the", "match: partial_match = True if False not in match: exact_match", "replacing {B,I}-TERM to TERM and {B,I}-DEF to DEF simple_preds =", "= get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels ) # New metrics", "import torch from colorama import Fore, Style from sklearn.metrics import", "partial_precision = count_partial_matches / count_both_in_preds partial_recall = count_partial_matches / count_both_in_labels", "read_prediction_text(args: Any) -> List[str]: return [ text.strip() for text in", "gold definition spans. Let X be the number of partial", "\"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r, f, s = score( labels_flattened,", "} def get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) -> Dict[Any, Any]: assert", "Any]: \"\"\"For the cases that intent and all the slots", "for preds, labels in zip(slot_preds, slot_labels): assert len(preds) == len(labels)", "simple_preds = simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels)", "exact_fscore = 2 * exact_precision * exact_recall / (exact_precision +", "if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds", "[\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r, f, s =", "return [ label.strip() for label in open( os.path.join(args.data_dir, args.intent_label_file), \"r\",", "results: Dict[Any, Any] = {} intent_result = get_intent_acc(intent_preds, intent_labels) slot_result", "[] for pred_sent, label_sent in zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent)", "exact_recall / (exact_precision + exact_recall) return { \"partial_match_precision\": partial_precision, \"partial_match_recall\":", "these matter because users may just care about accuracy of", "in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False exact_match = False", "[int(si) for si in s] p = [round(float(pi), 3) for", "labels): if p != l: one_sent_result = False break slot_result.append(one_sent_result)", "and the system predicts M such pairs. Say a ‘partial", "r] f = [round(float(pi), 3) for pi in f] per_class", "\"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r,", "& F1 numbers for TERM and DEF? (I think these", "List[str]: return [ label.strip() for label in open( os.path.join(args.data_dir, args.intent_label_file),", "def compute_metrics( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]],", "labels_flattened, preds_flattened, average=None, labels=label_names ) s = [int(si) for si", "in match and \"DEF\" in match: partial_match = True if", "in labels for l in ls] macro_f1 = f1_score(labels_flattened, preds_flattened,", "simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False exact_match = False match:", "exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) # N count_both_in_labels = sum(both_in_labels) #", "(partial_precision + partial_recall) ) exact_precision = count_exact_matches / count_both_in_preds exact_recall", "2 * partial_precision * partial_recall / (partial_precision + partial_recall) )", "List[str], labels: List[str]) -> Dict[Any, Any]: acc = (preds ==", "simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels) label_names = [\"O\", \"TERM\", \"DEF\"]", "precision on O. Likewise the current macro average treats missing", "what are the P,R & F1 numbers for TERM and", "macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\":", ") ] def get_slot_labels(args: Any) -> List[str]: return [ label.strip()", "current macro average treats missing the first word in a", "as np import torch from colorama import Fore, Style from", "the predicted and gold term spans AND there is some", "zip(preds, labels): if p != l: one_sent_result = False break", "import os import random from typing import Any, Dict, List,", "average treats missing the first word in a definition differently", "p, l in zip(simple_pred_sent, simple_label_sent): if p == l: match.append(p)", "f1_score from sklearn.metrics import precision_recall_fscore_support as score from sklearn.metrics import", "assert len(preds) == len(labels) # flatten preds_flattened = [p for", "happens when the system predicts a pair <term,defn> and there", "in s] p = [round(float(pi), 3) for pi in p]", "3) for pi in r] f = [round(float(pi), 3) for", "[] for p in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"):", "partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\":", "average=None, labels=label_names) s = [int(si) for si in s] p", "sklearn.metrics import precision_score, recall_score def highlight(input_: Any) -> str: input_", "the cases that intent and all the slots are correct", "= [], [] partial_matches, exact_matches = [], [] for pred_sent,", "list(r), \"f\": list(f), \"s\": list(s)} # pprint(per_class) return { \"slot_merged_TERM_precision\":", "\"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2],", "be the number of partial matches. What are Partial match", "some overlap between the predicted and gold definition spans. Let", "Dict[Any, Any]: \"\"\" Suppose there are N such pairs in", "and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False exact_match", "exact_recall) return { \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\":", "(at least one token) between the predicted and gold term", "partial matches. What are Partial match precision = P/M Partial", "random from typing import Any, Dict, List, Union import numpy", "recall on these metrics and precision on O. Likewise the", "-> List[str]: return [ text.strip() for text in open( os.path.join(args.pred_dir,", "and {B,I}-DEF to DEF simple_preds = simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened)", "s = score(simple_labels, simple_preds, average=None, labels=label_names) s = [int(si) for", "micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\")", "result intent_result = intent_preds == intent_labels # Get the slot", "def get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]:", "N count_both_in_labels = sum(both_in_labels) # M count_partial_matches = sum(partial_matches) #", "both_in_labels.append(both_in_label) partial_match = False exact_match = False match: List[Union[str, bool]]", "things like recall on these metrics and precision on O.", "import precision_recall_fscore_support as score from sklearn.metrics import precision_score, recall_score def", "List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: assert ( len(intent_preds)", "such pairs. Say a ‘partial match’ happens when the system", "[ label.strip() for label in open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\"", "# M count_partial_matches = sum(partial_matches) # P count_exact_matches = sum(exact_matches)", ") ] def get_pos_labels(args: Any) -> List[str]: return [ label.strip()", "preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened,", "= [round(float(pi), 3) for pi in f] per_class = {\"p\":", "per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) ->", "count_both_in_labels exact_fscore = 2 * exact_precision * exact_recall / (exact_precision", "overlap (at least one token) between the predicted and gold", "print(per_class) return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\":", "= {\"p\": list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)} #", "micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\")", "matter because users may just care about accuracy of term", "simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds def get_partial_match_metrics( preds: List[List[str]], labels:", "there are N such pairs in the gold data and", "list(s)} # print(per_class) return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\":", "acc = (preds == labels).mean() return {\"intent_acc\": acc} def read_prediction_text(args:", "no_cuda: bool) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore", "get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\"", "[round(float(pi), 3) for pi in r] f = [round(float(pi), 3)", "-> Dict[Any, Any]: \"\"\" Suppose there are N such pairs", "p in ps] labels_flattened = [l for ls in labels", "# pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1],", "intent_labels # Get the slot comparision result slot_result = []", "in open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" ) ] def set_torch_seed(seed:", "results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results def simplify_tokens(preds: List[str]) -> List[str]:", "= sum(exact_matches) # E partial_precision = count_partial_matches / count_both_in_preds partial_recall", "and both_in_label: for p, l in zip(simple_pred_sent, simple_label_sent): if p", "Any) -> List[str]: return [ label.strip() for label in open(", "no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore def compute_metrics( intent_preds:", "slot_preds, slot_labels ) # New metrics added following Dan's request.", "such pairs in the gold data and the system predicts", "tags) DEF = B-Def OR I-Def Now, what are the", "and defn matching and the macro averaged scores conflate other", "s] p = [round(float(pi), 3) for pi in p] r", "\"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]],", "== len(labels) one_sent_result = True for p, l in zip(preds,", "for ls in labels for l in ls] # simplify", "{ \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\":", "to DEF simple_preds = simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds)", "{ \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\":", "f, s = score( labels_flattened, preds_flattened, average=None, labels=label_names ) s", "( 2 * partial_precision * partial_recall / (partial_precision + partial_recall)", "f] per_class = {\"p\": list(p), \"r\": list(r), \"f\": list(f), \"s\":", "l in zip(preds, labels): if p != l: one_sent_result =", "those two tags) DEF = B-Def OR I-Def Now, what", "= True if False not in match: exact_match = True", "partial_match = True if False not in match: exact_match =", "simple_label_sent and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False", "os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" ) ] def get_slot_labels(args: Any) ->", "per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) -> Dict[Any, Any]:", "+ str(input_) + Style.RESET_ALL) def get_intent_labels(args: Any) -> List[str]: return", "recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names = [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"]", "[] if both_in_pred and both_in_label: for p, l in zip(simple_pred_sent,", "intent_result = intent_preds == intent_labels # Get the slot comparision", "just care about accuracy of term and defn matching and", "sklearn.metrics import precision_recall_fscore_support as score from sklearn.metrics import precision_score, recall_score", "in a definition differently from skipping the last word. \"\"\"", "partial_recall = count_partial_matches / count_both_in_labels partial_fscore = ( 2 *", "for p in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\")", "len(simple_labels) label_names = [\"O\", \"TERM\", \"DEF\"] p, r, f, s", "recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names =", "= score( labels_flattened, preds_flattened, average=None, labels=label_names ) s = [int(si)", "macro averaged scores conflate other things like recall on these", "in simple_pred_sent both_in_label = \"TERM\" in simple_label_sent and \"DEF\" in", "\"TERM\" in simple_label_sent and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match", "\"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"],", "differently from skipping the last word. \"\"\" assert len(preds) ==", "compute_metrics( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], )", "\"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) -> Dict[Any,", "F1 numbers for TERM and DEF? (I think these matter", "skipping the last word. \"\"\" assert len(preds) == len(labels) #", "intent_preds, intent_labels, slot_preds, slot_labels ) # New metrics added following", "= [] for p in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif", "the slots are correct (in one sentence)\"\"\" # Get the", "\"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False exact_match =", "p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds def get_partial_match_metrics( preds: List[List[str]],", "and gold term spans AND there is some overlap between", "match.append(p) else: match.append(False) if \"TERM\" in match and \"DEF\" in", "micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], }", "following Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds,", "from sklearn.metrics import precision_score, recall_score def highlight(input_: Any) -> str:", "get_intent_labels(args: Any) -> List[str]: return [ label.strip() for label in", "numpy as np import torch from colorama import Fore, Style", "\"DEF\" in simple_pred_sent both_in_label = \"TERM\" in simple_label_sent and \"DEF\"", "labels for l in ls] # simplify by replacing {B,I}-TERM", "os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" ) ] def get_sentence_frame_acc( intent_preds: List[str],", "# E partial_precision = count_partial_matches / count_both_in_preds partial_recall = count_partial_matches", "precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r =", "and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore def compute_metrics( intent_preds: List[str],", "return [ label.strip() for label in open( os.path.join(args.data_dir, args.slot_label_file), \"r\",", "are correct (in one sentence)\"\"\" # Get the intent comparison", "\"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1,", "in the gold data and the system predicts M such", "in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" ) ] def get_sentence_frame_acc(", "simple_preds.append(p) return simple_preds def get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]] )", "= [] if both_in_pred and both_in_label: for p, l in", "\"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore,", "OR I-Term (ie the union of those two tags) DEF", "{\"p\": list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)} # print(per_class)", "per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds: List[str], labels:", "and \"DEF\" in simple_pred_sent both_in_label = \"TERM\" in simple_label_sent and", "overlap between the predicted and gold definition spans. Let X", "import f1_score from sklearn.metrics import precision_recall_fscore_support as score from sklearn.metrics", "predicted and gold term spans AND there is some overlap", "# flatten preds_flattened = [p for ps in preds for", "preds for p in ps] labels_flattened = [l for ls", "== l: match.append(p) else: match.append(False) if \"TERM\" in match and", "slot_result = np.array(slot_result) sementic_acc = np.multiply(intent_result, slot_result).mean() return {\"sementic_frame_acc\": sementic_acc}", "macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\")", "and there is some overlap (at least one token) between", "gold term spans AND there is some overlap between the", "exact_matches = [], [] for pred_sent, label_sent in zip(preds, labels):", "len(simple_preds) == len(simple_labels) label_names = [\"O\", \"TERM\", \"DEF\"] p, r,", "= [round(float(pi), 3) for pi in r] f = [round(float(pi),", "List[Union[str, bool]] = [] if both_in_pred and both_in_label: for p,", "request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result)", "args.slot_label_file), \"r\", encoding=\"utf-8\" ) ] def get_pos_labels(args: Any) -> List[str]:", "[] for preds, labels in zip(slot_preds, slot_labels): assert len(preds) ==", "[] partial_matches, exact_matches = [], [] for pred_sent, label_sent in", "labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Suppose there are", "count_exact_matches / count_both_in_labels exact_fscore = 2 * exact_precision * exact_recall", "= 2 * exact_precision * exact_recall / (exact_precision + exact_recall)", "p in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else:", "/ (exact_precision + exact_recall) return { \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall,", "first word in a definition differently from skipping the last", "[l for ls in labels for l in ls] macro_f1", "elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds def get_partial_match_metrics( preds:", "in simple_label_sent and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match =", "\"r\", encoding=\"utf-8\" ) ] def set_torch_seed(seed: Any, no_cuda: bool) ->", "# simplify by replacing {B,I}-TERM to TERM and {B,I}-DEF to", "simplify_tokens(label_sent) # check whether term/def exist together both_in_pred = \"TERM\"", "} def get_intent_acc(preds: List[str], labels: List[str]) -> Dict[Any, Any]: acc", "input_ = str(input_) return str(Fore.YELLOW + str(input_) + Style.RESET_ALL) def", "in zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) #", "score from sklearn.metrics import precision_score, recall_score def highlight(input_: Any) ->", "Any]: \"\"\" Suppose there are N such pairs in the", "\"\"\" Suppose there are N such pairs in the gold", "import random from typing import Any, Dict, List, Union import", "Dict, List, Union import numpy as np import torch from", "open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" ) ] def get_slot_labels(args: Any)", "slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: assert (", "results.update(slot_simple_result) results.update(partial_match_result) return results def simplify_tokens(preds: List[str]) -> List[str]: simple_preds", "np.random.seed(seed) torch.manual_seed(seed) # type: ignore if not no_cuda and torch.cuda.is_available():", "precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r =", "count_partial_matches / count_both_in_preds partial_recall = count_partial_matches / count_both_in_labels partial_fscore =", "simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) # check whether term/def exist together", "on these metrics and precision on O. Likewise the current", "Style from sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support as", "users may just care about accuracy of term and defn", "in zip(preds, labels): if p != l: one_sent_result = False", "slot_labels: List[List[str]], ) -> Dict[Any, Any]: assert ( len(intent_preds) ==", "slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result)", "* partial_recall / (partial_precision + partial_recall) ) exact_precision = count_exact_matches", "and gold definition spans. Let X be the number of", ") # New metrics added following Dan's request. slot_simple_result =", "of those two tags) DEF = B-Def OR I-Def Now,", "partial_fscore = ( 2 * partial_precision * partial_recall / (partial_precision", "Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels)", "None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore if not no_cuda", "len(labels) # flatten preds_flattened = [p for ps in preds", "(ie the union of those two tags) DEF = B-Def", "{} intent_result = get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result", "label_names = [\"O\", \"TERM\", \"DEF\"] p, r, f, s =", "Say a ‘partial match’ happens when the system predicts a", ") ] def set_torch_seed(seed: Any, no_cuda: bool) -> None: random.seed(seed)", "import numpy as np import torch from colorama import Fore,", "get_pos_labels(args: Any) -> List[str]: return [ label.strip() for label in", "simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels) label_names =", "exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics( preds: List[List[str]],", "List[List[str]], labels: List[List[str]]) -> Dict[Any, Any]: assert len(preds) == len(labels)", "f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p =", "import precision_score, recall_score def highlight(input_: Any) -> str: input_ =", "in ps] labels_flattened = [l for ls in labels for", "matching and the macro averaged scores conflate other things like", "list(s)} # pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\":", "highlight(input_: Any) -> str: input_ = str(input_) return str(Fore.YELLOW +", "predicts a pair <term,defn> and there is some overlap (at", "token) between the predicted and gold term spans AND there", "bool]] = [] if both_in_pred and both_in_label: for p, l", "recall_score def highlight(input_: Any) -> str: input_ = str(input_) return", "= True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) # N count_both_in_labels", "def get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]],", "] def get_pos_labels(args: Any) -> List[str]: return [ label.strip() for", "\"s\": list(s)} # pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1],", "\"\"\" assert len(preds) == len(labels) # flatten preds_flattened = [p", "TERM and {B,I}-DEF to DEF simple_preds = simplify_tokens(preds_flattened) simple_labels =", "both_in_preds.append(both_in_pred) both_in_labels.append(both_in_label) partial_match = False exact_match = False match: List[Union[str,", ") results: Dict[Any, Any] = {} intent_result = get_intent_acc(intent_preds, intent_labels)", "labels: List[str]) -> Dict[Any, Any]: acc = (preds == labels).mean()", "per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\":", "labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Conceptually, define the", "metrics and precision on O. Likewise the current macro average", "in ls] macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened,", "True if False not in match: exact_match = True partial_matches.append(partial_match)", "-> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore if not", "both_in_labels = [], [] partial_matches, exact_matches = [], [] for", "one sentence)\"\"\" # Get the intent comparison result intent_result =", "= P/M Partial match recall = P/N \"\"\" assert len(preds)", "score(simple_labels, simple_preds, average=None, labels=label_names) s = [int(si) for si in", "define the following new types of ‘virtual tags’ TERM =", "exact_match = False match: List[Union[str, bool]] = [] if both_in_pred", "get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result)", "of term and defn matching and the macro averaged scores", "+ Style.RESET_ALL) def get_intent_labels(args: Any) -> List[str]: return [ label.strip()", "count_exact_matches / count_both_in_preds exact_recall = count_exact_matches / count_both_in_labels exact_fscore =", "simple_preds def get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any,", "B-term OR I-Term (ie the union of those two tags)", "in zip(slot_preds, slot_labels): assert len(preds) == len(labels) one_sent_result = True", "pred_sent, label_sent in zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent =", "simplify by replacing {B,I}-TERM to TERM and {B,I}-DEF to DEF", "types of ‘virtual tags’ TERM = B-term OR I-Term (ie", "and \"DEF\" in match: partial_match = True if False not", "match’ happens when the system predicts a pair <term,defn> and", "system predicts M such pairs. Say a ‘partial match’ happens", "‘partial match’ happens when the system predicts a pair <term,defn>", "simple_pred_sent both_in_label = \"TERM\" in simple_label_sent and \"DEF\" in simple_label_sent", "] def get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels:", "/ count_both_in_labels exact_fscore = 2 * exact_precision * exact_recall /", "ls] macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened,", "\"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds: List[str], labels: List[str])", "slot_labels: List[List[str]], ) -> Dict[Any, Any]: \"\"\"For the cases that", "partial_precision * partial_recall / (partial_precision + partial_recall) ) exact_precision =", "labels: List[List[str]]) -> Dict[Any, Any]: assert len(preds) == len(labels) #", "= count_exact_matches / count_both_in_labels exact_fscore = 2 * exact_precision *", ") -> Dict[Any, Any]: assert ( len(intent_preds) == len(intent_labels) ==", "predicts M such pairs. Say a ‘partial match’ happens when", "pairs. Say a ‘partial match’ happens when the system predicts", "= [p for ps in preds for p in ps]", "think these matter because users may just care about accuracy", "other things like recall on these metrics and precision on", "exact_recall, \"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]]", "* partial_precision * partial_recall / (partial_precision + partial_recall) ) exact_precision", "-> Dict[Any, Any]: \"\"\"For the cases that intent and all", "-> List[str]: return [ label.strip() for label in open( os.path.join(args.data_dir,", "exist together both_in_pred = \"TERM\" in simple_pred_sent and \"DEF\" in", "slot_labels) partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result)", "np import torch from colorama import Fore, Style from sklearn.metrics", "= sum(both_in_labels) # M count_partial_matches = sum(partial_matches) # P count_exact_matches", "str(input_) + Style.RESET_ALL) def get_intent_labels(args: Any) -> List[str]: return [", "macro average treats missing the first word in a definition", "= \"TERM\" in simple_pred_sent and \"DEF\" in simple_pred_sent both_in_label =", "\"f\": list(f), \"s\": list(s)} # pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1],", "of ‘virtual tags’ TERM = B-term OR I-Term (ie the", "slots are correct (in one sentence)\"\"\" # Get the intent", "get_intent_acc(preds: List[str], labels: List[str]) -> Dict[Any, Any]: acc = (preds", "for label in open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" ) ]", "in simple_pred_sent and \"DEF\" in simple_pred_sent both_in_label = \"TERM\" in", "{B,I}-DEF to DEF simple_preds = simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert", "f = [round(float(pi), 3) for pi in f] per_class =", "= [round(float(pi), 3) for pi in p] r = [round(float(pi),", "and the macro averaged scores conflate other things like recall", "intent comparison result intent_result = intent_preds == intent_labels # Get", "when the system predicts a pair <term,defn> and there is", "# type: ignore def compute_metrics( intent_preds: List[str], intent_labels: List[str], slot_preds:", "and precision on O. Likewise the current macro average treats", "== len(slot_preds) == len(slot_labels) ) results: Dict[Any, Any] = {}", "partial_matches, exact_matches = [], [] for pred_sent, label_sent in zip(preds,", "O. Likewise the current macro average treats missing the first", "s = [int(si) for si in s] p = [round(float(pi),", "average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened,", "from sklearn.metrics import precision_recall_fscore_support as score from sklearn.metrics import precision_score,", "] def set_torch_seed(seed: Any, no_cuda: bool) -> None: random.seed(seed) np.random.seed(seed)", "list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)} # pprint(per_class) return", "one_sent_result = True for p, l in zip(preds, labels): if", "List[str]) -> List[str]: simple_preds = [] for p in preds:", "in f] per_class = {\"p\": list(p), \"r\": list(r), \"f\": list(f),", "== len(simple_labels) label_names = [\"O\", \"TERM\", \"DEF\"] p, r, f,", "else: simple_preds.append(p) return simple_preds def get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]]", "List[List[str]] ) -> Dict[Any, Any]: \"\"\" Suppose there are N", "List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any,", "\"TERM\" in simple_pred_sent and \"DEF\" in simple_pred_sent both_in_label = \"TERM\"", "False not in match: exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds", "label in open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" ) ] def", "is some overlap between the predicted and gold definition spans.", "intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], ) ->", "simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) # check whether term/def", "zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent = simplify_tokens(label_sent) # check", "preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Conceptually,", "comparison result intent_result = intent_preds == intent_labels # Get the", "( len(intent_preds) == len(intent_labels) == len(slot_preds) == len(slot_labels) ) results:", "f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p =", "= B-term OR I-Term (ie the union of those two", "New metrics added following Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels)", "in ls] # simplify by replacing {B,I}-TERM to TERM and", "as score from sklearn.metrics import precision_score, recall_score def highlight(input_: Any)", "results.update(partial_match_result) return results def simplify_tokens(preds: List[str]) -> List[str]: simple_preds =", "\"r\", encoding=\"utf-8\" ) ] def get_pos_labels(args: Any) -> List[str]: return", "DEF = B-Def OR I-Def Now, what are the P,R", "simplify_tokens(preds: List[str]) -> List[str]: simple_preds = [] for p in", "intent_labels: List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]:", "there is some overlap (at least one token) between the", "text.strip() for text in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" )", "treats missing the first word in a definition differently from", "added following Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result =", "List[List[str]]) -> Dict[Any, Any]: assert len(preds) == len(labels) # flatten", "partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, }", "average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened,", "p, r, f, s = score( labels_flattened, preds_flattened, average=None, labels=label_names", "check whether term/def exist together both_in_pred = \"TERM\" in simple_pred_sent", "pi in p] r = [round(float(pi), 3) for pi in", "average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened,", "micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"], \"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\":", "args.pos_label_file), \"r\", encoding=\"utf-8\" ) ] def set_torch_seed(seed: Any, no_cuda: bool)", "p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds def", "len(slot_preds) == len(slot_labels) ) results: Dict[Any, Any] = {} intent_result", "predicted and gold definition spans. Let X be the number", "= recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names = [\"O\", \"B-TERM\", \"I-TERM\", \"B-DEF\",", "for p in ps] labels_flattened = [l for ls in", "l: one_sent_result = False break slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc", "Partial match precision = P/M Partial match recall = P/N", "if \"TERM\" in match and \"DEF\" in match: partial_match =", "Likewise the current macro average treats missing the first word", "in r] f = [round(float(pi), 3) for pi in f]", "return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2],", "args.pred_input_file), \"r\", encoding=\"utf-8\" ) ] def get_sentence_frame_acc( intent_preds: List[str], intent_labels:", "slot_labels ) # New metrics added following Dan's request. slot_simple_result", "# check whether term/def exist together both_in_pred = \"TERM\" in", "Any] = {} intent_result = get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds,", "definition spans. Let X be the number of partial matches.", ") exact_precision = count_exact_matches / count_both_in_preds exact_recall = count_exact_matches /", "there is some overlap between the predicted and gold definition", "args.intent_label_file), \"r\", encoding=\"utf-8\" ) ] def get_slot_labels(args: Any) -> List[str]:", "# P count_exact_matches = sum(exact_matches) # E partial_precision = count_partial_matches", "P count_exact_matches = sum(exact_matches) # E partial_precision = count_partial_matches /", "Dict[Any, Any]: assert ( len(intent_preds) == len(intent_labels) == len(slot_preds) ==", "= simplify_tokens(label_sent) # check whether term/def exist together both_in_pred =", "[l for ls in labels for l in ls] #", "= f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p", "least one token) between the predicted and gold term spans", "count_both_in_labels = sum(both_in_labels) # M count_partial_matches = sum(partial_matches) # P", "OR I-Def Now, what are the P,R & F1 numbers", "\"slot_recal_per_label\": per_class[\"r\"], \"slot_f1_per_label\": per_class[\"f\"], \"slot_num_per_label\": per_class[\"s\"], } def get_intent_acc(preds: List[str],", "slot_labels) sementic_result = get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels ) #", "a pair <term,defn> and there is some overlap (at least", "Any]: assert ( len(intent_preds) == len(intent_labels) == len(slot_preds) == len(slot_labels)", "in open( os.path.join(args.data_dir, args.intent_label_file), \"r\", encoding=\"utf-8\" ) ] def get_slot_labels(args:", "P/N \"\"\" assert len(preds) == len(labels) both_in_preds, both_in_labels = [],", "these metrics and precision on O. Likewise the current macro", "str: input_ = str(input_) return str(Fore.YELLOW + str(input_) + Style.RESET_ALL)", "get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels ) # New metrics added", "Dict[Any, Any]: assert len(preds) == len(labels) # flatten preds_flattened =", "recall = P/N \"\"\" assert len(preds) == len(labels) both_in_preds, both_in_labels", ") ] def get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]],", "term/def exist together both_in_pred = \"TERM\" in simple_pred_sent and \"DEF\"", "= False match: List[Union[str, bool]] = [] if both_in_pred and", "\"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics( preds: List[List[str]], labels:", "the macro averaged scores conflate other things like recall on", "= str(input_) return str(Fore.YELLOW + str(input_) + Style.RESET_ALL) def get_intent_labels(args:", "from typing import Any, Dict, List, Union import numpy as", "\"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, } def", "\"r\": list(r), \"f\": list(f), \"s\": list(s)} # print(per_class) return {", "= [l for ls in labels for l in ls]", "List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: \"\"\"For", "preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Suppose", "import Fore, Style from sklearn.metrics import f1_score from sklearn.metrics import", "micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names = [\"O\", \"B-TERM\", \"I-TERM\",", "Any) -> List[str]: return [ text.strip() for text in open(", "preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return", "missing the first word in a definition differently from skipping", "I-Def Now, what are the P,R & F1 numbers for", "r = [round(float(pi), 3) for pi in r] f =", "macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\")", "P/M Partial match recall = P/N \"\"\" assert len(preds) ==", "label in open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" ) ] def", "Union import numpy as np import torch from colorama import", "os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" ) ] def set_torch_seed(seed: Any, no_cuda:", "labels in zip(slot_preds, slot_labels): assert len(preds) == len(labels) one_sent_result =", "List[str]: simple_preds = [] for p in preds: if p.endswith(\"TERM\"):", "= f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p", "in p] r = [round(float(pi), 3) for pi in r]", "both_in_preds, both_in_labels = [], [] partial_matches, exact_matches = [], []", "Any]: acc = (preds == labels).mean() return {\"intent_acc\": acc} def", "str(input_) return str(Fore.YELLOW + str(input_) + Style.RESET_ALL) def get_intent_labels(args: Any)", "colorama import Fore, Style from sklearn.metrics import f1_score from sklearn.metrics", "a definition differently from skipping the last word. \"\"\" assert", "len(preds) == len(labels) # flatten preds_flattened = [p for ps", "\"\"\"For the cases that intent and all the slots are", "Any) -> str: input_ = str(input_) return str(Fore.YELLOW + str(input_)", "precision = P/M Partial match recall = P/N \"\"\" assert", "[], [] partial_matches, exact_matches = [], [] for pred_sent, label_sent", "List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: \"\"\"For the cases", "True for p, l in zip(preds, labels): if p !=", "in zip(simple_pred_sent, simple_label_sent): if p == l: match.append(p) else: match.append(False)", "the predicted and gold definition spans. Let X be the", "for ps in preds for p in ps] labels_flattened =", "List[List[str]], ) -> Dict[Any, Any]: assert ( len(intent_preds) == len(intent_labels)", "get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results def", "encoding=\"utf-8\" ) ] def get_slot_labels(args: Any) -> List[str]: return [", "ls in labels for l in ls] macro_f1 = f1_score(labels_flattened,", "p] r = [round(float(pi), 3) for pi in r] f", "List[List[str]], ) -> Dict[Any, Any]: \"\"\"For the cases that intent", "len(intent_labels) == len(slot_preds) == len(slot_labels) ) results: Dict[Any, Any] =", "partial_recall / (partial_precision + partial_recall) ) exact_precision = count_exact_matches /", "pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\":", "What are Partial match precision = P/M Partial match recall", "= get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels", "that intent and all the slots are correct (in one", "return str(Fore.YELLOW + str(input_) + Style.RESET_ALL) def get_intent_labels(args: Any) ->", "M count_partial_matches = sum(partial_matches) # P count_exact_matches = sum(exact_matches) #", "List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Conceptually, define", "accuracy of term and defn matching and the macro averaged", ") -> Dict[Any, Any]: \"\"\"For the cases that intent and", "for p, l in zip(preds, labels): if p != l:", "comparision result slot_result = [] for preds, labels in zip(slot_preds,", "of partial matches. What are Partial match precision = P/M", "count_both_in_preds partial_recall = count_partial_matches / count_both_in_labels partial_fscore = ( 2", "return { \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision,", "Any, Dict, List, Union import numpy as np import torch", "Now, what are the P,R & F1 numbers for TERM", "= {} intent_result = get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels)", "get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc( intent_preds,", "False match: List[Union[str, bool]] = [] if both_in_pred and both_in_label:", "macro_p = precision_score(labels_flattened, preds_flattened, average=\"macro\") micro_p = precision_score(labels_flattened, preds_flattened, average=\"micro\")", "average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened, preds_flattened,", "= sum(partial_matches) # P count_exact_matches = sum(exact_matches) # E partial_precision", "False exact_match = False match: List[Union[str, bool]] = [] if", "in preds for p in ps] labels_flattened = [l for", "simple_pred_sent and \"DEF\" in simple_pred_sent both_in_label = \"TERM\" in simple_label_sent", "\"r\", encoding=\"utf-8\" ) ] def get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str],", "label in open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\" ) ] def", "type: ignore def compute_metrics( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]],", "matches. What are Partial match precision = P/M Partial match", "List[str], slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: assert", "AND there is some overlap between the predicted and gold", "slot_labels): assert len(preds) == len(labels) one_sent_result = True for p,", "in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p)", "for l in ls] # simplify by replacing {B,I}-TERM to", "= False exact_match = False match: List[Union[str, bool]] = []", "\"B-TERM\", \"I-TERM\", \"B-DEF\", \"I-DEF\"] p, r, f, s = score(", "(exact_precision + exact_recall) return { \"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\":", "len(preds) == len(labels) one_sent_result = True for p, l in", "from sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support as score", "the system predicts a pair <term,defn> and there is some", "= simplify_tokens(preds_flattened) simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels) label_names", "in match: partial_match = True if False not in match:", "both_in_label = \"TERM\" in simple_label_sent and \"DEF\" in simple_label_sent both_in_preds.append(both_in_pred)", "intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc( intent_preds, intent_labels,", "] def get_slot_labels(args: Any) -> List[str]: return [ label.strip() for", "match.append(False) if \"TERM\" in match and \"DEF\" in match: partial_match", "(preds == labels).mean() return {\"intent_acc\": acc} def read_prediction_text(args: Any) ->", "[ text.strip() for text in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\"", "\"TERM\" in match and \"DEF\" in match: partial_match = True", "spans AND there is some overlap between the predicted and", "if p == l: match.append(p) else: match.append(False) if \"TERM\" in", "= ( 2 * partial_precision * partial_recall / (partial_precision +", "definition differently from skipping the last word. \"\"\" assert len(preds)", "ignore def compute_metrics( intent_preds: List[str], intent_labels: List[str], slot_preds: List[List[str]], slot_labels:", "results def simplify_tokens(preds: List[str]) -> List[str]: simple_preds = [] for", "TERM and DEF? (I think these matter because users may", "Suppose there are N such pairs in the gold data", "system predicts a pair <term,defn> and there is some overlap", "return simple_preds def get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]] ) ->", "the intent comparison result intent_result = intent_preds == intent_labels #", "count_both_in_labels partial_fscore = ( 2 * partial_precision * partial_recall /", "Dict[Any, Any]: acc = (preds == labels).mean() return {\"intent_acc\": acc}", "= (preds == labels).mean() return {\"intent_acc\": acc} def read_prediction_text(args: Any)", "exact_recall = count_exact_matches / count_both_in_labels exact_fscore = 2 * exact_precision", "match: List[Union[str, bool]] = [] if both_in_pred and both_in_label: for", "bool) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore if", "open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" ) ] def set_torch_seed(seed: Any,", "\"partial_match_precision\": partial_precision, \"partial_match_recall\": partial_recall, \"partial_match_f1\": partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall,", "= score(simple_labels, simple_preds, average=None, labels=label_names) s = [int(si) for si", "== intent_labels # Get the slot comparision result slot_result =", "between the predicted and gold term spans AND there is", "== labels).mean() return {\"intent_acc\": acc} def read_prediction_text(args: Any) -> List[str]:", "score( labels_flattened, preds_flattened, average=None, labels=label_names ) s = [int(si) for", "slot_preds: List[List[str]], slot_labels: List[List[str]], ) -> Dict[Any, Any]: \"\"\"For the", "(I think these matter because users may just care about", "defn matching and the macro averaged scores conflate other things", "/ count_both_in_preds partial_recall = count_partial_matches / count_both_in_labels partial_fscore = (", "List[str]: return [ label.strip() for label in open( os.path.join(args.data_dir, args.pos_label_file),", "zip(simple_pred_sent, simple_label_sent): if p == l: match.append(p) else: match.append(False) if", "exact_fscore, } def get_slot_simple_metrics( preds: List[List[str]], labels: List[List[str]] ) ->", "Any]: \"\"\" Conceptually, define the following new types of ‘virtual", "averaged scores conflate other things like recall on these metrics", "get_slot_metrics(slot_preds, slot_labels) sementic_result = get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels )", "for si in s] p = [round(float(pi), 3) for pi", "list(f), \"s\": list(s)} # pprint(per_class) return { \"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\":", "results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results def simplify_tokens(preds: List[str])", "the last word. \"\"\" assert len(preds) == len(labels) # flatten", "sementic_result = get_sentence_frame_acc( intent_preds, intent_labels, slot_preds, slot_labels ) # New", "result slot_result = [] for preds, labels in zip(slot_preds, slot_labels):", "pairs in the gold data and the system predicts M", "on O. Likewise the current macro average treats missing the", "in match: exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds)", "[round(float(pi), 3) for pi in p] r = [round(float(pi), 3)", "str(Fore.YELLOW + str(input_) + Style.RESET_ALL) def get_intent_labels(args: Any) -> List[str]:", "may just care about accuracy of term and defn matching", "len(labels) one_sent_result = True for p, l in zip(preds, labels):", "cases that intent and all the slots are correct (in", "label.strip() for label in open( os.path.join(args.data_dir, args.pos_label_file), \"r\", encoding=\"utf-8\" )", "return [ text.strip() for text in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\",", "partial_fscore, \"exact_match_precision\": exact_precision, \"excat_match_recall\": exact_recall, \"excat_match_f1\": exact_fscore, } def get_slot_simple_metrics(", "match recall = P/N \"\"\" assert len(preds) == len(labels) both_in_preds,", "True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) # N count_both_in_labels =", "pi in f] per_class = {\"p\": list(p), \"r\": list(r), \"f\":", "Any, no_cuda: bool) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type:", "labels=label_names ) s = [int(si) for si in s] p", "and all the slots are correct (in one sentence)\"\"\" #", "for pred_sent, label_sent in zip(preds, labels): simple_pred_sent = simplify_tokens(pred_sent) simple_label_sent", "torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore def compute_metrics( intent_preds: List[str], intent_labels:", "else: match.append(False) if \"TERM\" in match and \"DEF\" in match:", "\"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]], labels: List[List[str]])", "List[str]) -> Dict[Any, Any]: acc = (preds == labels).mean() return", "exact_precision * exact_recall / (exact_precision + exact_recall) return { \"partial_match_precision\":", "simple_label_sent): if p == l: match.append(p) else: match.append(False) if \"TERM\"", "p = [round(float(pi), 3) for pi in p] r =", "/ (partial_precision + partial_recall) ) exact_precision = count_exact_matches / count_both_in_preds", "sum(both_in_labels) # M count_partial_matches = sum(partial_matches) # P count_exact_matches =", "list(f), \"s\": list(s)} # print(per_class) return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\":", "both_in_pred and both_in_label: for p, l in zip(simple_pred_sent, simple_label_sent): if", "two tags) DEF = B-Def OR I-Def Now, what are", "flatten preds_flattened = [p for ps in preds for p", "def get_intent_labels(args: Any) -> List[str]: return [ label.strip() for label", "{\"p\": list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)} # pprint(per_class)", "zip(slot_preds, slot_labels): assert len(preds) == len(labels) one_sent_result = True for", "s = score( labels_flattened, preds_flattened, average=None, labels=label_names ) s =", "partial_match_result = get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return", "Partial match recall = P/N \"\"\" assert len(preds) == len(labels)", "text in open( os.path.join(args.pred_dir, args.pred_input_file), \"r\", encoding=\"utf-8\" ) ] def", "= get_partial_match_metrics(slot_preds, slot_labels) results.update(intent_result) results.update(slot_result) results.update(sementic_result) results.update(slot_simple_result) results.update(partial_match_result) return results", "Dict[Any, Any]: \"\"\"For the cases that intent and all the", "import Any, Dict, List, Union import numpy as np import", "\"s\": list(s)} # print(per_class) return { \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r,", "intent and all the slots are correct (in one sentence)\"\"\"", "word. \"\"\" assert len(preds) == len(labels) # flatten preds_flattened =", "macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\":", "encoding=\"utf-8\" ) ] def get_pos_labels(args: Any) -> List[str]: return [", "3) for pi in p] r = [round(float(pi), 3) for", "intent_result = get_intent_acc(intent_preds, intent_labels) slot_result = get_slot_metrics(slot_preds, slot_labels) sementic_result =", "\"\"\" Conceptually, define the following new types of ‘virtual tags’", "if not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore def", "labels).mean() return {\"intent_acc\": acc} def read_prediction_text(args: Any) -> List[str]: return", "def get_slot_labels(args: Any) -> List[str]: return [ label.strip() for label", "get_slot_metrics(preds: List[List[str]], labels: List[List[str]]) -> Dict[Any, Any]: assert len(preds) ==", "-> str: input_ = str(input_) return str(Fore.YELLOW + str(input_) +", "preds, labels in zip(slot_preds, slot_labels): assert len(preds) == len(labels) one_sent_result", "simple_preds = [] for p in preds: if p.endswith(\"TERM\"): simple_preds.append(\"TERM\")", "\"slot_merged_TERM_precision\": per_class[\"p\"][1], \"slot_merged_TERM_recall\": per_class[\"r\"][1], \"slot_merged_TERM_f1\": per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2],", "ls in labels for l in ls] # simplify by", "{B,I}-TERM to TERM and {B,I}-DEF to DEF simple_preds = simplify_tokens(preds_flattened)", "not in match: exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds =", "care about accuracy of term and defn matching and the", "match precision = P/M Partial match recall = P/N \"\"\"", "for pi in f] per_class = {\"p\": list(p), \"r\": list(r),", "Fore, Style from sklearn.metrics import f1_score from sklearn.metrics import precision_recall_fscore_support", "= True for p, l in zip(preds, labels): if p", "<term,defn> and there is some overlap (at least one token)", "slot_result.append(one_sent_result) slot_result = np.array(slot_result) sementic_acc = np.multiply(intent_result, slot_result).mean() return {\"sementic_frame_acc\":", "precision_score, recall_score def highlight(input_: Any) -> str: input_ = str(input_)", "the current macro average treats missing the first word in", "= precision_score(labels_flattened, preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r", "word in a definition differently from skipping the last word.", "some overlap (at least one token) between the predicted and", "X be the number of partial matches. What are Partial", "[p for ps in preds for p in ps] labels_flattened", "preds_flattened, average=\"micro\") macro_r = recall_score(labels_flattened, preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened,", "Any]: assert len(preds) == len(labels) # flatten preds_flattened = [p", "return {\"intent_acc\": acc} def read_prediction_text(args: Any) -> List[str]: return [", "/ count_both_in_labels partial_fscore = ( 2 * partial_precision * partial_recall", "os import random from typing import Any, Dict, List, Union", "metrics added following Dan's request. slot_simple_result = get_slot_simple_metrics(slot_preds, slot_labels) partial_match_result", "\"\"\" assert len(preds) == len(labels) both_in_preds, both_in_labels = [], []", "the gold data and the system predicts M such pairs.", "the P,R & F1 numbers for TERM and DEF? (I", "= [\"O\", \"TERM\", \"DEF\"] p, r, f, s = score(simple_labels,", "random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) # type: ignore if not no_cuda and", "-> Dict[Any, Any]: acc = (preds == labels).mean() return {\"intent_acc\":", "I-Term (ie the union of those two tags) DEF =", "for p, l in zip(simple_pred_sent, simple_label_sent): if p == l:", "= count_exact_matches / count_both_in_preds exact_recall = count_exact_matches / count_both_in_labels exact_fscore", "union of those two tags) DEF = B-Def OR I-Def", "per_class[\"s\"], } def get_intent_acc(preds: List[str], labels: List[str]) -> Dict[Any, Any]:", "= count_partial_matches / count_both_in_labels partial_fscore = ( 2 * partial_precision", "assert ( len(intent_preds) == len(intent_labels) == len(slot_preds) == len(slot_labels) )", "match: exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match) count_both_in_preds = sum(both_in_preds) #", "preds_flattened, average=\"macro\") micro_f1 = f1_score(labels_flattened, preds_flattened, average=\"micro\") macro_p = precision_score(labels_flattened,", "preds_flattened, average=\"macro\") micro_r = recall_score(labels_flattened, preds_flattened, average=\"micro\") label_names = [\"O\",", "3) for pi in f] per_class = {\"p\": list(p), \"r\":", "# Get the slot comparision result slot_result = [] for", "last word. \"\"\" assert len(preds) == len(labels) # flatten preds_flattened", "== len(slot_labels) ) results: Dict[Any, Any] = {} intent_result =", "whether term/def exist together both_in_pred = \"TERM\" in simple_pred_sent and", "both_in_pred = \"TERM\" in simple_pred_sent and \"DEF\" in simple_pred_sent both_in_label", "= P/N \"\"\" assert len(preds) == len(labels) both_in_preds, both_in_labels =", "‘virtual tags’ TERM = B-term OR I-Term (ie the union", "a ‘partial match’ happens when the system predicts a pair", "/ count_both_in_preds exact_recall = count_exact_matches / count_both_in_labels exact_fscore = 2", "l in ls] macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1 =", "acc} def read_prediction_text(args: Any) -> List[str]: return [ text.strip() for", "return results def simplify_tokens(preds: List[str]) -> List[str]: simple_preds = []", "E partial_precision = count_partial_matches / count_both_in_preds partial_recall = count_partial_matches /", "average=None, labels=label_names ) s = [int(si) for si in s]", "typing import Any, Dict, List, Union import numpy as np", "r, f, s = score(simple_labels, simple_preds, average=None, labels=label_names) s =", "simple_labels = simplify_tokens(labels_flattened) assert len(simple_preds) == len(simple_labels) label_names = [\"O\",", "# N count_both_in_labels = sum(both_in_labels) # M count_partial_matches = sum(partial_matches)", "intent_preds == intent_labels # Get the slot comparision result slot_result", "if False not in match: exact_match = True partial_matches.append(partial_match) exact_matches.append(exact_match)", "per_class[\"f\"][1], \"slot_merged_DEFINITION_precision\": per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds:", "slot comparision result slot_result = [] for preds, labels in", "one token) between the predicted and gold term spans AND", "Get the intent comparison result intent_result = intent_preds == intent_labels", "precision_recall_fscore_support as score from sklearn.metrics import precision_score, recall_score def highlight(input_:", "torch.manual_seed(seed) # type: ignore if not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)", "assert len(preds) == len(labels) both_in_preds, both_in_labels = [], [] partial_matches,", "sum(exact_matches) # E partial_precision = count_partial_matches / count_both_in_preds partial_recall =", "= B-Def OR I-Def Now, what are the P,R &", "term and defn matching and the macro averaged scores conflate", "for ls in labels for l in ls] macro_f1 =", "ignore if not no_cuda and torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) # type: ignore", "per_class[\"p\"][2], \"slot_merged_DEFINITION_recall\": per_class[\"r\"][2], \"slot_merged_DEFINITION_f1\": per_class[\"f\"][2], } def get_slot_metrics(preds: List[List[str]], labels:", "labels for l in ls] macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\")", "\"r\": list(r), \"f\": list(f), \"s\": list(s)} # pprint(per_class) return {", "in labels for l in ls] # simplify by replacing", "[ label.strip() for label in open( os.path.join(args.data_dir, args.slot_label_file), \"r\", encoding=\"utf-8\"", "from skipping the last word. \"\"\" assert len(preds) == len(labels)", "len(labels) both_in_preds, both_in_labels = [], [] partial_matches, exact_matches = [],", "== len(labels) both_in_preds, both_in_labels = [], [] partial_matches, exact_matches =", "to TERM and {B,I}-DEF to DEF simple_preds = simplify_tokens(preds_flattened) simple_labels", "get_partial_match_metrics( preds: List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\"", "* exact_precision * exact_recall / (exact_precision + exact_recall) return {", "list(p), \"r\": list(r), \"f\": list(f), \"s\": list(s)} # print(per_class) return", "{ \"slot_precision_macro\": macro_p, \"slot_recall_macro\": macro_r, \"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\":", "the union of those two tags) DEF = B-Def OR", "for l in ls] macro_f1 = f1_score(labels_flattened, preds_flattened, average=\"macro\") micro_f1", "assert len(preds) == len(labels) one_sent_result = True for p, l", "\"B-DEF\", \"I-DEF\"] p, r, f, s = score( labels_flattened, preds_flattened,", "encoding=\"utf-8\" ) ] def set_torch_seed(seed: Any, no_cuda: bool) -> None:", "encoding=\"utf-8\" ) ] def get_sentence_frame_acc( intent_preds: List[str], intent_labels: List[str], slot_preds:", "count_both_in_preds = sum(both_in_preds) # N count_both_in_labels = sum(both_in_labels) # M", "from colorama import Fore, Style from sklearn.metrics import f1_score from", "labels=label_names) s = [int(si) for si in s] p =", "are the P,R & F1 numbers for TERM and DEF?", "conflate other things like recall on these metrics and precision", "p, l in zip(preds, labels): if p != l: one_sent_result", "\"I-DEF\"] p, r, f, s = score( labels_flattened, preds_flattened, average=None,", "simple_preds.append(\"TERM\") elif p.endswith(\"DEF\"): simple_preds.append(\"DEF\") else: simple_preds.append(p) return simple_preds def get_partial_match_metrics(", "if both_in_pred and both_in_label: for p, l in zip(simple_pred_sent, simple_label_sent):", "def simplify_tokens(preds: List[str]) -> List[str]: simple_preds = [] for p", "pair <term,defn> and there is some overlap (at least one", "l in zip(simple_pred_sent, simple_label_sent): if p == l: match.append(p) else:", "\"slot_f1_macro\": macro_f1, \"slot_precision_micro\": micro_p, \"slot_recall_micro\": micro_r, \"slot_f1_micro\": micro_f1, \"slot_precision_per_label\": per_class[\"p\"],", "List[List[str]], labels: List[List[str]] ) -> Dict[Any, Any]: \"\"\" Suppose there" ]
[ "the command. Returns: A string representing a Fire CLI command", "during a single Fire execution. A FireTrace consists of a", "= FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name = name self.separator =", "Here's an example to demonstrate the separator. Let's say you", "insufficient arguments being provided to call a function, then that", "Whether the callable could have accepted additional args. action: The", "is defined, or None if N/A. capacity: (bool) Whether the", "then that error will be captured in the trace and", "2.0 (the \"License\"); # you may not use this file", "Bash (the default separator is the hyphen -) display hello", "if arg.startswith('--') and '=' in arg: prefix, value = arg.split('=',", "self._lineno is not None: path += ':{lineno}'.format(lineno=self._lineno) string += '", "whether a the trace need '--' before '--help'. '--' is", "ErrorAsStr(self): return ' '.join(str(arg) for arg in self._error.args) def __str__(self):", "self._capacity def HasSeparator(self): return self._separator def AddSeparator(self): self._separator = True", "one of the argument of the component, or the component", "self._filename if self._lineno is not None: path += ':{lineno}'.format(lineno=self._lineno) string", "by the represented action. filename: The file in which the", "AddCalledComponent(self, component, target, args, filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an", "routine, or accessing a property. Each action consumes args and", "If a Fire usage error occurs, such as insufficient arguments", "'--' before '--help'. '--' is needed when the component takes", "an example to demonstrate the separator. Let's say you have", "hello - upper # HELLO! Note how the separator caused", "for arg in self._error.args) def __str__(self): if self.HasError(): return self.ErrorAsStr()", "GetCommand(self, include_separators=True): \"\"\"Returns the command representing the trace up to", "mode' class FireTrace(object): \"\"\"A FireTrace represents the steps taken during", "called. Also applies to instantiating a class. Args: component: The", "= FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks that the most", "of a Fire execution. A FireTrace consists of a sequence", "fire import inspectutils INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS = 'Instantiated", "error occurs, such as insufficient arguments being provided to call", "= lineno self._error = error self._separator = False self._capacity =", "Fire CLI to separate args left of the separator from", "call itself. Returns: Whether a separator should be added to", "capacity: (bool) Whether the action could have accepted additional args.", "def GetCommand(self, include_separators=True): \"\"\"Returns the command representing the trace up", "AddSeparator(self): self._separator = True def ErrorAsStr(self): return ' '.join(str(arg) for", "will be captured in the trace and the final component", "single Fire execution. A FireTrace consists of a sequence of", "\"\"\"This module has classes for tracing the execution of a", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "property' COMPLETION_SCRIPT = 'Generated completion script' INTERACTIVE_MODE = 'Entered interactive", "component, target, args, filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an element", "not None or flag in spec.args or flag in spec.kwonlyargs)", "# pytype: disable=attribute-error return self.GetLastHealthyElement().component # pytype: enable=attribute-error def GetLastHealthyElement(self):", "= args self._filename = filename self._lineno = lineno self._error =", "value). Args: flag: the flag available for the trace Returns:", "or flag in spec.args or flag in spec.kwonlyargs) class FireTraceElement(object):", "= target self.args = args self._filename = filename self._lineno =", "def AddCompletionScript(self, script): element = FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element)", "represents the steps taken during a single Fire execution. A", "by the Fire method. If a Fire usage error occurs,", "to be called with the default value for arg2. \"\"\"", "= 'Initial component' INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE = 'Called", "class FireTraceElement(object): \"\"\"A FireTraceElement represents a single step taken by", "= [initial_trace_element] self.verbose = verbose self.show_help = show_help self.show_trace =", "this point. Args: include_separators: Whether or not to include separators", "trace_string=element, ) lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether", "with default value). Args: flag: the flag available for the", "of a sequence of FireTraceElement objects. Each element represents an", "or None if N/A. capacity: (bool) Whether the action could", "if N/A. capacity: (bool) Whether the action could have accepted", "flag='help'): \"\"\"Returns whether a the trace need '--' before '--help'.", "FireTrace represents the steps taken during a single Fire execution.", "a class. Args: component: The result of calling the callable.", "to this point. Args: include_separators: Whether or not to include", "arg to the function call, and sometimes would add an", "needed '--', False otherwise. \"\"\" element = self.GetLastHealthyElement() component =", "number on which the callable is defined, or None if", "if self._lineno is not None: path += ':{lineno}'.format(lineno=self._lineno) string +=", "self.name = name self.separator = separator self.elements = [initial_trace_element] self.verbose", "pytype: disable=attribute-error return self.GetLastHealthyElement().component # pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns", "self.verbose = verbose self.show_help = show_help self.show_trace = show_trace def", "have accepted additional args. action: The value to include as", "the callable could have accepted additional args. action: The value", "consumes args and results in a new component. The final", "results in a new component. The final component is serialized", "args left of the separator from args right of the", "the final component indicated by the trace. Returns: The last", "accessing of an object member. \"\"\" def __init__(self, component=None, action=None,", "if N/A. lineno: The line number on which the action", "calling a routine, or accessing a property. \"\"\" def __init__(self,", "use this file except in compliance with the License. #", "would add an extra arg to the function call, and", "class, calling a routine, or accessing a property. \"\"\" def", "is needed when the component takes keyword arguments, when the", "keyword-only arguments(e.g. argument with default value). Args: flag: the flag", "the callable. target: The name of the callable. args: The", "callable. filename: The file in which the callable is defined,", "left of the separator from args right of the separator.", "how the separator caused the display function to be called", "capacity=None): \"\"\"Instantiates a FireTraceElement. Args: component: The result of this", "= 'Called callable' ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT = 'Generated", "self.elements: if element.HasError(): continue if element.args: args.extend(element.args) if element.HasSeparator() and", "+ '=' + pipes.quote(value) return pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns", "The name of the component being acted upon. args: The", "self._error is not None def HasCapacity(self): return self._capacity def HasSeparator(self):", "argument with default value). Args: flag: the flag available for", "arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg): if arg.startswith('--') and '='", "and sometimes would add an arg acting on the result", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "provided to call a function, then that error will be", "may be instantiating a class, calling a routine, or accessing", "element will contain the final component indicated by the trace.", "and then upper case the result. Here's how to do", "the command. If the command is a function call, then", "a separator should be added to the command if order", "License. # You may obtain a copy of the License", "should be added to the command if order to keep", "upon. args: The args consumed by the represented action. filename:", "\"\"\"Returns the component from the last element of the trace.\"\"\"", "FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error, args): element = FireTraceElement(error=error, args=args)", "the action is defined, or None if N/A. error: The", "is not None def HasCapacity(self): return self._capacity def HasSeparator(self): return", "= 'Entered interactive mode' class FireTrace(object): \"\"\"A FireTrace represents the", "self.GetLastHealthyElement() return element.HasCapacity() and not element.HasSeparator() def __str__(self): lines =", "action: The value to include as the action in the", "self.ErrorAsStr() else: # Format is: {action} \"{target}\" ({filename}:{lineno}) string =", "def AddSeparator(self): self._separator = True def ErrorAsStr(self): return ' '.join(str(arg)", "= [] if self.name: args.append(self.name) for element in self.elements: if", "False otherwise. \"\"\" element = self.GetLastHealthyElement() component = element.component spec", "under the License is distributed on an \"AS IS\" BASIS,", "have a function that takes a variable number of args,", "then upper case the result. Here's how to do it:", "result. Here's how to do it: # in Python def", "License for the specific language governing permissions and # limitations", "if element.HasSeparator() and include_separators: args.append(self.separator) if self.NeedsSeparator() and include_separators: args.append(self.separator)", "keep the component referred to by the command the same", "action in the FireTraceElement. \"\"\" element = FireTraceElement( component=component, action=action,", "error self._separator = False self._capacity = capacity def HasError(self): return", "command sometimes would add an extra arg to the function", "is an argument you can pass to a Fire CLI", "if self._filename is not None: path = self._filename if self._lineno", "can pass to a Fire CLI to separate args left", "execution. An action may be instantiating a class, calling a", "flag: the flag available for the trace Returns: True for", "default value). Args: flag: the flag available for the trace", "(bool) Whether the callable could have accepted additional args. action:", "\"\"\"Returns the command representing the trace up to this point.", "__init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates", "element.component spec = inspectutils.GetFullArgSpec(component) return (spec.varkw is not None or", "component being acted upon. args: The args consumed by the", "args): element = FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks that", "hyphen -) display hello # hello! display hello upper #", "the same when adding additional args. \"\"\" element = self.GetLastHealthyElement()", "and include_separators: args.append(self.separator) if self.NeedsSeparator() and include_separators: args.append(self.separator) return '", "N/A. error: The error represented by the action, or None", "ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT = 'Generated completion script' INTERACTIVE_MODE", "= 'Generated completion script' INTERACTIVE_MODE = 'Entered interactive mode' class", "prefix, value = arg.split('=', 1) return pipes.quote(prefix) + '=' +", "for the trace Returns: True for needed '--', False otherwise.", "by a Fire execution. Examples of a FireTraceElement are the", "of the trace. action: The type of action (eg instantiating", "new component. The final component is serialized to stdout by", "args=args, filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self, script): element", "Fire as well as returned by the Fire method. If", "Returns: A string representing a Fire CLI command that would", "(spec.varkw is not None or flag in spec.args or flag", "the trace that is not an error. This element will", "args consumed in order to call this callable. filename: The", "= self._action if self._target is not None: string += '", "include_separators: args.append(self.separator) if self.NeedsSeparator() and include_separators: args.append(self.separator) return ' '.join(self._Quote(arg)", "a Fire CLI to separate args left of the separator", "the most recent element of the trace used a separator.", "from __future__ import absolute_import from __future__ import division from __future__", "'=' + pipes.quote(value) return pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns the", "the FireTraceElement. \"\"\" element = FireTraceElement( component=component, action=action, target=target, args=args,", "None: string += ' \"{target}\"'.format(target=self._target) if self._filename is not None:", "CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT =", "in compliance with the License. # You may obtain a", "want to call that function, and then upper case the", "to call that function, and then upper case the result.", "element.HasSeparator() and include_separators: args.append(self.separator) if self.NeedsSeparator() and include_separators: args.append(self.separator) return", "action=INITIAL_COMPONENT, ) self.name = name self.separator = separator self.elements =", "takes keyword arguments, when the value of flag matches one", "software # distributed under the License is distributed on an", "the trace Returns: True for needed '--', False otherwise. \"\"\"", "stdout by Fire as well as returned by the Fire", "The line number on which the action is defined, or", "the function call. This function tells us whether we should", "arguments being provided to call a function, then that error", "The final component is serialized to stdout by Fire as", "of calling the callable. target: The name of the callable.", "display(arg1, arg2='!'): return arg1 + arg2 # from Bash (the", "+ 1, trace_string=element, ) lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'):", "element in enumerate(self.elements): line = '{index}. {trace_string}'.format( index=index + 1,", "'--' is needed when the component takes keyword arguments, when", "None def HasCapacity(self): return self._capacity def HasSeparator(self): return self._separator def", "point. Args: include_separators: Whether or not to include separators in", "__future__ import print_function import pipes from fire import inspectutils INITIAL_COMPONENT", "contain the final component indicated by the trace. Returns: The", "the command sometimes would add an extra arg to the", "taking place. target: (string) The name of the component being", "capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self, script): element = FireTraceElement( component=script,", "error: The error represented by the action, or None if", "class. Args: component: The result of calling the callable. target:", "whether the Fire execution encountered a Fire usage error.\"\"\" return", "arg1 + arg2 # from Bash (the default separator is", "is: {action} \"{target}\" ({filename}:{lineno}) string = self._action if self._target is", "the separator. Here's an example to demonstrate the separator. Let's", "and you want to call that function, and then upper", "Fire execution encountered a Fire usage error.\"\"\" return self.elements[-1].HasError() def", "trace.\"\"\" # pytype: disable=attribute-error return self.GetLastHealthyElement().component # pytype: enable=attribute-error def", "not an error. \"\"\" for element in reversed(self.elements): if not", "None if N/A. capacity: (bool) Whether the callable could have", "The file in which the callable is defined, or None", "index=index + 1, trace_string=element, ) lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self,", "usage error occurs, such as insufficient arguments being provided to", "place. target: (string) The name of the component being acted", "have accepted additional args. \"\"\" self.component = component self._action =", "permissions and # limitations under the License. \"\"\"This module has", "self._separator = False self._capacity = capacity def HasError(self): return self._error", "GetResult(self): \"\"\"Returns the component from the last element of the", "args, and you want to call that function, and then", "function call, then adding an additional argument to the command", "separate args left of the separator from args right of", "(bool) Whether the action could have accepted additional args. \"\"\"", "capacity def HasError(self): return self._error is not None def HasCapacity(self):", "self._action if self._target is not None: string += ' \"{target}\"'.format(target=self._target)", "= 'Called routine' CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY = 'Accessed", "= arg.split('=', 1) return pipes.quote(prefix) + '=' + pipes.quote(value) return", "in args) def NeedsSeparator(self): \"\"\"Returns whether a separator should be", "def AddSeparator(self): \"\"\"Marks that the most recent element of the", "FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name = name self.separator = separator", "to separate args left of the separator from args right", "add an arg acting on the result of the function", "Also applies to instantiating a class. Args: component: The result", "Fire execution. Examples of a FireTraceElement are the instantiation of", "error represented by the action, or None if N/A. capacity:", "an extra arg to the function call, and sometimes would", "[] for index, element in enumerate(self.elements): line = '{index}. {trace_string}'.format(", "= FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self): element =", "component will be None. \"\"\" from __future__ import absolute_import from", "None. \"\"\" from __future__ import absolute_import from __future__ import division", "steps taken during a single Fire execution. A FireTrace consists", "for index, element in enumerate(self.elements): line = '{index}. {trace_string}'.format( index=index", "itself. Returns: Whether a separator should be added to the", "a class, calling a routine, or accessing a property. \"\"\"", "script): element = FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self):", "command before adding additional arguments in order to make sure", "an element to the trace indicating that a component was", "to the command if order to keep the component referred", "serialized to stdout by Fire as well as returned by", "trace used a separator. A separator is an argument you", "target, args, filename, lineno): element = FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target,", "string = self._action if self._target is not None: string +=", "not the function call itself. Returns: Whether a separator should", "action consumes args and results in a new component. The", "callable is defined, or None if N/A. lineno: The line", "if self.HasError(): return self.ErrorAsStr() else: # Format is: {action} \"{target}\"", "self.GetLastHealthyElement().component # pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the last element", "= error self._separator = False self._capacity = capacity def HasError(self):", "callable is defined, or None if N/A. capacity: (bool) Whether", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "to the result of the function call, and not the", "of action (eg instantiating a class) taking place. target: (string)", "N/A. capacity: (bool) Whether the action could have accepted additional", "lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a the", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "Each element represents an action taken by Fire during a", "representing the trace up to this point. Args: include_separators: Whether", "component referred to by the command the same when adding", "def HasCapacity(self): return self._capacity def HasSeparator(self): return self._separator def AddSeparator(self):", "to instantiating a class. Args: component: The result of calling", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "if element.args: args.extend(element.args) if element.HasSeparator() and include_separators: args.append(self.separator) if self.NeedsSeparator()", "the component takes keyword arguments, when the value of flag", "element to the trace indicating that a component was called.", "({filename}:{lineno}) string = self._action if self._target is not None: string", "call. This function tells us whether we should add a", "to in writing, software # distributed under the License is", "of this element of the trace. action: The type of", "class or the accessing of an object member. \"\"\" def", "default value for arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg): if", "Args: component: The result of calling the callable. target: The", "a Fire execution. A FireTrace consists of a sequence of", "args, filename, lineno): element = FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args,", "taken by Fire during a single Fire execution. An action", "be added to the command. If the command is a", "# See the License for the specific language governing permissions", "tells us whether we should add a separator to the", "\"\"\" element = self.GetLastHealthyElement() return element.HasCapacity() and not element.HasSeparator() def", "return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a the trace", "recent element of the trace used a separator. A separator", "command. If the command is a function call, then adding", "filename self._lineno = lineno self._error = error self._separator = False", "in arg: prefix, value = arg.split('=', 1) return pipes.quote(prefix) +", "or agreed to in writing, software # distributed under the", "filename=filename, lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self, component, target, args, filename,", "include_separators=True): \"\"\"Returns the command representing the trace up to this", "print_function import pipes from fire import inspectutils INITIAL_COMPONENT = 'Initial", "make sure the arg is applied to the result of", "required by applicable law or agreed to in writing, software", "property. Each action consumes args and results in a new", "well as returned by the Fire method. If a Fire", "display hello upper # helloupper display hello - upper #", "args.append(self.separator) return ' '.join(self._Quote(arg) for arg in args) def NeedsSeparator(self):", "a the trace need '--' before '--help'. '--' is needed", "spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement represents a single step taken", "= filename self._lineno = lineno self._error = error self._separator =", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "an argument you can pass to a Fire CLI to", "when the value of flag matches one of the argument", "command that would produce this trace. \"\"\" args = []", "and '=' in arg: prefix, value = arg.split('=', 1) return", "with the License. # You may obtain a copy of", "single Fire execution. An action may be instantiating a class,", "AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error, args): element", "module has classes for tracing the execution of a Fire", "_Quote(self, arg): if arg.startswith('--') and '=' in arg: prefix, value", "the flag available for the trace Returns: True for needed", "up to this point. Args: include_separators: Whether or not to", "# from Bash (the default separator is the hyphen -)", "execution encountered a Fire usage error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self,", "component=component, action=action, target=target, args=args, filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element) def", "additional arguments in order to make sure the arg is", "to by the command the same when adding additional args.", "__str__(self): lines = [] for index, element in enumerate(self.elements): line", "the instantiation of a class or the accessing of an", "the callable. args: The args consumed in order to call", "args. \"\"\" element = self.GetLastHealthyElement() return element.HasCapacity() and not element.HasSeparator()", "{trace_string}'.format( index=index + 1, trace_string=element, ) lines.append(line) return '\\n'.join(lines) def", "\"{target}\"'.format(target=self._target) if self._filename is not None: path = self._filename if", "how to do it: # in Python def display(arg1, arg2='!'):", "called with the default value for arg2. \"\"\" self.elements[-1].AddSeparator() def", "self._capacity = capacity def HasError(self): return self._error is not None", "component' INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE", "compliance with the License. # You may obtain a copy", "not None: string += ' \"{target}\"'.format(target=self._target) if self._filename is not", "Whether the action could have accepted additional args. \"\"\" self.component", "agreed to in writing, software # distributed under the License", "which the callable is defined, or None if N/A. capacity:", "trace indicating that a component was called. Also applies to", "the command before adding additional arguments in order to make", "pipes.quote(prefix) + '=' + pipes.quote(value) return pipes.quote(arg) def GetCommand(self, include_separators=True):", "added to the command if order to keep the component", "action taken by Fire during a single Fire execution. An", "is not None: path = self._filename if self._lineno is not", "self.elements.append(element) def AddSeparator(self): \"\"\"Marks that the most recent element of", "# in Python def display(arg1, arg2='!'): return arg1 + arg2", "distributed under the License is distributed on an \"AS IS\"", "accessing a property. Each action consumes args and results in", "you want to call that function, and then upper case", "self.GetLastHealthyElement() component = element.component spec = inspectutils.GetFullArgSpec(component) return (spec.varkw is", "component was called. Also applies to instantiating a class. Args:", "the argument of the component, or the component takes in", "name self.separator = separator self.elements = [initial_trace_element] self.verbose = verbose", "has classes for tracing the execution of a Fire execution.", "the component takes in keyword-only arguments(e.g. argument with default value).", "+ arg2 # from Bash (the default separator is the", "= show_trace def GetResult(self): \"\"\"Returns the component from the last", "' '.join(self._Quote(arg) for arg in args) def NeedsSeparator(self): \"\"\"Returns whether", "whether we should add a separator to the command before", "routine' CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT", "is applied to the result of the function call, and", "an error. This element will contain the final component indicated", "not None def HasCapacity(self): return self._capacity def HasSeparator(self): return self._separator", "takes in keyword-only arguments(e.g. argument with default value). Args: flag:", "express or implied. # See the License for the specific", "value = arg.split('=', 1) return pipes.quote(prefix) + '=' + pipes.quote(value)", "the command representing the trace up to this point. Args:", "N/A. lineno: The line number on which the action is", "except in compliance with the License. # You may obtain", "INTERACTIVE_MODE = 'Entered interactive mode' class FireTrace(object): \"\"\"A FireTrace represents", "self._separator = True def ErrorAsStr(self): return ' '.join(str(arg) for arg", "pipes from fire import inspectutils INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS", "return pipes.quote(prefix) + '=' + pipes.quote(value) return pipes.quote(arg) def GetCommand(self,", "None: path += ':{lineno}'.format(lineno=self._lineno) string += ' ({path})'.format(path=path) return string", "representing a Fire CLI command that would produce this trace.", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "separator. Let's say you have a function that takes a", "not use this file except in compliance with the License.", "args=args, filename=filename, lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self, component, target, args,", "a Fire usage error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self, component, target,", "the callable is defined, or None if N/A. capacity: (bool)", "command if order to keep the component referred to by", "element of the trace that is not an error. \"\"\"", "writing, software # distributed under the License is distributed on", "self.args = args self._filename = filename self._lineno = lineno self._error", "from the last element of the trace.\"\"\" # pytype: disable=attribute-error", "final component will be None. \"\"\" from __future__ import absolute_import", "was called. Also applies to instantiating a class. Args: component:", "acting on the result of the function call. This function", "arguments(e.g. argument with default value). Args: flag: the flag available", "you may not use this file except in compliance with", "line number on which the action is defined, or None", "an action taken by Fire during a single Fire execution.", "order to call this callable. filename: The file in which", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "function that takes a variable number of args, and you", "# pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the last element of", "or accessing a property. Each action consumes args and results", "lineno: The line number on which the action is defined,", "self.elements = [initial_trace_element] self.verbose = verbose self.show_help = show_help self.show_trace", "upper # HELLO! Note how the separator caused the display", "accepted additional args. action: The value to include as the", "call, then adding an additional argument to the command sometimes", "result of this element of the trace. action: The type", "AddCompletionScript(self, script): element = FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def", "the action, or None if N/A. capacity: (bool) Whether the", "Examples of a FireTraceElement are the instantiation of a class", "instantiating a class. Args: component: The result of calling the", "to the command. If the command is a function call,", "a FireTraceElement. Args: component: The result of this element of", "\"\"\" def __init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None,", "(the default separator is the hyphen -) display hello #", "could have accepted additional args. action: The value to include", "separators in the command. Returns: A string representing a Fire", "sometimes would add an extra arg to the function call,", "CONDITIONS OF ANY KIND, either express or implied. # See", "action. filename: The file in which the action is defined,", "element of the trace.\"\"\" # pytype: disable=attribute-error return self.GetLastHealthyElement().component #", "'Called routine' CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY = 'Accessed property'", "self.show_help = show_help self.show_trace = show_trace def GetResult(self): \"\"\"Returns the", "def HasError(self): \"\"\"Returns whether the Fire execution encountered a Fire", "The name of the callable. args: The args consumed in", "of flag matches one of the argument of the component,", "to keep the component referred to by the command the", "component, or the component takes in keyword-only arguments(e.g. argument with", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "the separator. Let's say you have a function that takes", "target: (string) The name of the component being acted upon.", "component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element)", "\"\"\"Returns whether a the trace need '--' before '--help'. '--'", "that error will be captured in the trace and the", "the trace up to this point. Args: include_separators: Whether or", "callable. args: The args consumed in order to call this", "the final component will be None. \"\"\" from __future__ import", "taken during a single Fire execution. A FireTrace consists of", "the License. \"\"\"This module has classes for tracing the execution", "not None: path = self._filename if self._lineno is not None:", "NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a the trace need '--' before", "could have accepted additional args. \"\"\" self.component = component self._action", "initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name = name self.separator", "The result of this element of the trace. action: The", "trace Returns: True for needed '--', False otherwise. \"\"\" element", "args consumed by the represented action. filename: The file in", "import print_function import pipes from fire import inspectutils INITIAL_COMPONENT =", "self.NeedsSeparator() and include_separators: args.append(self.separator) return ' '.join(self._Quote(arg) for arg in", "(C) 2018 Google Inc. # # Licensed under the Apache", "not element.HasError(): return element return None def HasError(self): \"\"\"Returns whether", "\"\"\" args = [] if self.name: args.append(self.name) for element in", "separator self.elements = [initial_trace_element] self.verbose = verbose self.show_help = show_help", "be added to the command if order to keep the", "name of the component being acted upon. args: The args", "that the most recent element of the trace used a", "= self.GetLastHealthyElement() return element.HasCapacity() and not element.HasSeparator() def __str__(self): lines", ") self.name = name self.separator = separator self.elements = [initial_trace_element]", "is the hyphen -) display hello # hello! display hello", "lineno=lineno, capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self, script): element = FireTraceElement(", "trace up to this point. Args: include_separators: Whether or not", "a variable number of args, and you want to call", "of the argument of the component, or the component takes", "line number on which the callable is defined, or None", "element represents an action taken by Fire during a single", "return arg1 + arg2 # from Bash (the default separator", "callable could have accepted additional args. action: The value to", "returned by the Fire method. If a Fire usage error", "property. \"\"\" def __init__(self, initial_component, name=None, separator='-', verbose=False, show_help=False, show_trace=False):", "step taken by a Fire execution. Examples of a FireTraceElement", "separator. Here's an example to demonstrate the separator. Let's say", "defined, or None if N/A. error: The error represented by", "Args: include_separators: Whether or not to include separators in the", "be called with the default value for arg2. \"\"\" self.elements[-1].AddSeparator()", "OR CONDITIONS OF ANY KIND, either express or implied. #", "in order to make sure the arg is applied to", "arguments in order to make sure the arg is applied", "spec = inspectutils.GetFullArgSpec(component) return (spec.varkw is not None or flag", "the License is distributed on an \"AS IS\" BASIS, #", "or None if N/A. lineno: The line number on which", "that is not an error. This element will contain the", "arg2 # from Bash (the default separator is the hyphen", "otherwise. \"\"\" element = self.GetLastHealthyElement() component = element.component spec =", "most recent element of the trace used a separator. A", ") self.elements.append(element) def AddCompletionScript(self, script): element = FireTraceElement( component=script, action=COMPLETION_SCRIPT,", "filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self, script): element =", "'Instantiated class' CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE = 'Called callable'", "call that function, and then upper case the result. Here's", "= name self.separator = separator self.elements = [initial_trace_element] self.verbose =", "consumed by the represented action. filename: The file in which", "CLI to separate args left of the separator from args", "'--help'. '--' is needed when the component takes keyword arguments,", "execution of a Fire execution. A FireTrace consists of a", "inspectutils.GetFullArgSpec(component) return (spec.varkw is not None or flag in spec.args", "for arg in args) def NeedsSeparator(self): \"\"\"Returns whether a separator", "division from __future__ import print_function import pipes from fire import", "from args right of the separator. Here's an example to", "INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE =", "return self.elements[-1].HasError() def AddAccessedProperty(self, component, target, args, filename, lineno): element", "return pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns the command representing the", "\"\"\" for element in reversed(self.elements): if not element.HasError(): return element", "- upper # HELLO! Note how the separator caused the", "the trace that is not an error. \"\"\" for element", "self._action = action self._target = target self.args = args self._filename", "+ pipes.quote(value) return pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns the command", "Returns: Whether a separator should be added to the command", "of the trace that is not an error. \"\"\" for", "being acted upon. args: The args consumed by the represented", "to make sure the arg is applied to the result", "order to keep the component referred to by the command", "file in which the callable is defined, or None if", "the action in the FireTraceElement. \"\"\" element = FireTraceElement( component=component,", "by the command the same when adding additional args. \"\"\"", "accepted additional args. \"\"\" self.component = component self._action = action", "if not element.HasError(): return element return None def HasError(self): \"\"\"Returns", "defined, or None if N/A. capacity: (bool) Whether the callable", "error=None, capacity=None): \"\"\"Instantiates a FireTraceElement. Args: component: The result of", "to include as the action in the FireTraceElement. \"\"\" element", "element of the trace that is not an error. This", "= '{index}. {trace_string}'.format( index=index + 1, trace_string=element, ) lines.append(line) return", "target=None, args=None, filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates a FireTraceElement. Args:", "law or agreed to in writing, software # distributed under", "call a function, then that error will be captured in", "True for needed '--', False otherwise. \"\"\" element = self.GetLastHealthyElement()", "else: # Format is: {action} \"{target}\" ({filename}:{lineno}) string = self._action", "+= ' \"{target}\"'.format(target=self._target) if self._filename is not None: path =", "path = self._filename if self._lineno is not None: path +=", "language governing permissions and # limitations under the License. \"\"\"This", "\"\"\" from __future__ import absolute_import from __future__ import division from", "= action self._target = target self.args = args self._filename =", "(eg instantiating a class) taking place. target: (string) The name", "takes a variable number of args, and you want to", "not element.HasSeparator() def __str__(self): lines = [] for index, element", "self.show_trace = show_trace def GetResult(self): \"\"\"Returns the component from the", "True def ErrorAsStr(self): return ' '.join(str(arg) for arg in self._error.args)", "\"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg): if arg.startswith('--') and '=' in", "the function call, and sometimes would add an arg acting", "A string representing a Fire CLI command that would produce", "if self.name: args.append(self.name) for element in self.elements: if element.HasError(): continue", "are the instantiation of a class or the accessing of", "of FireTraceElement objects. Each element represents an action taken by", "to the trace indicating that a component was called. Also", "occurs, such as insufficient arguments being provided to call a", "name of the callable. args: The args consumed in order", "FireTraceElement(object): \"\"\"A FireTraceElement represents a single step taken by a", "string += ' \"{target}\"'.format(target=self._target) if self._filename is not None: path", "we should add a separator to the command before adding", "the callable is defined, or None if N/A. lineno: The", "def __str__(self): if self.HasError(): return self.ErrorAsStr() else: # Format is:", "call this callable. filename: The file in which the callable", "def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a the trace need '--'", "= separator self.elements = [initial_trace_element] self.verbose = verbose self.show_help =", "if N/A. error: The error represented by the action, or", "component self._action = action self._target = target self.args = args", "not an error. This element will contain the final component", "= capacity def HasError(self): return self._error is not None def", "lineno): element = FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno,", "None or flag in spec.args or flag in spec.kwonlyargs) class", "encountered a Fire usage error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self, component,", "# HELLO! Note how the separator caused the display function", "None: path = self._filename if self._lineno is not None: path", "may obtain a copy of the License at # #", "is not None: path += ':{lineno}'.format(lineno=self._lineno) string += ' ({path})'.format(path=path)", "additional argument to the command sometimes would add an extra", "to the command sometimes would add an extra arg to", "indicated by the trace. Returns: The last element of the", "and not the function call itself. Returns: Whether a separator", "result of calling the callable. target: The name of the", "sequence of FireTraceElement objects. Each element represents an action taken", "enumerate(self.elements): line = '{index}. {trace_string}'.format( index=index + 1, trace_string=element, )", "acted upon. args: The args consumed by the represented action.", "a routine, or accessing a property. \"\"\" def __init__(self, initial_component,", "say you have a function that takes a variable number", "for arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg): if arg.startswith('--') and", "filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates a FireTraceElement. Args: component: The", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "Inc. # # Licensed under the Apache License, Version 2.0", "= self.GetLastHealthyElement() component = element.component spec = inspectutils.GetFullArgSpec(component) return (spec.varkw", "Copyright (C) 2018 Google Inc. # # Licensed under the", "you have a function that takes a variable number of", "__str__(self): if self.HasError(): return self.ErrorAsStr() else: # Format is: {action}", "show_trace def GetResult(self): \"\"\"Returns the component from the last element", "may not use this file except in compliance with the", "capacity: (bool) Whether the callable could have accepted additional args.", "return (spec.varkw is not None or flag in spec.args or", "function tells us whether we should add a separator to", "FireTrace consists of a sequence of FireTraceElement objects. Each element", "action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates a FireTraceElement.", "from fire import inspectutils INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS =", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "limitations under the License. \"\"\"This module has classes for tracing", "for tracing the execution of a Fire execution. A FireTrace", "to call a function, then that error will be captured", "the last element of the trace.\"\"\" # pytype: disable=attribute-error return", "separator caused the display function to be called with the", "routine, or accessing a property. \"\"\" def __init__(self, initial_component, name=None,", "this file except in compliance with the License. # You", "callable' ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT = 'Generated completion script'", "element = self.GetLastHealthyElement() return element.HasCapacity() and not element.HasSeparator() def __str__(self):", "import absolute_import from __future__ import division from __future__ import print_function", "target, args, filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an element to", "a separator should be added to the command. If the", "function, and then upper case the result. Here's how to", "to a Fire CLI to separate args left of the", "FireTraceElement. Args: component: The result of this element of the", "return self._capacity def HasSeparator(self): return self._separator def AddSeparator(self): self._separator =", "indicating that a component was called. Also applies to instantiating", "If the command is a function call, then adding an", "spec.args or flag in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement represents", "command the same when adding additional args. \"\"\" element =", "component, target, args, filename, lineno): element = FireTraceElement( component=component, action=ACCESSED_PROPERTY,", "The type of action (eg instantiating a class) taking place.", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "Format is: {action} \"{target}\" ({filename}:{lineno}) string = self._action if self._target", "# limitations under the License. \"\"\"This module has classes for", "the function call itself. Returns: Whether a separator should be", "pipes.quote(value) return pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns the command representing", "# # Licensed under the Apache License, Version 2.0 (the", "Fire during a single Fire execution. An action may be", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "and not element.HasSeparator() def __str__(self): lines = [] for index,", "= component self._action = action self._target = target self.args =", "is not None: string += ' \"{target}\"'.format(target=self._target) if self._filename is", "'{index}. {trace_string}'.format( index=index + 1, trace_string=element, ) lines.append(line) return '\\n'.join(lines)", "the trace need '--' before '--help'. '--' is needed when", "filename, lineno): element = FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename,", "in reversed(self.elements): if not element.HasError(): return element return None def", "\"\"\"A FireTrace represents the steps taken during a single Fire", "The line number on which the callable is defined, or", "# Copyright (C) 2018 Google Inc. # # Licensed under", "\"\"\"Returns the last element of the trace that is not", "lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self, component, target, args, filename, lineno,", "lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an element to the trace indicating", "defined, or None if N/A. lineno: The line number on", "to do it: # in Python def display(arg1, arg2='!'): return", "a function, then that error will be captured in the", "The result of calling the callable. target: The name of", "is a function call, then adding an additional argument to", "'Called callable' ACCESSED_PROPERTY = 'Accessed property' COMPLETION_SCRIPT = 'Generated completion", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "component. The final component is serialized to stdout by Fire", "element.HasCapacity() and not element.HasSeparator() def __str__(self): lines = [] for", "an error. \"\"\" for element in reversed(self.elements): if not element.HasError():", "Fire method. If a Fire usage error occurs, such as", "'Generated completion script' INTERACTIVE_MODE = 'Entered interactive mode' class FireTrace(object):", "interactive mode' class FireTrace(object): \"\"\"A FireTrace represents the steps taken", "execution. Examples of a FireTraceElement are the instantiation of a", "target=target, args=args, filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self, script):", "as returned by the Fire method. If a Fire usage", "hello! display hello upper # helloupper display hello - upper", "Python def display(arg1, arg2='!'): return arg1 + arg2 # from", "FireTrace(object): \"\"\"A FireTrace represents the steps taken during a single", "1) return pipes.quote(prefix) + '=' + pipes.quote(value) return pipes.quote(arg) def", "represents an action taken by Fire during a single Fire", "CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY =", "Whether a separator should be added to the command if", "needed when the component takes keyword arguments, when the value", "flag available for the trace Returns: True for needed '--',", "final component is serialized to stdout by Fire as well", "for needed '--', False otherwise. \"\"\" element = self.GetLastHealthyElement() component", "def __init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None):", "HasCapacity(self): return self._capacity def HasSeparator(self): return self._separator def AddSeparator(self): self._separator", "the separator caused the display function to be called with", "value to include as the action in the FireTraceElement. \"\"\"", "self._filename is not None: path = self._filename if self._lineno is", "include separators in the command. Returns: A string representing a", "\"\"\"Adds an element to the trace indicating that a component", "Here's how to do it: # in Python def display(arg1,", "self._error = error self._separator = False self._capacity = capacity def", "calling a routine, or accessing a property. Each action consumes", "error. \"\"\" for element in reversed(self.elements): if not element.HasError(): return", "separator to the command before adding additional arguments in order", "a single step taken by a Fire execution. Examples of", "def GetResult(self): \"\"\"Returns the component from the last element of", "args=None, filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates a FireTraceElement. Args: component:", "as the action in the FireTraceElement. \"\"\" element = FireTraceElement(", "self._separator def AddSeparator(self): self._separator = True def ErrorAsStr(self): return '", "script' INTERACTIVE_MODE = 'Entered interactive mode' class FireTrace(object): \"\"\"A FireTrace", "element = FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self): element", "'Initial component' INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE = 'Called routine'", "trace. Returns: The last element of the trace that is", "\"\"\" self.component = component self._action = action self._target = target", "used a separator. A separator is an argument you can", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "this callable. filename: The file in which the callable is", "taken by a Fire execution. Examples of a FireTraceElement are", "capacity, action=CALLED_CALLABLE): \"\"\"Adds an element to the trace indicating that", "lineno self._error = error self._separator = False self._capacity = capacity", "tracing the execution of a Fire execution. A FireTrace consists", "arguments, when the value of flag matches one of the", "a single Fire execution. An action may be instantiating a", "= inspectutils.GetFullArgSpec(component) return (spec.varkw is not None or flag in", "of the component being acted upon. args: The args consumed", "= FireTraceElement( component=component, action=action, target=target, args=args, filename=filename, lineno=lineno, capacity=capacity, )", "which the action is defined, or None if N/A. lineno:", "element.args: args.extend(element.args) if element.HasSeparator() and include_separators: args.append(self.separator) if self.NeedsSeparator() and", "The value to include as the action in the FireTraceElement.", "HasSeparator(self): return self._separator def AddSeparator(self): self._separator = True def ErrorAsStr(self):", "self._error.args) def __str__(self): if self.HasError(): return self.ErrorAsStr() else: # Format", "then adding an additional argument to the command sometimes would", "or implied. # See the License for the specific language", "accessing a property. \"\"\" def __init__(self, initial_component, name=None, separator='-', verbose=False,", "referred to by the command the same when adding additional", "FireTraceElement( component=script, action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE)", "string representing a Fire CLI command that would produce this", "being provided to call a function, then that error will", "NeedsSeparator(self): \"\"\"Returns whether a separator should be added to the", "member. \"\"\" def __init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None,", "Fire usage error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self, component, target, args,", "Note how the separator caused the display function to be", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "method. If a Fire usage error occurs, such as insufficient", "such as insufficient arguments being provided to call a function,", "the last element of the trace that is not an", "AddError(self, error, args): element = FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self):", "of the trace.\"\"\" # pytype: disable=attribute-error return self.GetLastHealthyElement().component # pytype:", "the command if order to keep the component referred to", "the component being acted upon. args: The args consumed by", "self._lineno = lineno self._error = error self._separator = False self._capacity", "The args consumed in order to call this callable. filename:", "args. action: The value to include as the action in", "command is a function call, then adding an additional argument", "adding additional arguments in order to make sure the arg", "= self._filename if self._lineno is not None: path += ':{lineno}'.format(lineno=self._lineno)", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "lineno: The line number on which the callable is defined,", "the default value for arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg):", "the trace.\"\"\" # pytype: disable=attribute-error return self.GetLastHealthyElement().component # pytype: enable=attribute-error", "on which the action is defined, or None if N/A.", "the arg is applied to the result of the function", "This element will contain the final component indicated by the", "action=action, target=target, args=args, filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element) def AddCompletionScript(self,", "error, args): element = FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks", "Google Inc. # # Licensed under the Apache License, Version", "show_trace=False): initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name = name", "sure the arg is applied to the result of the", "during a single Fire execution. An action may be instantiating", "available for the trace Returns: True for needed '--', False", "return None def HasError(self): \"\"\"Returns whether the Fire execution encountered", "or None if N/A. capacity: (bool) Whether the callable could", "\"{target}\" ({filename}:{lineno}) string = self._action if self._target is not None:", ") lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a", "def GetLastHealthyElement(self): \"\"\"Returns the last element of the trace that", "= show_help self.show_trace = show_trace def GetResult(self): \"\"\"Returns the component", "consumed in order to call this callable. filename: The file", "add a separator to the command before adding additional arguments", "in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement represents a single step", "(the \"License\"); # you may not use this file except", "def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error, args):", "type of action (eg instantiating a class) taking place. target:", "This function tells us whether we should add a separator", "# you may not use this file except in compliance", "include_separators: args.append(self.separator) return ' '.join(self._Quote(arg) for arg in args) def", "self._target = target self.args = args self._filename = filename self._lineno", "\"\"\" element = self.GetLastHealthyElement() component = element.component spec = inspectutils.GetFullArgSpec(component)", "'.join(str(arg) for arg in self._error.args) def __str__(self): if self.HasError(): return", "component is serialized to stdout by Fire as well as", "element = FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno, )", "would produce this trace. \"\"\" args = [] if self.name:", "pipes.quote(arg) def GetCommand(self, include_separators=True): \"\"\"Returns the command representing the trace", "if element.HasError(): continue if element.args: args.extend(element.args) if element.HasSeparator() and include_separators:", "self._target is not None: string += ' \"{target}\"'.format(target=self._target) if self._filename", "self.name: args.append(self.name) for element in self.elements: if element.HasError(): continue if", "arg): if arg.startswith('--') and '=' in arg: prefix, value =", "flag in spec.args or flag in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A", "component: The result of calling the callable. target: The name", "trace need '--' before '--help'. '--' is needed when the", "lines = [] for index, element in enumerate(self.elements): line =", "continue if element.args: args.extend(element.args) if element.HasSeparator() and include_separators: args.append(self.separator) if", "-) display hello # hello! display hello upper # helloupper", "element return None def HasError(self): \"\"\"Returns whether the Fire execution", "include as the action in the FireTraceElement. \"\"\" element =", "adding an additional argument to the command sometimes would add", "usage error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self, component, target, args, filename,", "instantiation of a class or the accessing of an object", "# # Unless required by applicable law or agreed to", "under the License. \"\"\"This module has classes for tracing the", "[initial_trace_element] self.verbose = verbose self.show_help = show_help self.show_trace = show_trace", "1, trace_string=element, ) lines.append(line) return '\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns", "separator should be added to the command if order to", "this element of the trace. action: The type of action", "in order to call this callable. filename: The file in", "number on which the action is defined, or None if", "class FireTrace(object): \"\"\"A FireTrace represents the steps taken during a", "enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the last element of the trace", "Returns: The last element of the trace that is not", "in enumerate(self.elements): line = '{index}. {trace_string}'.format( index=index + 1, trace_string=element,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "is not None or flag in spec.args or flag in", "the accessing of an object member. \"\"\" def __init__(self, component=None,", "number of args, and you want to call that function,", "arg acting on the result of the function call. This", "Version 2.0 (the \"License\"); # you may not use this", "trace and the final component will be None. \"\"\" from", "trace that is not an error. \"\"\" for element in", "The last element of the trace that is not an", "in Python def display(arg1, arg2='!'): return arg1 + arg2 #", "the result of the function call, and not the function", "def AddError(self, error, args): element = FireTraceElement(error=error, args=args) self.elements.append(element) def", "file in which the action is defined, or None if", "verbose=False, show_help=False, show_trace=False): initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name", "adding additional args. \"\"\" element = self.GetLastHealthyElement() return element.HasCapacity() and", "result of the function call, and not the function call", "\"\"\"Instantiates a FireTraceElement. Args: component: The result of this element", "return self.ErrorAsStr() else: # Format is: {action} \"{target}\" ({filename}:{lineno}) string", "the trace. Returns: The last element of the trace that", "arg.startswith('--') and '=' in arg: prefix, value = arg.split('=', 1)", "Fire CLI command that would produce this trace. \"\"\" args", "represented by the action, or None if N/A. capacity: (bool)", "of the separator from args right of the separator. Here's", "and include_separators: args.append(self.separator) return ' '.join(self._Quote(arg) for arg in args)", "separator should be added to the command. If the command", "the function call, and not the function call itself. Returns:", "action (eg instantiating a class) taking place. target: (string) The", "or not to include separators in the command. Returns: A", "represented action. filename: The file in which the action is", "__future__ import absolute_import from __future__ import division from __future__ import", "pass to a Fire CLI to separate args left of", "[] if self.name: args.append(self.name) for element in self.elements: if element.HasError():", "in a new component. The final component is serialized to", "a Fire CLI command that would produce this trace. \"\"\"", "implied. # See the License for the specific language governing", "a class, calling a routine, or accessing a property. Each", "to stdout by Fire as well as returned by the", "return ' '.join(self._Quote(arg) for arg in args) def NeedsSeparator(self): \"\"\"Returns", "in spec.args or flag in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement", "if order to keep the component referred to by the", "of a FireTraceElement are the instantiation of a class or", "under the Apache License, Version 2.0 (the \"License\"); # you", "component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None): \"\"\"Instantiates a", "class, calling a routine, or accessing a property. Each action", "a single Fire execution. A FireTrace consists of a sequence", "self.separator = separator self.elements = [initial_trace_element] self.verbose = verbose self.show_help", "separator. A separator is an argument you can pass to", "to include separators in the command. Returns: A string representing", "action self._target = target self.args = args self._filename = filename", "N/A. capacity: (bool) Whether the callable could have accepted additional", "self.elements[-1].HasError() def AddAccessedProperty(self, component, target, args, filename, lineno): element =", "a separator to the command before adding additional arguments in", "A FireTrace consists of a sequence of FireTraceElement objects. Each", "be None. \"\"\" from __future__ import absolute_import from __future__ import", "separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, )", "by applicable law or agreed to in writing, software #", "of the component, or the component takes in keyword-only arguments(e.g.", "arg: prefix, value = arg.split('=', 1) return pipes.quote(prefix) + '='", "case the result. Here's how to do it: # in", "additional args. \"\"\" self.component = component self._action = action self._target", "added to the command. If the command is a function", "element = FireTraceElement( component=component, action=action, target=target, args=args, filename=filename, lineno=lineno, capacity=capacity,", "right of the separator. Here's an example to demonstrate the", "in the command. Returns: A string representing a Fire CLI", "by the action, or None if N/A. capacity: (bool) Whether", "argument of the component, or the component takes in keyword-only", "action, or None if N/A. capacity: (bool) Whether the action", "value of flag matches one of the argument of the", "upper case the result. Here's how to do it: #", "= 'Accessed property' COMPLETION_SCRIPT = 'Generated completion script' INTERACTIVE_MODE =", "COMPLETION_SCRIPT = 'Generated completion script' INTERACTIVE_MODE = 'Entered interactive mode'", "filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an element to the trace", "def AddCalledComponent(self, component, target, args, filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds", "return element return None def HasError(self): \"\"\"Returns whether the Fire", "def _Quote(self, arg): if arg.startswith('--') and '=' in arg: prefix,", "that a component was called. Also applies to instantiating a", "Args: flag: the flag available for the trace Returns: True", "governing permissions and # limitations under the License. \"\"\"This module", "not to include separators in the command. Returns: A string", "arg in self._error.args) def __str__(self): if self.HasError(): return self.ErrorAsStr() else:", "FireTraceElement objects. Each element represents an action taken by Fire", "or None if N/A. error: The error represented by the", "\"\"\"Returns whether a separator should be added to the command.", "the Fire execution encountered a Fire usage error.\"\"\" return self.elements[-1].HasError()", "component takes keyword arguments, when the value of flag matches", "action: The type of action (eg instantiating a class) taking", "component from the last element of the trace.\"\"\" # pytype:", "instantiating a class) taking place. target: (string) The name of", "if N/A. capacity: (bool) Whether the callable could have accepted", "the hyphen -) display hello # hello! display hello upper", "object member. \"\"\" def __init__(self, component=None, action=None, target=None, args=None, filename=None,", "filename: The file in which the action is defined, or", "action is defined, or None if N/A. error: The error", "display function to be called with the default value for", "Let's say you have a function that takes a variable", "default separator is the hyphen -) display hello # hello!", "be instantiating a class, calling a routine, or accessing a", "upper # helloupper display hello - upper # HELLO! Note", "that is not an error. \"\"\" for element in reversed(self.elements):", "import inspectutils INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS = 'Instantiated class'", "a new component. The final component is serialized to stdout", "error.\"\"\" return self.elements[-1].HasError() def AddAccessedProperty(self, component, target, args, filename, lineno):", "args, filename, lineno, capacity, action=CALLED_CALLABLE): \"\"\"Adds an element to the", "FireTraceElement. \"\"\" element = FireTraceElement( component=component, action=action, target=target, args=args, filename=filename,", "AddSeparator(self): \"\"\"Marks that the most recent element of the trace", "component: The result of this element of the trace. action:", "as insufficient arguments being provided to call a function, then", "function call itself. Returns: Whether a separator should be added", "value for arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self, arg): if arg.startswith('--')", "a property. \"\"\" def __init__(self, initial_component, name=None, separator='-', verbose=False, show_help=False,", "= verbose self.show_help = show_help self.show_trace = show_trace def GetResult(self):", "element.HasSeparator() def __str__(self): lines = [] for index, element in", "in self.elements: if element.HasError(): continue if element.args: args.extend(element.args) if element.HasSeparator()", "last element of the trace.\"\"\" # pytype: disable=attribute-error return self.GetLastHealthyElement().component", "args) def NeedsSeparator(self): \"\"\"Returns whether a separator should be added", "arg is applied to the result of the function call,", "in keyword-only arguments(e.g. argument with default value). Args: flag: the", "with the default value for arg2. \"\"\" self.elements[-1].AddSeparator() def _Quote(self,", "execution. A FireTrace consists of a sequence of FireTraceElement objects.", "= 'Instantiated class' CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE = 'Called", "<reponame>nvhoang55/python-fire<gh_stars>0 # Copyright (C) 2018 Google Inc. # # Licensed", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "def display(arg1, arg2='!'): return arg1 + arg2 # from Bash", "Unless required by applicable law or agreed to in writing,", "def NeedsSeparator(self): \"\"\"Returns whether a separator should be added to", "calling the callable. target: The name of the callable. args:", "a Fire usage error occurs, such as insufficient arguments being", "'.join(self._Quote(arg) for arg in args) def NeedsSeparator(self): \"\"\"Returns whether a", "the value of flag matches one of the argument of", "of the trace used a separator. A separator is an", "component=initial_component, action=INITIAL_COMPONENT, ) self.name = name self.separator = separator self.elements", "whether a separator should be added to the command. If", "when the component takes keyword arguments, when the value of", "to the command before adding additional arguments in order to", "'Entered interactive mode' class FireTrace(object): \"\"\"A FireTrace represents the steps", "element.HasError(): return element return None def HasError(self): \"\"\"Returns whether the", "the display function to be called with the default value", "keyword arguments, when the value of flag matches one of", "hello upper # helloupper display hello - upper # HELLO!", "' '.join(str(arg) for arg in self._error.args) def __str__(self): if self.HasError():", "the specific language governing permissions and # limitations under the", "last element of the trace that is not an error.", "License. \"\"\"This module has classes for tracing the execution of", "import pipes from fire import inspectutils INITIAL_COMPONENT = 'Initial component'", "display hello # hello! display hello upper # helloupper display", "target self.args = args self._filename = filename self._lineno = lineno", "should be added to the command. If the command is", "\"\"\" element = FireTraceElement( component=component, action=action, target=target, args=args, filename=filename, lineno=lineno,", "from Bash (the default separator is the hyphen -) display", "applicable law or agreed to in writing, software # distributed", "return self.GetLastHealthyElement().component # pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the last", "GetLastHealthyElement(self): \"\"\"Returns the last element of the trace that is", "initial_component, name=None, separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element = FireTraceElement( component=initial_component,", "flag matches one of the argument of the component, or", "argument to the command sometimes would add an extra arg", "return self._separator def AddSeparator(self): self._separator = True def ErrorAsStr(self): return", "component indicated by the trace. Returns: The last element of", "reversed(self.elements): if not element.HasError(): return element return None def HasError(self):", "for element in reversed(self.elements): if not element.HasError(): return element return", "as well as returned by the Fire method. If a", "\"\"\"Returns whether the Fire execution encountered a Fire usage error.\"\"\"", "= element.component spec = inspectutils.GetFullArgSpec(component) return (spec.varkw is not None", "of the callable. args: The args consumed in order to", "of an object member. \"\"\" def __init__(self, component=None, action=None, target=None,", "represents a single step taken by a Fire execution. Examples", "self.elements.append(element) def AddError(self, error, args): element = FireTraceElement(error=error, args=args) self.elements.append(element)", "be captured in the trace and the final component will", "include_separators: Whether or not to include separators in the command.", "the separator from args right of the separator. Here's an", "the result of the function call. This function tells us", "in writing, software # distributed under the License is distributed", "extra arg to the function call, and sometimes would add", "to call this callable. filename: The file in which the", "an additional argument to the command sometimes would add an", "of the trace that is not an error. This element", "function call, and sometimes would add an arg acting on", "trace that is not an error. This element will contain", "The error represented by the action, or None if N/A.", "separator from args right of the separator. Here's an example", "hello # hello! display hello upper # helloupper display hello", "produce this trace. \"\"\" args = [] if self.name: args.append(self.name)", "if self._target is not None: string += ' \"{target}\"'.format(target=self._target) if", "2018 Google Inc. # # Licensed under the Apache License,", "completion script' INTERACTIVE_MODE = 'Entered interactive mode' class FireTrace(object): \"\"\"A", "additional args. action: The value to include as the action", "arg2='!'): return arg1 + arg2 # from Bash (the default", "captured in the trace and the final component will be", "target=target, args=args, filename=filename, lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self, component, target,", "return element.HasCapacity() and not element.HasSeparator() def __str__(self): lines = []", "flag in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement represents a single", "of a class or the accessing of an object member.", "the execution of a Fire execution. A FireTrace consists of", "to the function call, and sometimes would add an arg", "or the accessing of an object member. \"\"\" def __init__(self,", "the trace and the final component will be None. \"\"\"", "self._filename = filename self._lineno = lineno self._error = error self._separator", "target: The name of the callable. args: The args consumed", "line = '{index}. {trace_string}'.format( index=index + 1, trace_string=element, ) lines.append(line)", "error will be captured in the trace and the final", "by the trace. Returns: The last element of the trace", "or flag in spec.kwonlyargs) class FireTraceElement(object): \"\"\"A FireTraceElement represents a", "a class or the accessing of an object member. \"\"\"", "__future__ import division from __future__ import print_function import pipes from", "us whether we should add a separator to the command", "' \"{target}\"'.format(target=self._target) if self._filename is not None: path = self._filename", "\"\"\"A FireTraceElement represents a single step taken by a Fire", "if N/A. lineno: The line number on which the callable", "error. This element will contain the final component indicated by", "will contain the final component indicated by the trace. Returns:", "self.HasError(): return self.ErrorAsStr() else: # Format is: {action} \"{target}\" ({filename}:{lineno})", "\"\"\"Marks that the most recent element of the trace used", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "disable=attribute-error return self.GetLastHealthyElement().component # pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the", "function, then that error will be captured in the trace", "License, Version 2.0 (the \"License\"); # you may not use", "argument you can pass to a Fire CLI to separate", "that would produce this trace. \"\"\" args = [] if", "before '--help'. '--' is needed when the component takes keyword", "function to be called with the default value for arg2.", "# You may obtain a copy of the License at", "a property. Each action consumes args and results in a", "= [] for index, element in enumerate(self.elements): line = '{index}.", "action may be instantiating a class, calling a routine, or", "def ErrorAsStr(self): return ' '.join(str(arg) for arg in self._error.args) def", "class' CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE = 'Called callable' ACCESSED_PROPERTY", "that function, and then upper case the result. Here's how", "the trace. action: The type of action (eg instantiating a", "'\\n'.join(lines) def NeedsSeparatingHyphenHyphen(self, flag='help'): \"\"\"Returns whether a the trace need", "in self._error.args) def __str__(self): if self.HasError(): return self.ErrorAsStr() else: #", "is serialized to stdout by Fire as well as returned", "name=None, separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "in which the action is defined, or None if N/A.", "a Fire execution. Examples of a FireTraceElement are the instantiation", "and # limitations under the License. \"\"\"This module has classes", "show_help self.show_trace = show_trace def GetResult(self): \"\"\"Returns the component from", "Fire usage error occurs, such as insufficient arguments being provided", "an arg acting on the result of the function call.", "action could have accepted additional args. \"\"\" self.component = component", "args: The args consumed in order to call this callable.", "FireTraceElement( component=component, action=action, target=target, args=args, filename=filename, lineno=lineno, capacity=capacity, ) self.elements.append(element)", "if self.NeedsSeparator() and include_separators: args.append(self.separator) return ' '.join(self._Quote(arg) for arg", "a function that takes a variable number of args, and", "consists of a sequence of FireTraceElement objects. Each element represents", "on the result of the function call. This function tells", "args: The args consumed by the represented action. filename: The", "helloupper display hello - upper # HELLO! Note how the", "filename: The file in which the callable is defined, or", "arg.split('=', 1) return pipes.quote(prefix) + '=' + pipes.quote(value) return pipes.quote(arg)", "args.append(self.separator) if self.NeedsSeparator() and include_separators: args.append(self.separator) return ' '.join(self._Quote(arg) for", "index, element in enumerate(self.elements): line = '{index}. {trace_string}'.format( index=index +", "this trace. \"\"\" args = [] if self.name: args.append(self.name) for", "element of the trace used a separator. A separator is", "__init__(self, initial_component, name=None, separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element = FireTraceElement(", "None def HasError(self): \"\"\"Returns whether the Fire execution encountered a", "def AddAccessedProperty(self, component, target, args, filename, lineno): element = FireTraceElement(", "an object member. \"\"\" def __init__(self, component=None, action=None, target=None, args=None,", ") self.elements.append(element) def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self,", "same when adding additional args. \"\"\" element = self.GetLastHealthyElement() return", "= False self._capacity = capacity def HasError(self): return self._error is", "the steps taken during a single Fire execution. A FireTrace", "HasError(self): return self._error is not None def HasCapacity(self): return self._capacity", "a separator. A separator is an argument you can pass", "the License for the specific language governing permissions and #", "import division from __future__ import print_function import pipes from fire", "of args, and you want to call that function, and", "display hello - upper # HELLO! Note how the separator", "you can pass to a Fire CLI to separate args", "CLI command that would produce this trace. \"\"\" args =", "Apache License, Version 2.0 (the \"License\"); # you may not", "Each action consumes args and results in a new component.", "command representing the trace up to this point. Args: include_separators:", "element of the trace. action: The type of action (eg", "either express or implied. # See the License for the", "of the function call. This function tells us whether we", "action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self, component,", "should add a separator to the command before adding additional", "need '--' before '--help'. '--' is needed when the component", "'=' in arg: prefix, value = arg.split('=', 1) return pipes.quote(prefix)", "a component was called. Also applies to instantiating a class.", "caused the display function to be called with the default", "show_help=False, show_trace=False): initial_trace_element = FireTraceElement( component=initial_component, action=INITIAL_COMPONENT, ) self.name =", "on which the callable is defined, or None if N/A.", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "args right of the separator. Here's an example to demonstrate", "The args consumed by the represented action. filename: The file", "args = [] if self.name: args.append(self.name) for element in self.elements:", "element = self.GetLastHealthyElement() component = element.component spec = inspectutils.GetFullArgSpec(component) return", "return ' '.join(str(arg) for arg in self._error.args) def __str__(self): if", "not None: path += ':{lineno}'.format(lineno=self._lineno) string += ' ({path})'.format(path=path) return", "Whether or not to include separators in the command. Returns:", "is not an error. This element will contain the final", "and the final component will be None. \"\"\" from __future__", "element in reversed(self.elements): if not element.HasError(): return element return None", "args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks that the most recent element", "do it: # in Python def display(arg1, arg2='!'): return arg1", "a class) taking place. target: (string) The name of the", "return self._error is not None def HasCapacity(self): return self._capacity def", "action=CALLED_CALLABLE): \"\"\"Adds an element to the trace indicating that a", "inspectutils INITIAL_COMPONENT = 'Initial component' INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE", "trace. action: The type of action (eg instantiating a class)", "= FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno, ) self.elements.append(element)", "trace. \"\"\" args = [] if self.name: args.append(self.name) for element", "command. Returns: A string representing a Fire CLI command that", "in which the callable is defined, or None if N/A.", "a sequence of FireTraceElement objects. Each element represents an action", "in the trace and the final component will be None.", "self.elements.append(element) def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error,", "element.HasError(): continue if element.args: args.extend(element.args) if element.HasSeparator() and include_separators: args.append(self.separator)", "component takes in keyword-only arguments(e.g. argument with default value). Args:", "is defined, or None if N/A. lineno: The line number", "for element in self.elements: if element.HasError(): continue if element.args: args.extend(element.args)", "An action may be instantiating a class, calling a routine,", "args.append(self.name) for element in self.elements: if element.HasError(): continue if element.args:", "'Accessed property' COMPLETION_SCRIPT = 'Generated completion script' INTERACTIVE_MODE = 'Entered", "instantiating a class, calling a routine, or accessing a property.", "a function call, then adding an additional argument to the", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "A separator is an argument you can pass to a", "self.component = component self._action = action self._target = target self.args", "def HasError(self): return self._error is not None def HasCapacity(self): return", "Returns: True for needed '--', False otherwise. \"\"\" element =", "FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks that the most recent", "that takes a variable number of args, and you want", "the result. Here's how to do it: # in Python", "order to make sure the arg is applied to the", "def __str__(self): lines = [] for index, element in enumerate(self.elements):", "FireTraceElement are the instantiation of a class or the accessing", "component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno, ) self.elements.append(element) def AddCalledComponent(self,", "self.elements.append(element) def AddCompletionScript(self, script): element = FireTraceElement( component=script, action=COMPLETION_SCRIPT, )", "Fire execution. An action may be instantiating a class, calling", "would add an arg acting on the result of the", "{action} \"{target}\" ({filename}:{lineno}) string = self._action if self._target is not", "= FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error, args): element = FireTraceElement(error=error,", "the component referred to by the command the same when", "objects. Each element represents an action taken by Fire during", "of the function call, and not the function call itself.", "Args: component: The result of this element of the trace.", "separator is the hyphen -) display hello # hello! display", "applied to the result of the function call, and not", "args and results in a new component. The final component", "HasError(self): \"\"\"Returns whether the Fire execution encountered a Fire usage", "a routine, or accessing a property. Each action consumes args", "the Fire method. If a Fire usage error occurs, such", "element = FireTraceElement(error=error, args=args) self.elements.append(element) def AddSeparator(self): \"\"\"Marks that the", "in the FireTraceElement. \"\"\" element = FireTraceElement( component=component, action=action, target=target,", "absolute_import from __future__ import division from __future__ import print_function import", "the action could have accepted additional args. \"\"\" self.component =", "INSTANTIATED_CLASS = 'Instantiated class' CALLED_ROUTINE = 'Called routine' CALLED_CALLABLE =", "verbose self.show_help = show_help self.show_trace = show_trace def GetResult(self): \"\"\"Returns", "element in self.elements: if element.HasError(): continue if element.args: args.extend(element.args) if", "single step taken by a Fire execution. Examples of a", "from __future__ import print_function import pipes from fire import inspectutils", "args self._filename = filename self._lineno = lineno self._error = error", "Fire execution. A FireTrace consists of a sequence of FireTraceElement", "call, and not the function call itself. Returns: Whether a", "is defined, or None if N/A. error: The error represented", "the component, or the component takes in keyword-only arguments(e.g. argument", "'--', False otherwise. \"\"\" element = self.GetLastHealthyElement() component = element.component", "\"License\"); # you may not use this file except in", "None if N/A. error: The error represented by the action,", "N/A. lineno: The line number on which the callable is", "HELLO! Note how the separator caused the display function to", "def HasSeparator(self): return self._separator def AddSeparator(self): self._separator = True def", "(string) The name of the component being acted upon. args:", "= True def ErrorAsStr(self): return ' '.join(str(arg) for arg in", "action=COMPLETION_SCRIPT, ) self.elements.append(element) def AddInteractiveMode(self): element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def", "# hello! display hello upper # helloupper display hello -", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# helloupper display hello - upper # HELLO! Note how", "component = element.component spec = inspectutils.GetFullArgSpec(component) return (spec.varkw is not", "which the action is defined, or None if N/A. error:", "False self._capacity = capacity def HasError(self): return self._error is not", "FireTraceElement represents a single step taken by a Fire execution.", "the represented action. filename: The file in which the action", "# distributed under the License is distributed on an \"AS", "pytype: enable=attribute-error def GetLastHealthyElement(self): \"\"\"Returns the last element of the", "to demonstrate the separator. Let's say you have a function", "None if N/A. capacity: (bool) Whether the action could have", "the command the same when adding additional args. \"\"\" element", ") self.elements.append(element) def AddCalledComponent(self, component, target, args, filename, lineno, capacity,", "# Unless required by applicable law or agreed to in", "function call, and not the function call itself. Returns: Whether", "additional args. \"\"\" element = self.GetLastHealthyElement() return element.HasCapacity() and not", "element = FireTraceElement(action=INTERACTIVE_MODE) self.elements.append(element) def AddError(self, error, args): element =", "a FireTraceElement are the instantiation of a class or the", "AddAccessedProperty(self, component, target, args, filename, lineno): element = FireTraceElement( component=component,", "\"\"\" def __init__(self, initial_component, name=None, separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element", "example to demonstrate the separator. Let's say you have a", "the action is defined, or None if N/A. lineno: The", "or the component takes in keyword-only arguments(e.g. argument with default", "args.extend(element.args) if element.HasSeparator() and include_separators: args.append(self.separator) if self.NeedsSeparator() and include_separators:", "callable. target: The name of the callable. args: The args", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "separator is an argument you can pass to a Fire", "lineno=None, error=None, capacity=None): \"\"\"Instantiates a FireTraceElement. Args: component: The result", "applies to instantiating a class. Args: component: The result of", "# Format is: {action} \"{target}\" ({filename}:{lineno}) string = self._action if", "action is defined, or None if N/A. lineno: The line", "arg in args) def NeedsSeparator(self): \"\"\"Returns whether a separator should", "and results in a new component. The final component is", "final component indicated by the trace. Returns: The last element", "when adding additional args. \"\"\" element = self.GetLastHealthyElement() return element.HasCapacity()", "function call. This function tells us whether we should add", "You may obtain a copy of the License at #", "the trace indicating that a component was called. Also applies", "or accessing a property. \"\"\" def __init__(self, initial_component, name=None, separator='-',", "demonstrate the separator. Let's say you have a function that", "None if N/A. lineno: The line number on which the", "self.elements.append(element) def AddCalledComponent(self, component, target, args, filename, lineno, capacity, action=CALLED_CALLABLE):", "The file in which the action is defined, or None", "is not an error. \"\"\" for element in reversed(self.elements): if", "the command is a function call, then adding an additional", "by Fire as well as returned by the Fire method.", "the trace used a separator. A separator is an argument", "sometimes would add an arg acting on the result of", "matches one of the argument of the component, or the", "classes for tracing the execution of a Fire execution. A", "of the separator. Here's an example to demonstrate the separator.", "will be None. \"\"\" from __future__ import absolute_import from __future__", "add an extra arg to the function call, and sometimes", "before adding additional arguments in order to make sure the", "class) taking place. target: (string) The name of the component", "which the callable is defined, or None if N/A. lineno:", "def __init__(self, initial_component, name=None, separator='-', verbose=False, show_help=False, show_trace=False): initial_trace_element =", "variable number of args, and you want to call that", "the Apache License, Version 2.0 (the \"License\"); # you may", "FireTraceElement( component=component, action=ACCESSED_PROPERTY, target=target, args=args, filename=filename, lineno=lineno, ) self.elements.append(element) def", "it: # in Python def display(arg1, arg2='!'): return arg1 +", "args. \"\"\" self.component = component self._action = action self._target =", "from __future__ import division from __future__ import print_function import pipes", "call, and sometimes would add an arg acting on the", "result of the function call. This function tells us whether", "self.elements[-1].AddSeparator() def _Quote(self, arg): if arg.startswith('--') and '=' in arg:", "the component from the last element of the trace.\"\"\" #", "by Fire during a single Fire execution. An action may" ]
[ "# it's a thing, we return the wrapped thing instead", "] default_ring_args = [{'replicas': 14}, {}] else: default_policies = [", "instead of 100 # Continue, even if the client sent", "pass class DebugLogger(FakeLogger): \"\"\"A simple stdout logging version of FakeLogger\"\"\"", "expect_sleep=None, response_sleep=None): \"\"\" :param status: the response status int, or", "'10.0.0.%d' % (i % self.nodes), 'port': self.port, 'replication_port': self.port, }", "path = '.' + path new_path = os.path.join(tempdir, path) subdir", "tuple of ([expect_status, ...], response_status) :param expect_sleep: float, time to", "from swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN!", "2.0 (the \"License\"); # you may not use this file", "if self.sent < 4: self.sent += 1 eventlet.sleep(value) return '", "= getattr(module, modname) if hasattr(module, attr): returns.append((module, attr, getattr(module, attr)))", "'device': 'sda', 'zone': x % 3, 'region': x % 2,", ">>> thing == True # True == True True >>>", "self.slowness) def __len__(self): return len(self.body) def __radd__(self, other): self.slowdown() return", "and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status =", "help tests get better isolation without having to think about", "1 lc = c return rv def connect_tcp(hostport): rv =", "floats :param response_sleep: float, time to eventlet sleep during response", "return connect @contextmanager def mocked_http_conn(*args, **kwargs): requests = [] def", "reference to the module with an instance of this class", "self.lines_dict.items() if len(msgs) > 0) def _store_in(store_name): def stub_fn(self, *args,", "# 9 total nodes (6 more past the initial 3)", "from hashlib import md5 import logging.handlers from six.moves.http_client import HTTPException", "rv def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return rv @contextmanager", "else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type':", "class DebugLogger(FakeLogger): \"\"\"A simple stdout logging version of FakeLogger\"\"\" def", "self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status return", "\\ kwargs.get('count', 12345) if not self.timestamp: # when timestamp is", "about it, here we're capturing the args required to *build*", "the expect and response stages of the connection. \"\"\" def", "got %r\" % rv) rv = rv + c if", "break else: raise SystemExit('ERROR: unable to find suitable PyECLib type'", "self.nodes = nodes self.port = port self.replicas = 6 self.part_power", "try: return object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'], name) def", "flush(self): pass def handleError(self, record): pass class DebugLogger(FakeLogger): \"\"\"A simple", "whitespace in the response. Also it should be easy to", "ip, 'port': port, 'method': method, 'path': path, 'headers': headers, 'qs':", "[{ 'region': 1, 'zone': 1, 'weight': 1.0, 'id': i, 'device':", "**kwargs) def _clear(self): self.log_dict = defaultdict(list) self.lines_dict = {'critical': [],", "of floats :param response_sleep: float, time to eventlet sleep during", "'device': 'sda%d' % i, 'ip': '10.0.0.%d' % (i % self.nodes),", "[call[0][0] for call in self.log_dict['increment']] def get_increment_counts(self): counts = {}", "self.level = logging.NOTSET if 'facility' in kwargs: self.facility = kwargs['facility']", ">>> thing.method() True >>> thing.attribute.method() True >>> thing.method().attribute True \"\"\"", "def close(self): pass timestamps_iter = iter(kwargs.get('timestamps') or ['1'] * len(code_iter))", "= None self.thread_locals = None self.parent = None store_in =", "0]] devs = [dev1, dev2] part_shift = 30 with closing(GzipFile(path,", "self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record) def flush(self): pass def handleError(self,", "\"\"\" @functools.wraps(f) def wrapped(*args, **kwargs): tempdir = mkdtemp() args =", "== 409: headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers)", "attributes if not isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep] *", "socket from tempfile import mkdtemp from shutil import rmtree from", "{} def get(self, key): return self.store.get(key) def keys(self): return self.store.keys()", "methods: update_stats = _store_in('update_stats') increment = _store_in('increment') decrement = _store_in('decrement')", "self.store = {} def get(self, key): return self.store.get(key) def keys(self):", "import mock as mocklib import inspect EMPTY_ETAG = md5().hexdigest() #", "= next(dev_ids) class FakeMemcache(object): def __init__(self): self.store = {} def", "'10.0.0.%d' % (i % self.nodes), 'replication_ip': '10.0.0.%d' % (i %", "status if isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status = status[-1]", "set a part_power when you setup your FakeRing the parts", "not None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise Exception('Test did", "= 0 while crlfs < 2: c = fd.read(1) if", "am_slow, value = self.get_slow() if am_slow: headers['content-length'] = '4' headers.update(self.headers)", "License for the specific language governing permissions and # limitations", "\"reset\" behavior with custom FakeRing's they can pass in their", "self._part_shift = 32 - part_power # 9 total nodes (6", "from swift.common import swob, utils from swift.common.ring import Ring, RingData", "iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter)) x =", "True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp =", "c return rv def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return", "for eclib_name in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break else:", "'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6000} dev1_updates, dev2_updates = devs", "if body_iter is None: body = static_body or '' else:", "mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status: raise", "do. if self.status in (507, 412, 409): self.expect_status = [status]", "i, node in enumerate(list(self._devs))] def get_more_nodes(self, part): for x in", "this log lvl to the LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE,", "the StatsD logging methods: update_stats = _store_in('update_stats') increment = _store_in('increment')", "isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers',", "nodes (6 more past the initial 3) is the cap,", "raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record) def flush(self): pass def", "self.get_slow() if am_slow: if self.received < 4: self.received += 1", "higher, or R^2 for R replicas self.set_replicas(replicas) self._reload() def _reload(self):", "- which inserts whitespace in the response. Also it should", "port, 'replication_port': port, 'device': 'sd' + (chr(ord('a') + x)), 'zone':", "or [None] * len(self.policies) def _setup_rings(self): \"\"\" Our tests tend", "self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self, *args, **kwargs):", "\"\"\" Our tests tend to use the policies rings like", "return repr(True) def __eq__(self, other): return other is True def", "when timestamp is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try:", "timestamps_iter = iter(kwargs.get('timestamps') or ['1'] * len(code_iter)) etag_iter = iter(kwargs.get('etags')", "def set_name(self, name): # don't touch _handlers self._name = name", "mocklib import inspect EMPTY_ETAG = md5().hexdigest() # try not to", "value) for module, attr in deletes: delattr(module, attr) class FakeStatus(object):", "self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep = None # be", "next(headers_iter) expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter) if status <=", "a clean ring setup. The TestCase can always \"tweak\" these", "etag = self.etag if not etag: if isinstance(self.body, str): etag", "= storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None] * len(self.policies) def", "def handle(self, record): self._handle(record) def flush(self): pass def handleError(self, record):", "finally: rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator to give a single", "= _clear # this is a public interface def get_lines_for_level(self,", "level, msgs in self.lines_dict.items() if len(msgs) > 0) def _store_in(store_name):", "backend service returns a status before reading # from the", "LOG_NOTICE. The python logging lvl is set to 25, just", "*args, **kwargs): return self def __repr__(*args, **kwargs): return repr(True) def", "ssl): req = { 'ip': ip, 'port': port, 'method': method,", "part_shift = 30 with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs,", "import get_config from swift.common import swob, utils from swift.common.ring import", "f: f.write(str(content)) try: yield tempdir finally: rmtree(tempdir) def with_tempdir(f): \"\"\"", "fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over status", "tmpfile(content): with NamedTemporaryFile('w', delete=False) as f: file_name = f.name f.write(str(content))", "in range(self.devices)] self._replica2part2dev_id = [ [None] * 2 ** self.part_power", "in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object): def __init__(self): self.store", "< 4: self.received += 1 eventlet.sleep(value) def getheader(self, name, default=None):", "self._reload() def _reload(self): self._rtime = time.time() def set_replicas(self, replicas): self.replicas", "1 eventlet.sleep(value) return ' ' rv = self.body[:amt] self.body =", "= next(etag_iter) headers = next(headers_iter) expect_headers = next(expect_headers_iter) timestamp =", "cls.setUp orig_tearDown = cls.tearDown def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if", "the cap, no matter if # this is set higher,", "storage_policy._POLICIES = self.policies def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class", "these instead of strings it will make reads take longer", "= self.get_slow() if am_slow: if self.received < 4: self.received +=", "reads take longer by the given amount. It should be", "response stages of the connection. \"\"\" def __init__(self, status, expect_sleep=None,", "ensure each test method gets a clean ring setup. The", "0, 1], [1, 0, 1, 0]] devs = [dev1, dev2]", "from tempfile import NamedTemporaryFile import time import eventlet from eventlet.green", "else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None] *", "return the wrapped thing instead of the decorator return decorator(thing_or_policies)", "os import copy import logging import errno from six.moves import", "get out of ring methods will actually be based on", "outside of the TestCase instance which can lead to some", "_get_inode(fd): if not isinstance(fd, int): try: fd = fd.fileno() except", "patched to map this log lvl to the LOG_NOTICE syslog", "returns = [] deletes = [] for key, value in", "their own personal playground - which can be a problem", "seen class decorators done - but it seems to cause", "read(self, amt=None): am_slow, value = self.get_slow() if am_slow: if self.sent", "= 'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility' in kwargs: self.facility", "def write_fake_ring(path, *devs): \"\"\" Pretty much just a two node,", "mocked_http_conn(*args, **kwargs): requests = [] def capture_requests(ip, port, method, path,", "a two node, two replica, 2 part power ring... \"\"\"", "behavior in a another module who imports time directly by", "from six.moves.http_client import HTTPException from swift.common import storage_policy from swift.common.storage_policy", "= os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir)", "See the License for the specific language governing permissions and", "if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object): \"\"\" Instances of", "[], 'warning': [], 'debug': [], 'notice': []} clear = _clear", "rmtree from swift.common.utils import Timestamp, NOTICE from test import get_config", "time.time() * 2 if hasattr(self, '_replica2part2dev_id'): return self._devs = [{", "thing != True # True != True False >>> thing", "Expect 100 header. # BufferedHttp and the proxy both see", "to in writing, software # distributed under the License is", "(Exception, eventlet.Timeout)): raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout()", "'\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp,", "to get by. \"\"\" def __init__(self, body, slowness): self.body =", "self._next_sleep else: return False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number):", "tempdir = mkdtemp() for path, content in zip(files, contents): if", "'10.0.0.%s' % x, 'replication_ip': '10.0.0.%s' % x, 'port': self._base_port +", "*build* a new FakeRing instances so we can ensure each", "default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass timestamps_iter = iter(kwargs.get('timestamps')", "body = next(body_iter) return FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers,", "the connection. \"\"\" def __init__(self, status, expect_sleep=None, response_sleep=None): \"\"\" :param", "3, 'region': x % 2, 'id': x} def write_fake_ring(path, *devs):", "if not data: raise IOError(errno.ENODATA, \"Fake IOError\") return data import", "case, when used as a decorator on the class it", "or agreed to in writing, software # distributed under the", "counts = {} for metric in self.get_increments(): if metric not", "rv = socket.socket() rv.connect(hostport) return rv @contextmanager def tmpfile(content): with", "self.lines_dict = {'critical': [], 'error': [], 'info': [], 'warning': [],", "port, 'method': method, 'path': path, 'headers': headers, 'qs': qs, 'ssl':", ")) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if", "to think about it, here we're capturing the args required", "if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only:", "think about it, here we're capturing the args required to", "next(body_iter) return FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send'))", "if level not in self.lines_dict: raise KeyError( \"Invalid log level", "each test method gets a clean ring setup. The TestCase", "*args, **kwargs): store_name = self.store_in[level] cargs = [msg] if any(args):", "status, expect_sleep=None, response_sleep=None): \"\"\" :param status: the response status int,", "is the more common way I've seen class decorators done", "body self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s):", "def read(self, amt=None): am_slow, value = self.get_slow() if am_slow: if", "attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler", "a named adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler =", "createLock(self): pass def emit(self, record): pass def _handle(self, record): try:", "compliance with the License. # You may obtain a copy", "with open(new_path, 'w') as f: f.write(str(content)) try: yield tempdir finally:", "modname) if hasattr(module, attr): returns.append((module, attr, getattr(module, attr))) else: deletes.append((module,", "expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter) if status <= 0:", "msgs) for level, msgs in self.lines_dict.items() if len(msgs) > 0)", "__ne__(self, other): return other is not True @contextmanager def mock(update):", "import sys from contextlib import contextmanager, closing from collections import", "= kwargs.get('missing_container', [False] * len(code_iter)) if not isinstance(x, (tuple, list)):", "enough contents to fill the files c = len(files) contents", "ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests", "self.expect_status, self.status = ([], status) self.explicit_expect_list = False if not", "or # implied. # See the License for the specific", "def _reload(self, *args, **kwargs): self._rtime = time.time() * 2 if", "- otherwise we exercise the real ring code, but ignore", "log level '%s'; valid levels are %s\" % (level, ',", "server would do. if self.status in (507, 412, 409): self.expect_status", "super is called from inside methods in the decorated class.", "= requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter)", "False if not self.expect_status: # when a swift backend service", "Timestamp, NOTICE from test import get_config from swift.common import swob,", "import six.moves.cPickle as pickle from gzip import GzipFile import mock", "FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param part_power:", "version of FakeLogger\"\"\" def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs)", "MockTrue(object): \"\"\" Instances of MockTrue evaluate like True Any attr", "else: body = next(body_iter) return FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers,", "path) subdir = os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path,", "eventlet.Timeout)): raise expect_status return expect_status class SlowBody(object): \"\"\" This will", "to some bled state. To help tests get better isolation", "new class that inherits from decorated class is the more", "returns.append((module, attr, getattr(module, attr))) else: deletes.append((module, attr)) setattr(module, attr, value)", "else: return False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return", "inside methods in the decorated class. \"\"\" orig_setUp = cls.setUp", "in kwargs: give_conn_fn = kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if argspec.keywords", "not use this file except in compliance with the License.", "%r %% %r' % ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def", "express or # implied. # See the License for the", "response_sleep=None): \"\"\" :param status: the response status int, or a", "for attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr)))", "range(self.replicas): ip = '10.0.0.%s' % x port = self._base_port +", "3, 'region': x % 2, 'id': x, }) @property def", "ValueError(\"didn't get two CRLFs; just got %r\" % rv) rv", "= self.expect_sleep_list.pop(0) if expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status =", "headers['content-length'] = '4' headers.update(self.headers) return headers.items() def get_slow(self): if 'slow'", "return True def readuntil2crlfs(fd): rv = '' lc = ''", "' ' rv = self.body[:amt] self.body = self.body[amt:] return rv", "def __ne__(self, other): return other is not True @contextmanager def", "you may not use this file except in compliance with", "iter you can add some eventlet sleep to the expect", "for the body inside of FakeConn if we wanted to", "= _store_in('update_stats') increment = _store_in('increment') decrement = _store_in('decrement') timing =", "self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility' in kwargs:", "**kwargs): return repr(True) def __eq__(self, other): return other is True", "body = static_body or '' else: body = next(body_iter) return", "under the License. \"\"\" Swift tests \"\"\" from __future__ import", "[ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args = [{}] elif with_ec_default:", "try: del self.store[key] except Exception: pass return True def readuntil2crlfs(fd):", "expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list)", "imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]: module", "\"\"\"get a named adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler", "super(FakeLogger, self)._log(level, msg, *args, **kwargs) def _clear(self): self.log_dict = defaultdict(list)", "return True, self._next_sleep else: return False, 0.01 if kwargs.get('slow') and", "object_ring on the policy definitions. \"\"\" for policy, fake_ring_arg in", "(i % self.nodes), 'replication_ip': '10.0.0.%d' % (i % self.nodes), 'port':", "] default_ring_args = [{}] elif with_ec_default: default_policies = [ ECStoragePolicy(0,", "of ring methods will actually be based on the path", "[dict(node, index=i) for i, node in enumerate(list(self._devs))] def get_more_nodes(self, part):", "import range import sys from contextlib import contextmanager, closing from", "'id': x} def write_fake_ring(path, *devs): \"\"\" Pretty much just a", "= xattr_data.get(inode, {}).get(k) if not data: raise IOError(errno.ENODATA, \"Fake IOError\")", "= _store_in('set_statsd_prefix') def get_increments(self): return [call[0][0] for call in self.log_dict['increment']]", "in the particular case of a patched TestCase class where", "== '\\n': crlfs += 1 lc = c return rv", "True Any attr accessed on an instance of MockTrue will", "isinstance(kwargs['slow'], list): if self._next_sleep is not None: return True, self._next_sleep", "status, etag=None, body='', timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None): if not", "exception if isinstance(status, (Exception, eventlet.Timeout)): raise status if isinstance(status, tuple):", "set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self): return [call[0][0] for call in", "base_port=1000): \"\"\" :param part_power: make part calculation based on the", "log lvl to the LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE, msg,", "during response \"\"\" # connect exception if isinstance(status, (Exception, eventlet.Timeout)):", "connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter return connect @contextmanager def mocked_http_conn(*args,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "if self._next_sleep is not None: return True, self._next_sleep else: return", "= {'critical': [], 'error': [], 'info': [], 'warning': [], 'debug':", "get_increment_counts(self): counts = {} for metric in self.get_increments(): if metric", "DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies,", "= _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try: return", "( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False,", "FakeLogger(logging.Logger, object): # a thread safe fake logger def __init__(self,", "thing == False # True == False False >>> thing", "}) if self.status // 100 == 2: headers['x-account-container-count'] = \\", "module, attr in deletes: delattr(module, attr) class FakeStatus(object): \"\"\" This", "!= True # True != True False >>> thing !=", "os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd, k, v): inode = _get_inode(fd)", "called from inside methods in the decorated class. \"\"\" orig_setUp", "1, 0]] devs = [dev1, dev2] part_shift = 30 with", "set_name(self, name): # don't touch _handlers self._name = name def", "in range(2 ** self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p] =", "'connection_id' in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag =", "return stub_fn # delegate to FakeLogger's mocks update_stats = _send_to_logger('update_stats')", "status) self.explicit_expect_list = False if not self.expect_status: # when a", "with our fake_http_connect, if you hand in these instead of", "from eventlet.green import socket from tempfile import mkdtemp from shutil", ">>> thing.attribute.method() True >>> thing.method().attribute True \"\"\" def __getattribute__(self, *args,", "delete(self, key): try: del self.store[key] except Exception: pass return True", "= body self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self,", "expect statuses just like a real backend server would do.", "Exception('Test did not consume all fake ' 'expect status: %r'", "= '\"' + md5(self.body).hexdigest() + '\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"'", "at the wrong time (i.e. in setup the global wasn't", "True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow, value", "\"\"\" Even if a test mocks time.time - you can", "self._next_sleep = None # be nice to trixy bits with", "tries to act like # our backend services and return", "in kwargs: if len(args) >= 7 and 'Content-Type' in args[6]:", "to eventlet sleep during expect, can be a iter of", "x, 'port': self._base_port + x, 'replication_port': self._base_port + x, 'device':", "None) try: if next(container_ts_iter) is False: headers['x-container-timestamp'] = '1' except", "Decorator to give a single test a tempdir as argument", "'.join(\"'%s'\" % lvl for lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def", "License. \"\"\" Swift tests \"\"\" from __future__ import print_function import", "in VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable to find suitable", "(c) 2010-2012 OpenStack Foundation # # Licensed under the Apache", "fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies:", "timestamp=self.timestamp, headers=headers) response.status = expect_status return response def getheaders(self): etag", "= False if not self.expect_status: # when a swift backend", "the Expect 100 header. # BufferedHttp and the proxy both", "from shutil import rmtree from swift.common.utils import Timestamp, NOTICE from", "'' else: body = next(body_iter) return FakeConn(status, etag, body=body, timestamp=timestamp,", "capture_requests) fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw',", "if you hand in one of these instead of a", "raise AssertionError('left over status %r' % left_over_status) def make_timestamp_iter(): return", "storage_policy from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools import", "dev_ids = itertools.cycle(range(self.devices)) for p in range(2 ** self.part_power): for", "[''] * c)[:c] tempdir = mkdtemp() for path, content in", "numbers import Number from tempfile import NamedTemporaryFile import time import", "find suitable PyECLib type' ' (none of %r found in", "= FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing, type): return self._patch_class(thing)", "self.get_slow() if am_slow: headers['content-length'] = '4' headers.update(self.headers) return headers.items() def", "to the patch_policies wrapper outside of the TestCase instance which", "= ([], status) self.explicit_expect_list = False if not self.expect_status: #", "self.formatter = logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def handle(self, record): self._handle(record)", "etag, 'x-works': 'yes', }) if self.status // 100 == 2:", "name == 'time': return UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__", "name): try: return object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'], name)", "0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': 6000} dev2 = {'id':", "return certain types of responses # as expect statuses just", "f) class FabricatedRing(Ring): \"\"\" When a FakeRing just won't do", "% left_over_status) def make_timestamp_iter(): return iter(Timestamp(t) for t in itertools.count(int(time.time())))", "self.get_slow() if am_slow: if self.sent < 4: self.sent += 1", "calls time.time logging.time = UnmockTimeModule() class FakeLogger(logging.Logger, object): # a", "nodes self.port = port self.replicas = 6 self.part_power = part_power", "**kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility'", "readuntil2crlfs(fd): rv = '' lc = '' crlfs = 0", "NullLoggingHandler(logging.Handler): def emit(self, record): pass class UnmockTimeModule(object): \"\"\" Even if", "next(conn_id_and_code_iter) if 'give_connect' in kwargs: give_conn_fn = kwargs['give_connect'] argspec =", "*args, **kwargs): return getattr(self.logger, name)(*args, **kwargs) return stub_fn # delegate", "import this module from swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never", "(chr(ord('a') + x)), 'zone': x % 3, 'region': x %", "if the client sent the Expect 100 header. # BufferedHttp", "body='', timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None): if not isinstance(status, FakeStatus):", "= give_send if 'slow' in kwargs and isinstance(kwargs['slow'], list): try:", "Also it should be easy to detect if you have", "'time': return UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__ calls time.time", "= static_body or '' else: body = next(body_iter) return FakeConn(status,", "2: headers['x-account-container-count'] = \\ kwargs.get('count', 12345) if not self.timestamp: #", "self.host = '1.2.3.4' self.port = '1234' self.sent = 0 self.received", "transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try:", "__repr__(*args, **kwargs): return repr(True) def __eq__(self, other): return other is", "= devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0,", "files c = len(files) contents = (list(contents) + [''] *", "= kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise exc", "False >>> thing != True # True != True False", "return f(*args, **kwargs) finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def", "defaultdict(list) self.lines_dict = {'critical': [], 'error': [], 'info': [], 'warning':", "When a FakeRing just won't do - you can fabricate", "interface def get_lines_for_level(self, level): if level not in self.lines_dict: raise", "pass def release(self): pass def createLock(self): pass def emit(self, record):", "= True else: self.expect_status, self.status = ([], status) self.explicit_expect_list =", "def get(self, key): return self.store.get(key) def keys(self): return self.store.keys() def", "way I've seen class decorators done - but it seems", "'port': port, 'method': method, 'path': path, 'headers': headers, 'qs': qs,", "for R replicas self.set_replicas(replicas) self._reload() def _reload(self): self._rtime = time.time()", "def readuntil2crlfs(fd): rv = '' lc = '' crlfs =", "# generate enough contents to fill the files c =", "'port': self._base_port + x, 'replication_port': self._base_port + x, 'device': 'sda',", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "is not True @contextmanager def mock(update): returns = [] deletes", "kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in kwargs: if len(args) >=", "self._base_port + x, 'replication_port': self._base_port + x, 'device': 'sda', 'zone':", "close(self): pass timestamps_iter = iter(kwargs.get('timestamps') or ['1'] * len(code_iter)) etag_iter", "if not etag: if isinstance(self.body, str): etag = '\"' +", "imports = key.split('.') attr = imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:])", "- self.part_power self._reload() def _reload(self, *args, **kwargs): self._rtime = time.time()", "0 while crlfs < 2: c = fd.read(1) if not", "path, headers, qs, ssl): req = { 'ip': ip, 'port':", "if they'd prefer to get the same \"reset\" behavior with", "of MockTrue will return a MockTrue instance. Any method called", "MockTrue will return a MockTrue instance. Any method called on", "409: headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status", "when used as a decorator on the class it seemed", "PatchPolicies(object): \"\"\" Why not mock.patch? In my case, when used", "next(container_ts_iter) is False: headers['x-container-timestamp'] = '1' except StopIteration: pass am_slow,", "*args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter = logging.Formatter( \"%(server)s %(levelname)s:", "emit(self, record): pass class UnmockTimeModule(object): \"\"\" Even if a test", "expect_headers or {} self.timestamp = timestamp self.connection_id = connection_id self.give_send", "return self.replicas def _get_part_nodes(self, part): return [dict(node, index=i) for i,", "inherits from decorated class is the more common way I've", "fake_ring_args or [None] * len(self.policies) def _setup_rings(self): \"\"\" Our tests", "syslog priority. \"\"\" self.log(NOTICE, msg, *args, **kwargs) def _log(self, level,", "ip = '10.0.0.%s' % x port = self._base_port + x", "utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object): \"\"\" Instances of MockTrue", "True # True == True True >>> thing == False", "= time.time() * 2 if hasattr(self, '_replica2part2dev_id'): return self._devs =", "we return the wrapped thing instead of the decorator return", "this is set higher, or R^2 for R replicas self.set_replicas(replicas)", "response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status return response", "public interface def get_lines_for_level(self, level): if level not in self.lines_dict:", "import eventlet from eventlet.green import socket from tempfile import mkdtemp", "(list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})]", "[None] * 2 ** self.part_power for i in range(self.replicas) ]", "# try not to import this module from swift if", "patched TestCase class where the FakeRing objects are scoped in", "= \\ kwargs.get('count', 12345) if not self.timestamp: # when timestamp", "file except in compliance with the License. # You may", "pass in their own fake_ring_args to patch_policies instead of setting", "FakeConn(object): def __init__(self, status, etag=None, body='', timestamp='1', headers=None, expect_headers=None, connection_id=None,", "types of responses # as expect statuses just like a", "'1234' self.sent = 0 self.received = 0 self.etag = etag", "fromlist=imports[1:]) for modname in imports[1:]: module = getattr(module, modname) if", "'zone': x % 3, 'region': x % 2, 'id': x}", "file_name = f.name f.write(str(content)) try: yield file_name finally: os.unlink(file_name) xattr_data", "[100, 100] # setup sleep attributes if not isinstance(expect_sleep, (list,", "return decorator else: # it's a thing, we return the", "rv + c if c == '\\r' and lc !=", "'127.0.0.1', 'port': 6000} dev2 = {'id': 0, 'zone': 0, 'device':", "value = self.get_slow() if am_slow: headers['content-length'] = '4' headers.update(self.headers) return", "found in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE =", "kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0) except IndexError:", "enumerate(code_iter) static_body = kwargs.get('body', None) body_iter = kwargs.get('body_iter', None) if", "with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status:", "= storage_policy._POLICIES storage_policy._POLICIES = self.policies def __exit__(self, *args): storage_policy._POLICIES =", "{} for metric in self.get_increments(): if metric not in counts:", "body_iter = iter(body_iter) def connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1)", "self.received = 0 self.etag = etag self.body = body self.headers", "import inspect EMPTY_ETAG = md5().hexdigest() # try not to import", "metric in self.get_increments(): if metric not in counts: counts[metric] =", "exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise Exception('test') if", "swob, utils from swift.common.ring import Ring, RingData from hashlib import", "= { 'ip': ip, 'port': port, 'method': method, 'path': path,", "you setup your FakeRing the parts you get out of", "self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag':", "replicas=6, devices=8, nodes=4, port=6000, part_power=4): self.devices = devices self.nodes =", "rv = self.body[:amt] self.body = self.body[amt:] return rv def send(self,", "stages of the connection. \"\"\" def __init__(self, status, expect_sleep=None, response_sleep=None):", "= [{}, {}] fake_ring_args = fake_ring_args or default_ring_args decorator =", "* len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None] * len(code_iter)) if", "= max_more_nodes self._part_shift = 32 - part_power # 9 total", "= mkdtemp() for path, content in zip(files, contents): if os.path.isabs(path):", "finally: os.unlink(file_name) xattr_data = {} def _get_inode(fd): if not isinstance(fd,", "msg, *args, **kwargs) def _log(self, level, msg, *args, **kwargs): store_name", "def setFormatter(self, obj): self.formatter = obj def close(self): self._clear() def", "x in range(self.replicas, (self.replicas + self.max_more_nodes)): yield {'ip': '10.0.0.%s' %", "FakeConn if we wanted to do something smarter than just", "cargs.extend(args) captured = dict(kwargs) if 'exc_info' in kwargs and \\", "unable to find suitable PyECLib type' ' (none of %r", "0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': 6000} dev2", "[False] * len(code_iter)) if not isinstance(x, (tuple, list)): x =", "def _get_inode(fd): if not isinstance(fd, int): try: fd = fd.fileno()", "([expect_status, ...], response_status) :param expect_sleep: float, time to eventlet sleep", "value = self.get_slow() if am_slow: if self.received < 4: self.received", "crlfs < 2: c = fd.read(1) if not c: raise", "= md5().hexdigest() # try not to import this module from", "increment = _store_in('increment') decrement = _store_in('decrement') timing = _store_in('timing') timing_since", "will # respond with that status line immediately instead of", "thing): if isinstance(thing, type): return self._patch_class(thing) else: return self._patch_method(thing) def", "raise self.status return self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if", "replicas self._devs = [] for x in range(self.replicas): ip =", "[msg] if any(args): cargs.extend(args) captured = dict(kwargs) if 'exc_info' in", "an instance of MockTrue will return a MockTrue instance. Any", "= name def acquire(self): pass def release(self): pass def createLock(self):", "status int, or a tuple of ([expect_status, ...], response_status) :param", "than the current slow kwarg - which inserts whitespace in", "tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp = setUp cls.tearDown =", "'debug': [], 'notice': []} clear = _clear # this is", "os.unlink(file_name) xattr_data = {} def _get_inode(fd): if not isinstance(fd, int):", "*args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn # mock out the", "a tuple of ([expect_status, ...], response_status) :param expect_sleep: float, time", "= next(expect_headers_iter) timestamp = next(timestamps_iter) if status <= 0: raise", "immediately instead of 100 # Continue, even if the client", "'\\r' and c == '\\n': crlfs += 1 lc =", "better isolation without having to think about it, here we're", "devs, part_shift), f) class FabricatedRing(Ring): \"\"\" When a FakeRing just", "self.etag if not etag: if isinstance(self.body, str): etag = '\"'", "level not in self.lines_dict: raise KeyError( \"Invalid log level '%s';", "range(self.devices)] self._replica2part2dev_id = [ [None] * 2 ** self.part_power for", "of FakeConn if we wanted to do something smarter than", "% 2, 'id': x, }) @property def replica_count(self): return self.replicas", "rv def send(self, amt=None): if self.give_send: self.give_send(self.connection_id, amt) am_slow, value", "port, 'device': 'sd' + (chr(ord('a') + x)), 'zone': x %", "%r found in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE", "(the \"License\"); # you may not use this file except", "logging methods: update_stats = _store_in('update_stats') increment = _store_in('increment') decrement =", "yield True finally: for module, attr, value in returns: setattr(module,", "not self.expect_status: # when a swift backend service returns a", "these (or a subclass) for the body inside of FakeConn", "= kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in", "else: # it's a thing, we return the wrapped thing", "import errno from six.moves import range import sys from contextlib", "md5().hexdigest() # try not to import this module from swift", "'9876543210', 'etag': etag, 'x-works': 'yes', }) if self.status // 100", "expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter return connect @contextmanager def", "or ['1'] * len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None] *", "class where the FakeRing objects are scoped in the call", "on an instance of MockTrue will return a MockTrue instance.", "cls.tearDown def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if not getattr(cls_self, '_policies_patched',", "= len(files) contents = (list(contents) + [''] * c)[:c] tempdir", "Iterable import itertools from numbers import Number from tempfile import", "tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args,", "== '\\r' and c == '\\n': crlfs += 1 lc", "'4' headers.update(self.headers) return headers.items() def get_slow(self): if 'slow' in kwargs", "\"\"\" Creating a new class that inherits from decorated class", "except AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get a named", "- but it seems to cause infinite recursion when super", "in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for p in range(2", "# # Unless required by applicable law or agreed to", "# mock out the StatsD logging methods: update_stats = _store_in('update_stats')", "= [] deletes = [] for key, value in update.items():", "the response status int, or a tuple of ([expect_status, ...],", "on the policy definitions. \"\"\" for policy, fake_ring_arg in zip(self.policies,", "obj): self.formatter = obj def close(self): self._clear() def set_name(self, name):", "self.body = body self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness) def", "def __init__(self, status, expect_sleep=None, response_sleep=None): \"\"\" :param status: the response", "argument to test method. \"\"\" @functools.wraps(f) def wrapped(*args, **kwargs): tempdir", "attr))) else: deletes.append((module, attr)) setattr(module, attr, value) try: yield True", "give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers = next(headers_iter) expect_headers =", "storage_policy._POLICIES = self._orig_POLICIES cls.setUp = setUp cls.tearDown = tearDown return", "'sda', 'zone': x % 3, 'region': x % 2, 'id':", "**kwargs) fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status", "instead of strings it will make reads take longer by", "int, or a tuple of ([expect_status, ...], response_status) :param expect_sleep:", "k): inode = _get_inode(fd) data = xattr_data.get(inode, {}).get(k) if not", "0 self.etag = etag self.body = body self.headers = headers", "'slow' in kwargs and isinstance(kwargs['slow'], list): if self._next_sleep is not", "self.log(NOTICE, msg, *args, **kwargs) def _log(self, level, msg, *args, **kwargs):", "the str/buffer api enough to get by. \"\"\" def __init__(self,", "+ 1 return self.store[key] @contextmanager def soft_lock(self, key, timeout=0, retries=5):", "(self.replicas + self.max_more_nodes)): yield {'ip': '10.0.0.%s' % x, 'replication_ip': '10.0.0.%s'", "requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter) if", "'slow' in kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0)", "MockTrue instance. Any method called on an instance of MockTrue", "%s\" % (level, ', '.join(\"'%s'\" % lvl for lvl in", "implied. # See the License for the specific language governing", "statuses just like a real backend server would do. if", "def __init__(self, *args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level =", "{'id': 0, 'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6000}", "self._reload() def _reload(self, *args, **kwargs): self._rtime = time.time() * 2", "thing.attribute True >>> thing.method() True >>> thing.attribute.method() True >>> thing.method().attribute", "return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies = [ StoragePolicy(0, name='legacy',", "replicas): self.replicas = replicas self._devs = [] for x in", "to patch setUp at the wrong time (i.e. in setup", "= 32 - self.part_power self._reload() def _reload(self, *args, **kwargs): self._rtime", "of 100 # Continue, even if the client sent the", "* len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else:", "= defaultdict(list) self.lines_dict = {'critical': [], 'error': [], 'info': [],", "rings in setUp - or if they'd prefer to get", "s): return SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body) def __radd__(self,", "self.replicas = replicas self._devs = [] for x in range(self.replicas):", "parts you get out of ring methods will actually be", "[] deletes = [] for key, value in update.items(): imports", "response_sleep def get_response_status(self): if self.response_sleep is not None: eventlet.sleep(self.response_sleep) if", "but ignore the result and return 1. \"\"\" self._base_port =", "To help tests get better isolation without having to think", "= self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000):", "self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works':", "self.status = ([], status) self.explicit_expect_list = False if not self.expect_status:", "'region': x % 2, 'id': x} def write_fake_ring(path, *devs): \"\"\"", "'port': 6000} dev2 = {'id': 0, 'zone': 0, 'device': 'sdb1',", "= list(status[:-1]) self.status = status[-1] self.explicit_expect_list = True else: self.expect_status,", "self.expect_status and self.explicit_expect_list: raise Exception('Test did not consume all fake", "- part_power # 9 total nodes (6 more past the", "FakeStatus(status) self._status = status self.reason = 'Fake' self.host = '1.2.3.4'", "from tempfile import mkdtemp from shutil import rmtree from swift.common.utils", "self.parent = None store_in = { logging.ERROR: 'error', logging.WARNING: 'warning',", "AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ]", "expect_sleep: float, time to eventlet sleep during expect, can be", "'sdb1', 'ip': '127.0.0.1', 'port': 6000} dev1_updates, dev2_updates = devs or", "*args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET if", "self.headers = headers or {} self.expect_headers = expect_headers or {}", "return self def __repr__(*args, **kwargs): return repr(True) def __eq__(self, other):", "cls.setUp = setUp cls.tearDown = tearDown return cls def _patch_method(self,", "to the module with an instance of this class \"\"\"", "= os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as", "body, slowness): self.body = body self.slowness = slowness def slowdown(self):", "False # True != False True >>> thing.attribute True >>>", "[{'replicas': 14}, {}] else: default_policies = [ StoragePolicy(0, name='nulo', is_default=True),", "as f: f.write(str(content)) try: yield tempdir finally: rmtree(tempdir) def with_tempdir(f):", "headers_iter = iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})] * len(code_iter))", "+= 1 lc = c return rv def connect_tcp(hostport): rv", "self._base_port + x self._devs.append({ 'ip': ip, 'replication_ip': ip, 'port': port,", "'\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length': len(self.body),", "enough to get by. \"\"\" def __init__(self, body, slowness): self.body", "_store_in('update_stats') increment = _store_in('increment') decrement = _store_in('decrement') timing = _store_in('timing')", "timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None): if not isinstance(status, FakeStatus): status", "you have one of these (or a subclass) for the", "wasn't patched yet) \"\"\" def __init__(self, policies, fake_ring_args=None): if isinstance(policies,", "ECStoragePolicy, VALID_EC_TYPES) import functools import six.moves.cPickle as pickle from gzip", "= _store_in('increment') decrement = _store_in('decrement') timing = _store_in('timing') timing_since =", "len(files) contents = (list(contents) + [''] * c)[:c] tempdir =", "len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def get_response_status(self): if", "to detect if you have one of these (or a", "name='unu'), ] default_ring_args = [{}, {}] fake_ring_args = fake_ring_args or", "409): self.expect_status = [status] else: self.expect_status = [100, 100] #", "Unless required by applicable law or agreed to in writing,", "= 32 - part_power # 9 total nodes (6 more", "def flush(self): pass def handleError(self, record): pass class DebugLogger(FakeLogger): \"\"\"A", "def fake_syslog_handler(): for attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr,", "is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args = [{}, {}] fake_ring_args =", "can be a problem in the particular case of a", "inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id'] = i", "functools import six.moves.cPickle as pickle from gzip import GzipFile import", "lead to some bled state. To help tests get better", "@contextmanager def mock(update): returns = [] deletes = [] for", "patch setUp at the wrong time (i.e. in setup the", "the specific language governing permissions and # limitations under the", "more common way I've seen class decorators done - but", "logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def handle(self, record): self._handle(record) print(self.formatter.format(record)) class", "to the \"codes\" iter you can add some eventlet sleep", "% (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return self.status", "class UnmockTimeModule(object): \"\"\" Even if a test mocks time.time -", "called on an instance of MockTrue will return a MockTrue", "to get the same \"reset\" behavior with custom FakeRing's they", "record): pass class UnmockTimeModule(object): \"\"\" Even if a test mocks", "which inserts whitespace in the response. Also it should be", "to test method. \"\"\" @functools.wraps(f) def wrapped(*args, **kwargs): tempdir =", "or 'connection_id' in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag", "len(self.policies) def _setup_rings(self): \"\"\" Our tests tend to use the", "{ 'ip': ip, 'port': port, 'method': method, 'path': path, 'headers':", "= _get_inode(fd) data = xattr_data.get(inode, {}) data[k] = v xattr_data[inode]", "_getxattr(fd, k): inode = _get_inode(fd) data = xattr_data.get(inode, {}).get(k) if", "the given amount. It should be a little bit easier", "a subclass) for the body inside of FakeConn if we", "touch _handlers self._name = name def acquire(self): pass def release(self):", "self.log_dict = defaultdict(list) self.lines_dict = {'critical': [], 'error': [], 'info':", "f(*args, **kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES return mywrapper def __enter__(self):", "= kwargs.get('body', None) body_iter = kwargs.get('body_iter', None) if body_iter: body_iter", "In my case, when used as a decorator on the", "or R^2 for R replicas self.set_replicas(replicas) self._reload() def _reload(self): self._rtime", "requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests = requests", "not None: return True, self._next_sleep else: return False, 0.01 if", "getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass timestamps_iter", "= part_power self._part_shift = 32 - self.part_power self._reload() def _reload(self,", "+ path new_path = os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if", "just duck-type the str/buffer api enough to get by. \"\"\"", "one of these instead of a status int or status", "FabricatedRing(Ring): \"\"\" When a FakeRing just won't do - you", "the more common way I've seen class decorators done -", "= cls.setUp orig_tearDown = cls.tearDown def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES", "getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get a named adapted debug logger\"\"\"", "GzipFile import mock as mocklib import inspect EMPTY_ETAG = md5().hexdigest()", "self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is not", "module = getattr(module, modname) if hasattr(module, attr): returns.append((module, attr, getattr(module,", "def get_response_status(self): if self.response_sleep is not None: eventlet.sleep(self.response_sleep) if self.expect_status", "fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies =", "return self.store.get(key) def keys(self): return self.store.keys() def set(self, key, value,", "__getitem__(self, s): return SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body) def", "import defaultdict, Iterable import itertools from numbers import Number from", "Instances of MockTrue evaluate like True Any attr accessed on", "node_iter's eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc') if exc: if", "True >>> thing == False # True == False False", "iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'),", "'10.0.0.%s' % x, 'port': self._base_port + x, 'replication_port': self._base_port +", "= devices self.nodes = nodes self.port = port self.replicas =", "= \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')):", "of FakeLogger\"\"\" def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter", "= self.policies def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring):", "if not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched", "self def __repr__(*args, **kwargs): return repr(True) def __eq__(self, other): return", "0, 'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6000} dev1_updates,", "these error statuses # when they call getexpect, so our", "pass am_slow, value = self.get_slow() if am_slow: headers['content-length'] = '4'", "orig_tearDown = cls.tearDown def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if not", "body inside of FakeConn if we wanted to do something", "# from the body (mostly an error response) eventlet.wsgi will", "= iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})] * len(code_iter)) if", "status %r' % left_over_status) def make_timestamp_iter(): return iter(Timestamp(t) for t", "x % 3, 'region': x % 2, 'id': x} def", "UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__ calls time.time logging.time =", "response. Also it should be easy to detect if you", "'error': [], 'info': [], 'warning': [], 'debug': [], 'notice': []}", "storage_policy._POLICIES = self.policies self._setup_rings() return f(*args, **kwargs) finally: storage_policy._POLICIES =", "if expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if", "path, content in zip(files, contents): if os.path.isabs(path): path = '.'", "getattr(module, modname) if hasattr(module, attr): returns.append((module, attr, getattr(module, attr))) else:", "copy import logging import errno from six.moves import range import", "def get_lines_for_level(self, level): if level not in self.lines_dict: raise KeyError(", "< 2: c = fd.read(1) if not c: raise ValueError(\"didn't", "time directly by monkey patching it's imported reference to the", "* 2 if hasattr(self, '_replica2part2dev_id'): return self._devs = [{ 'region':", "def getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass", "\"\"\" Pretty much just a two node, two replica, 2", "self.store_in[level] cargs = [msg] if any(args): cargs.extend(args) captured = dict(kwargs)", "'headers': headers, 'qs': qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests)", "mocks time.time - you can restore unmolested behavior in a", "__init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param part_power: make part", "restore unmolested behavior in a another module who imports time", "a problem in the particular case of a patched TestCase", "fake_syslog_handler(): for attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler,", "= [expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) <", "patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand',", "you can add some eventlet sleep to the expect and", "am_slow, value = self.get_slow() if am_slow: if self.sent < 4:", "self.policies self._setup_rings() return f(*args, **kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES return", "something smarter than just duck-type the str/buffer api enough to", "headers, qs, ssl): req = { 'ip': ip, 'port': port,", "def _store_in(store_name): def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn", "timeout=0, retries=5): yield True def delete(self, key): try: del self.store[key]", "'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', } def notice(self,", "\"\"\" This will work with our fake_http_connect, if you hand", "% lvl for lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self):", "a tempdir as argument to test method. \"\"\" @functools.wraps(f) def", "class MockTrue(object): \"\"\" Instances of MockTrue evaluate like True Any", "if isinstance(status, (Exception, eventlet.Timeout)): raise status if isinstance(status, tuple): self.expect_status", "backend services and return certain types of responses # as", "= list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep", "do something smarter than just duck-type the str/buffer api enough", "replica2part2dev_id = [[0, 1, 0, 1], [1, 0, 1, 0]]", ">>> thing != True # True != True False >>>", "name)(*args, **kwargs) return stub_fn # delegate to FakeLogger's mocks update_stats", "def __init__(self, body, slowness): self.body = body self.slowness = slowness", "record): pass def _handle(self, record): try: line = record.getMessage() except", "return FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter", "**kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter = logging.Formatter( \"%(server)s %(levelname)s: %(message)s\")", "contextlib import contextmanager, closing from collections import defaultdict, Iterable import", "False): storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self) def", "'warning': [], 'debug': [], 'notice': []} clear = _clear #", "to fill the files c = len(files) contents = (list(contents)", "try: return f(*args, **kwargs) finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler):", "= next(timestamps_iter) if status <= 0: raise HTTPException() if body_iter", "= _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self): return [call[0][0] for", "a thread safe fake logger def __init__(self, *args, **kwargs): self._clear()", "is not None: return True, self._next_sleep else: return False, 0.01", "the current slow kwarg - which inserts whitespace in the", "devices=8, nodes=4, port=6000, part_power=4): self.devices = devices self.nodes = nodes", ">>> thing = MockTrue() >>> thing True >>> thing ==", "always \"tweak\" these fresh rings in setUp - or if", "time.time logging.time = UnmockTimeModule() class FakeLogger(logging.Logger, object): # a thread", "= replicas self._devs = [] for x in range(self.replicas): ip", "in range(self.replicas): ip = '10.0.0.%s' % x port = self._base_port", "- or if they'd prefer to get the same \"reset\"", "timestamp self.connection_id = connection_id self.give_send = give_send if 'slow' in", "def set_replicas(self, replicas): self.replicas = replicas self._devs = [] for", "self.status = self._status.get_response_status() return self def getexpect(self): expect_status = self._status.get_expect_status()", "1 return self.store[key] @contextmanager def soft_lock(self, key, timeout=0, retries=5): yield", "# BufferedHttp and the proxy both see these error statuses", "monkey patched to map this log lvl to the LOG_NOTICE", "You may obtain a copy of the License at #", "dict((level, msgs) for level, msgs in self.lines_dict.items() if len(msgs) >", "as mocklib import inspect EMPTY_ETAG = md5().hexdigest() # try not", "os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with", "str): etag = '\"' + md5(self.body).hexdigest() + '\"' else: etag", "# when timestamp is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None)", "our FakeConn tries to act like # our backend services", "'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', }", "__getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'],", "if a test mocks time.time - you can restore unmolested", "if status <= 0: raise HTTPException() if body_iter is None:", "name='unu'), ] default_ring_args = [{'replicas': 14}, {}] else: default_policies =", "playground - which can be a problem in the particular", "xattr_data = {} def _get_inode(fd): if not isinstance(fd, int): try:", "part_power self._part_shift = 32 - self.part_power self._reload() def _reload(self, *args,", "return self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is", "to give a single test a tempdir as argument to", "if self.received < 4: self.received += 1 eventlet.sleep(value) def getheader(self,", "x, 'replication_port': self._base_port + x, 'device': 'sda', 'zone': x %", "getexpect(self): expect_status = self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status ==", "= next(conn_id_and_code_iter) if 'give_connect' in kwargs: give_conn_fn = kwargs['give_connect'] argspec", "or if they'd prefer to get the same \"reset\" behavior", "', '.join(\"'%s'\" % lvl for lvl in sorted(self.lines_dict)))) return self.lines_dict[level]", "return self._devs = [{ 'region': 1, 'zone': 1, 'weight': 1.0,", "can ensure each test method gets a clean ring setup.", "common way I've seen class decorators done - but it", "cls.tearDown = tearDown return cls def _patch_method(self, f): @functools.wraps(f) def", "tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})] *", "iter(kwargs.get('timestamps') or ['1'] * len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None]", "The TestCase can always \"tweak\" these fresh rings in setUp", "= 0 self.etag = etag self.body = body self.headers =", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "clean ring setup. The TestCase can always \"tweak\" these fresh", "os.fstat(fd).st_ino def _setxattr(fd, k, v): inode = _get_inode(fd) data =", "with an instance of this class \"\"\" _orig_time = time.time", "base_port self.max_more_nodes = max_more_nodes self._part_shift = 32 - part_power #", "return UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__ calls time.time logging.time", "'notice': []} clear = _clear # this is a public", "headers.items() def get_slow(self): if 'slow' in kwargs and isinstance(kwargs['slow'], list):", "body_iter: body_iter = iter(body_iter) def connect(*args, **ckwargs): if kwargs.get('slow_connect', False):", "BufferedHttp and the proxy both see these error statuses #", "'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in", "logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger,", "import socket from tempfile import mkdtemp from shutil import rmtree", "capturing the args required to *build* a new FakeRing instances", "kwargs: if len(args) >= 7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type'])", "if eclib_name in VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable to", "HTTPException from swift.common import storage_policy from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy,", "it seemed to patch setUp at the wrong time (i.e.", "range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object): def __init__(self): self.store =", "be a iter of floats :param response_sleep: float, time to", "6000} dev1_updates, dev2_updates = devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates)", "your tests needs. \"\"\" def __init__(self, replicas=6, devices=8, nodes=4, port=6000,", "= cls.tearDown def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if not getattr(cls_self,", "sleep to the expect and response stages of the connection.", "have one of these (or a subclass) for the body", "a decorator on the class it seemed to patch setUp", "= [ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args = [{}] elif", "is not None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise Exception('Test", "'10.0.0.%s' % x port = self._base_port + x self._devs.append({ 'ip':", "kwargs)) return stub_fn # mock out the StatsD logging methods:", "status = next(conn_id_and_code_iter) if 'give_connect' in kwargs: give_conn_fn = kwargs['give_connect']", "I've seen class decorators done - but it seems to", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "tempfile import mkdtemp from shutil import rmtree from swift.common.utils import", "License. # You may obtain a copy of the License", "with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args)", "= self.policies self._setup_rings() return f(*args, **kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES", "as expect statuses just like a real backend server would", "seemed to patch setUp at the wrong time (i.e. in", "return wrapped class NullLoggingHandler(logging.Handler): def emit(self, record): pass class UnmockTimeModule(object):", "priority. \"\"\" self.log(NOTICE, msg, *args, **kwargs) def _log(self, level, msg,", "headers = swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp':", "iter(kwargs.get('etags') or [None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter", "{}] fake_ring_args = fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args)", "if not isinstance(status, FakeStatus): status = FakeStatus(status) self._status = status", "Exception: pass return True def readuntil2crlfs(fd): rv = '' lc", "log message %r %% %r' % ( record.msg, record.args)) raise", "isinstance(self.body, str): etag = '\"' + md5(self.body).hexdigest() + '\"' else:", "self.thread_locals = None self.parent = None store_in = { logging.ERROR:", "if # this is set higher, or R^2 for R", "backend server would do. if self.status in (507, 412, 409):", "\"\"\" Convenience function for syslog priority LOG_NOTICE. The python logging", "dict(kwargs) if 'exc_info' in kwargs and \\ not isinstance(kwargs['exc_info'], tuple):", "certain types of responses # as expect statuses just like", "= xattr_data.get(inode, {}) data[k] = v xattr_data[inode] = data def", "} requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests =", "= PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator else: #", "6 self.part_power = part_power self._part_shift = 32 - self.part_power self._reload()", "else: raise SystemExit('ERROR: unable to find suitable PyECLib type' '", "*args, **kwargs) def _clear(self): self.log_dict = defaultdict(list) self.lines_dict = {'critical':", "set to 25, just above info. SysLogHandler is monkey patched", "= iter(body_iter) def connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if", "_get_inode(fd) data = xattr_data.get(inode, {}) data[k] = v xattr_data[inode] =", "status int tuple to the \"codes\" iter you can add", "contents): if os.path.isabs(path): path = '.' + path new_path =", "if you have one of these (or a subclass) for", "close(self): self._clear() def set_name(self, name): # don't touch _handlers self._name", "= _send_to_logger('update_stats') increment = _send_to_logger('increment') decrement = _send_to_logger('decrement') timing =", "our backend services and return certain types of responses #", "'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes',", "gets a clean ring setup. The TestCase can always \"tweak\"", "VALID_EC_TYPES) import functools import six.moves.cPickle as pickle from gzip import", "if not c: raise ValueError(\"didn't get two CRLFs; just got", "= port self.replicas = 6 self.part_power = part_power self._part_shift =", "def mocked_http_conn(*args, **kwargs): requests = [] def capture_requests(ip, port, method,", "_setxattr(fd, k, v): inode = _get_inode(fd) data = xattr_data.get(inode, {})", "if isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'):", "(list, tuple)): expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep)", "particular case of a patched TestCase class where the FakeRing", "thing.attribute.method() True >>> thing.method().attribute True \"\"\" def __getattribute__(self, *args, **kwargs):", "stub_fn # delegate to FakeLogger's mocks update_stats = _send_to_logger('update_stats') increment", "= tearDown return cls def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args,", "SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body) def __radd__(self, other): self.slowdown()", "eventlet sleep during response \"\"\" # connect exception if isinstance(status,", "type' ' (none of %r found in %r)' % (", "FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status return response def getheaders(self):", "lvl to the LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE, msg, *args,", "\"\"\" def __init__(self, body, slowness): self.body = body self.slowness =", "[] def capture_requests(ip, port, method, path, headers, qs, ssl): req", "len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test':", "can pass in their own fake_ring_args to patch_policies instead of", "class FakeConn(object): def __init__(self, status, etag=None, body='', timestamp='1', headers=None, expect_headers=None,", "eclib_name in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break else: raise", "wrong time (i.e. in setup the global wasn't patched yet)", "'sd' + (chr(ord('a') + x)), 'zone': x % 3, 'region':", "a MockTrue instance. >>> thing = MockTrue() >>> thing True", "'port': 6000} dev1_updates, dev2_updates = devs or ({}, {}) dev1.update(dev1_updates)", "self.status return self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep", "setUp at the wrong time (i.e. in setup the global", "Number): return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self, amt=None):", "the policy definitions. \"\"\" for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args):", "return ' ' rv = self.body[:amt] self.body = self.body[amt:] return", "eventlet.Timeout() self.status = self._status.get_response_status() return self def getexpect(self): expect_status =", "'%s'; valid levels are %s\" % (level, ', '.join(\"'%s'\" %", "orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp = setUp", "= iter([kwargs.get('expect_headers', {})] * len(code_iter)) x = kwargs.get('missing_container', [False] *", "acquire(self): pass def release(self): pass def createLock(self): pass def emit(self,", "handleError(self, record): pass class DebugLogger(FakeLogger): \"\"\"A simple stdout logging version", "policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing, type): return", "logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice',", "\"\"\"A simple stdout logging version of FakeLogger\"\"\" def __init__(self, *args,", "stdout logging version of FakeLogger\"\"\" def __init__(self, *args, **kwargs): FakeLogger.__init__(self,", "\"\"\" Decorator to give a single test a tempdir as", "name): if name == 'time': return UnmockTimeModule._orig_time return getattr(time, name)", "def notice(self, msg, *args, **kwargs): \"\"\" Convenience function for syslog", "timing_since = _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def", "debug_logger(name='test'): \"\"\"get a named adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name)", "decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator else:", "fake_http_connect(*args, **kwargs) fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn", "in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break else: raise SystemExit('ERROR:", "_store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self): return [call[0][0] for call", "two replica, 2 part power ring... \"\"\" dev1 = {'id':", "= headers or {} self.expect_headers = expect_headers or {} self.timestamp", "in the response. Also it should be easy to detect", "and return certain types of responses # as expect statuses", "with that status line immediately instead of 100 # Continue,", "expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status,", "if next(container_ts_iter) is False: headers['x-container-timestamp'] = '1' except StopIteration: pass", "etag = next(etag_iter) headers = next(headers_iter) expect_headers = next(expect_headers_iter) timestamp", "!= True False >>> thing != False # True !=", "add some eventlet sleep to the expect and response stages", "data def _getxattr(fd, k): inode = _get_inode(fd) data = xattr_data.get(inode,", "self.expect_status = [status] else: self.expect_status = [100, 100] # setup", "= self._base_port + x self._devs.append({ 'ip': ip, 'replication_ip': ip, 'port':", "bits with node_iter's eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc') if", "headers_iter = iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)):", "= 30 with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift),", "getattr(time, name) # logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule() class", "NamedTemporaryFile('w', delete=False) as f: file_name = f.name f.write(str(content)) try: yield", "_send_to_logger('update_stats') increment = _send_to_logger('increment') decrement = _send_to_logger('decrement') timing = _send_to_logger('timing')", "# connect exception if isinstance(status, (Exception, eventlet.Timeout)): raise status if", "current slow kwarg - which inserts whitespace in the response.", "self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return expect_status class", "sleep during response \"\"\" # connect exception if isinstance(status, (Exception,", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "if 'exc_info' in kwargs and \\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info']", "_send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self, name):", "value in update.items(): imports = key.split('.') attr = imports.pop(-1) module", "consume all fake ' 'expect status: %r' % (self.expect_status,)) if", "= '' crlfs = 0 while crlfs < 2: c", "will actually be based on the path - otherwise we", "you can fabricate one to meet your tests needs. \"\"\"", "copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class", "name def acquire(self): pass def release(self): pass def createLock(self): pass", "of the TestCase instance which can lead to some bled", "index=i) for i, node in enumerate(list(self._devs))] def get_more_nodes(self, part): for", "not isinstance(status, FakeStatus): status = FakeStatus(status) self._status = status self.reason", "# this is a public interface def get_lines_for_level(self, level): if", "isinstance(status, FakeStatus): status = FakeStatus(status) self._status = status self.reason =", "ring methods will actually be based on the path -", "required by applicable law or agreed to in writing, software", "cls def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES =", "of strings it will make reads take longer by the", "while crlfs < 2: c = fd.read(1) if not c:", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "the same \"reset\" behavior with custom FakeRing's they can pass", "class FabricatedRing(Ring): \"\"\" When a FakeRing just won't do -", "'port': port, 'replication_port': port, 'device': 'sd' + (chr(ord('a') + x)),", "body_iter = kwargs.get('body_iter', None) if body_iter: body_iter = iter(body_iter) def", "keys(self): return self.store.keys() def set(self, key, value, time=0): self.store[key] =", "having to think about it, here we're capturing the args", "2 if hasattr(self, '_replica2part2dev_id'): return self._devs = [{ 'region': 1,", "class NullLoggingHandler(logging.Handler): def emit(self, record): pass class UnmockTimeModule(object): \"\"\" Even", "repr(True) def __eq__(self, other): return other is True def __ne__(self,", "TestCase instance which can lead to some bled state. To", "else: headers_iter = iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list,", "2: c = fd.read(1) if not c: raise ValueError(\"didn't get", "and lc != '\\n': crlfs = 0 if lc ==", "class PatchPolicies(object): \"\"\" Why not mock.patch? In my case, when", "policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies", "return False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True,", "inode = _get_inode(fd) data = xattr_data.get(inode, {}) data[k] = v", "agreed to in writing, software # distributed under the License", "not None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing,", "class it seemed to patch setUp at the wrong time", "'port': self.port, 'replication_port': self.port, } for i in range(self.devices)] self._replica2part2dev_id", "pass def handleError(self, record): pass class DebugLogger(FakeLogger): \"\"\"A simple stdout", "distributed under the License is distributed on an \"AS IS\"", "inspect EMPTY_ETAG = md5().hexdigest() # try not to import this", "{} self.timestamp = timestamp self.connection_id = connection_id self.give_send = give_send", "{}).get(k) if not data: raise IOError(errno.ENODATA, \"Fake IOError\") return data", "of responses # as expect statuses just like a real", "test method. \"\"\" @functools.wraps(f) def wrapped(*args, **kwargs): tempdir = mkdtemp()", "fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn):", "priority LOG_NOTICE. The python logging lvl is set to 25,", "won't do - you can fabricate one to meet your", "amt=None): if self.give_send: self.give_send(self.connection_id, amt) am_slow, value = self.get_slow() if", "return getattr(time, name) # logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule()", "argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers", "fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if", "= rv + c if c == '\\r' and lc", "counts[metric] = 0 counts[metric] += 1 return counts def setFormatter(self,", "StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args = [{}] elif with_ec_default: default_policies", "logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule() class FakeLogger(logging.Logger, object): #", "self.store[key] @contextmanager def soft_lock(self, key, timeout=0, retries=5): yield True def", "part_power=4): self.devices = devices self.nodes = nodes self.port = port", "# delegate to FakeLogger's mocks update_stats = _send_to_logger('update_stats') increment =", "name) original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in dir(original_syslog_handler):", "from collections import defaultdict, Iterable import itertools from numbers import", "{} self.expect_headers = expect_headers or {} self.timestamp = timestamp self.connection_id", "= None # be nice to trixy bits with node_iter's", "[None] * len(self.policies) def _setup_rings(self): \"\"\" Our tests tend to", "AssertionError('left over status %r' % left_over_status) def make_timestamp_iter(): return iter(Timestamp(t)", "of ([expect_status, ...], response_status) :param expect_sleep: float, time to eventlet", "shutil import rmtree from swift.common.utils import Timestamp, NOTICE from test", "not to import this module from swift if not os.path.basename(sys.argv[0]).startswith('swift'):", "Ring, RingData from hashlib import md5 import logging.handlers from six.moves.http_client", "{'ip': '10.0.0.%s' % x, 'replication_ip': '10.0.0.%s' % x, 'port': self._base_port", "timing_since = _store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def", "**kwargs): return self def __call__(self, *args, **kwargs): return self def", "[]} clear = _clear # this is a public interface", "connect exception if isinstance(status, (Exception, eventlet.Timeout)): raise status if isinstance(status,", "eventlet.Timeout)): raise status if isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status", "'ip': '127.0.0.1', 'port': 6000} dev2 = {'id': 0, 'zone': 0,", "test import get_config from swift.common import swob, utils from swift.common.ring", "def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES", "these instead of a status int or status int tuple", "Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status() return self", "%(message)s\") def handle(self, record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name):", "respond with that status line immediately instead of 100 #", "EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False,", "def handle(self, record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def", "md5(self.body).hexdigest() + '\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({", "= f.name f.write(str(content)) try: yield file_name finally: os.unlink(file_name) xattr_data =", "value return True def incr(self, key, time=0): self.store[key] = self.store.setdefault(key,", "done - but it seems to cause infinite recursion when", "KeyError( \"Invalid log level '%s'; valid levels are %s\" %", "args = list(args) args.append(tempdir) try: return f(*args, **kwargs) finally: rmtree(tempdir)", "Creating a new class that inherits from decorated class is", "bled state. To help tests get better isolation without having", "our fake_http_connect, if you hand in one of these instead", "= _get_inode(fd) data = xattr_data.get(inode, {}).get(k) if not data: raise", "these fresh rings in setUp - or if they'd prefer", "\"Fake IOError\") return data import xattr xattr.setxattr = _setxattr xattr.getxattr", "= MockTrue() >>> thing True >>> thing == True #", "body self.headers = headers or {} self.expect_headers = expect_headers or", "raise eventlet.Timeout() self.status = self._status.get_response_status() return self def getexpect(self): expect_status", "FakeRing instances so we can ensure each test method gets", "clear = _clear # this is a public interface def", "'etag': etag, 'x-works': 'yes', }) if self.status // 100 ==", "SystemExit('ERROR: unable to find suitable PyECLib type' ' (none of", "'replication_port': port, 'device': 'sd' + (chr(ord('a') + x)), 'zone': x", "so we can ensure each test method gets a clean", "smarter than just duck-type the str/buffer api enough to get", "v xattr_data[inode] = data def _getxattr(fd, k): inode = _get_inode(fd)", "time import eventlet from eventlet.green import socket from tempfile import", "to meet your tests needs. \"\"\" def __init__(self, replicas=6, devices=8,", "Swift tests \"\"\" from __future__ import print_function import os import", "isinstance(status, (Exception, eventlet.Timeout)): raise status if isinstance(status, tuple): self.expect_status =", "if self.expect_status and self.explicit_expect_list: raise Exception('Test did not consume all", "time.time() def set_replicas(self, replicas): self.replicas = replicas self._devs = []", "return os.fstat(fd).st_ino def _setxattr(fd, k, v): inode = _get_inode(fd) data", "= (list(contents) + [''] * c)[:c] tempdir = mkdtemp() for", "# logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule() class FakeLogger(logging.Logger, object):", "'1' except StopIteration: pass am_slow, value = self.get_slow() if am_slow:", "list): try: self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep = None", "self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\"", "record): pass class DebugLogger(FakeLogger): \"\"\"A simple stdout logging version of", "than just duck-type the str/buffer api enough to get by.", "import print_function import os import copy import logging import errno", "other): self.slowdown() return other + self.body def fake_http_connect(*code_iter, **kwargs): class", "ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas': 14}, {}]", "= '.' + path new_path = os.path.join(tempdir, path) subdir =", "self.store[key] = self.store.setdefault(key, 0) + 1 return self.store[key] @contextmanager def", "None: return True, self._next_sleep else: return False, 0.01 if kwargs.get('slow')", "self.body[amt:] return rv def send(self, amt=None): if self.give_send: self.give_send(self.connection_id, amt)", "name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args", "UnmockTimeModule() class FakeLogger(logging.Logger, object): # a thread safe fake logger", "def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def __init__(self,", "if body_iter: body_iter = iter(body_iter) def connect(*args, **ckwargs): if kwargs.get('slow_connect',", "of the connection. \"\"\" def __init__(self, status, expect_sleep=None, response_sleep=None): \"\"\"", "policy definitions. \"\"\" for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if", "str/buffer api enough to get by. \"\"\" def __init__(self, body,", "def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def __init__(self, status, etag=None, body='',", "from swift.common.utils import Timestamp, NOTICE from test import get_config from", "return data import xattr xattr.setxattr = _setxattr xattr.getxattr = _getxattr", "fake_syslog_handler() class MockTrue(object): \"\"\" Instances of MockTrue evaluate like True", "amt) am_slow, value = self.get_slow() if am_slow: if self.received <", "the License is distributed on an \"AS IS\" BASIS, #", "f): @functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES", "except Exception: pass return True def readuntil2crlfs(fd): rv = ''", "True True >>> thing == False # True == False", "else: deletes.append((module, attr)) setattr(module, attr, value) try: yield True finally:", "fd.fileno() except AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd, k,", "not in counts: counts[metric] = 0 counts[metric] += 1 return", "kwargs.get('count', 12345) if not self.timestamp: # when timestamp is None,", "<filename>test/unit/__init__.py # Copyright (c) 2010-2012 OpenStack Foundation # # Licensed", "max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param part_power: make part calculation based", "before reading # from the body (mostly an error response)", "False False >>> thing != True # True != True", "attr) class FakeStatus(object): \"\"\" This will work with our fake_http_connect,", "above info. SysLogHandler is monkey patched to map this log", "= _getxattr @contextmanager def temptree(files, contents=''): # generate enough contents", "etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter", "30 with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f)", "= {} for metric in self.get_increments(): if metric not in", "class decorators done - but it seems to cause infinite", "(or a subclass) for the body inside of FakeConn if", "by monkey patching it's imported reference to the module with", "status int or status int tuple to the \"codes\" iter", "out of ring methods will actually be based on the", "the result and return 1. \"\"\" self._base_port = base_port self.max_more_nodes", "self.nodes), 'replication_ip': '10.0.0.%d' % (i % self.nodes), 'port': self.port, 'replication_port':", "logging import errno from six.moves import range import sys from", "of these instead of a status int or status int", "law or agreed to in writing, software # distributed under", "os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as f:", "else: return self._patch_method(thing) def _patch_class(self, cls): \"\"\" Creating a new", "the real ring code, but ignore the result and return", "generate enough contents to fill the files c = len(files)", "over status %r' % left_over_status) def make_timestamp_iter(): return iter(Timestamp(t) for", "2, 'id': x, }) @property def replica_count(self): return self.replicas def", "fake logger def __init__(self, *args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger'", "setup sleep attributes if not isinstance(expect_sleep, (list, tuple)): expect_sleep =", "modname in imports[1:]: module = getattr(module, modname) if hasattr(module, attr):", "self.timestamp = timestamp self.connection_id = connection_id self.give_send = give_send if", "try not to import this module from swift if not", "__enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies def __exit__(self, *args):", "# be nice to trixy bits with node_iter's eventlet.sleep() def", "RingData from hashlib import md5 import logging.handlers from six.moves.http_client import", "replica_count(self): return self.replicas def _get_part_nodes(self, part): return [dict(node, index=i) for", "self.explicit_expect_list: raise Exception('Test did not consume all fake ' 'expect", "fd = fd.fileno() except AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino def", "**kwargs): class FakeConn(object): def __init__(self, status, etag=None, body='', timestamp='1', headers=None,", "instance of MockTrue will return a MockTrue instance. >>> thing", "LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE, msg, *args, **kwargs) def _log(self,", "__future__ import print_function import os import copy import logging import", "port = self._base_port + x self._devs.append({ 'ip': ip, 'replication_ip': ip,", "kwargs.get('missing_container', [False] * len(code_iter)) if not isinstance(x, (tuple, list)): x", "in self.get_increments(): if metric not in counts: counts[metric] = 0", "may obtain a copy of the License at # #", "method, path, headers, qs, ssl): req = { 'ip': ip,", "if lc == '\\r' and c == '\\n': crlfs +=", "= next(headers_iter) expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter) if status", "'critical', NOTICE: 'notice', } def notice(self, msg, *args, **kwargs): \"\"\"", "1, 'weight': 1.0, 'id': i, 'device': 'sda%d' % i, 'ip':", "CRLFs; just got %r\" % rv) rv = rv +", "from test import get_config from swift.common import swob, utils from", "False True >>> thing.attribute True >>> thing.method() True >>> thing.attribute.method()", "mock(update): returns = [] deletes = [] for key, value", "other is not True @contextmanager def mock(update): returns = []", "self.expect_status = list(status[:-1]) self.status = status[-1] self.explicit_expect_list = True else:", "case of a patched TestCase class where the FakeRing objects", "yield tempdir finally: rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator to give", "storage_policy._POLICIES if not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES = self.policies self._setup_rings()", "may not use this file except in compliance with the", "mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies def", "'_replica2part2dev_id'): return self._devs = [{ 'region': 1, 'zone': 1, 'weight':", "self.slowdown() return other + self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object):", "def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp = setUp cls.tearDown", "record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self, *args,", "response.status = expect_status return response def getheaders(self): etag = self.etag", "two CRLFs; just got %r\" % rv) rv = rv", "headers=headers) response.status = expect_status return response def getheaders(self): etag =", "isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args", "= setUp cls.tearDown = tearDown return cls def _patch_method(self, f):", "'id': i, 'device': 'sda%d' % i, 'ip': '10.0.0.%d' % (i", "this file except in compliance with the License. # You", "the args required to *build* a new FakeRing instances so", "problem in the particular case of a patched TestCase class", "it, here we're capturing the args required to *build* a", "__init__(self, status, expect_sleep=None, response_sleep=None): \"\"\" :param status: the response status", "a swift backend service returns a status before reading #", "14}, {}] else: default_policies = [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1,", "[ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'),", "*args, **kwargs) self.formatter = logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def handle(self,", "is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args =", "storage_policy._POLICIES = self._orig_POLICIES return mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES", "if len(msgs) > 0) def _store_in(store_name): def stub_fn(self, *args, **kwargs):", "__len__(self): return len(self.body) def __radd__(self, other): self.slowdown() return other +", "\"tweak\" these fresh rings in setUp - or if they'd", "* len(self.policies) def _setup_rings(self): \"\"\" Our tests tend to use", "(self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return self.status def", "etag_iter = iter(kwargs.get('etags') or [None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list,", "* len(code_iter) container_ts_iter = iter(x) code_iter = iter(code_iter) conn_id_and_code_iter =", "if 'give_content_type' in kwargs: if len(args) >= 7 and 'Content-Type'", "imports time directly by monkey patching it's imported reference to", "# # Licensed under the Apache License, Version 2.0 (the", "set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try: return object.__getattribute__(self, name)", "* 2 ** self.part_power for i in range(self.replicas) ] dev_ids", "try: self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep = None #", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "\"\"\" :param part_power: make part calculation based on the path", "own fake_ring_args to patch_policies instead of setting the object_ring on", "increment = _send_to_logger('increment') decrement = _send_to_logger('decrement') timing = _send_to_logger('timing') timing_since", "exercise the real ring code, but ignore the result and", "finally: for module, attr, value in returns: setattr(module, attr, value)", "same \"reset\" behavior with custom FakeRing's they can pass in", "in imports[1:]: module = getattr(module, modname) if hasattr(module, attr): returns.append((module,", "( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record) def", "# never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE =", "'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes', }) if self.status //", "(i % self.nodes), 'port': self.port, 'replication_port': self.port, } for i", "self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs) def _clear(self): self.log_dict", "True finally: for module, attr, value in returns: setattr(module, attr,", "self._orig_POLICIES cls.setUp = setUp cls.tearDown = tearDown return cls def", "- you can restore unmolested behavior in a another module", "@contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False) as f: file_name =", "return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get a named adapted debug", "import md5 import logging.handlers from six.moves.http_client import HTTPException from swift.common", "'\\r' and lc != '\\n': crlfs = 0 if lc", "**kwargs) self.formatter = logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def handle(self, record):", "self.explicit_expect_list = False if not self.expect_status: # when a swift", "True != False True >>> thing.attribute True >>> thing.method() True", "yield file_name finally: os.unlink(file_name) xattr_data = {} def _get_inode(fd): if", "attr accessed on an instance of MockTrue will return a", "def mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES = self.policies", "= imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]:", "lvl for lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return", "[] for key, value in update.items(): imports = key.split('.') attr", "as f: file_name = f.name f.write(str(content)) try: yield file_name finally:", "kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status() return self def getexpect(self):", "OpenStack Foundation # # Licensed under the Apache License, Version", "return rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False) as f:", "return os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd, k, v): inode =", "**kwargs): requests = [] def capture_requests(ip, port, method, path, headers,", "instances so we can ensure each test method gets a", "test method gets a clean ring setup. The TestCase can", "= iter(kwargs.get('timestamps') or ['1'] * len(code_iter)) etag_iter = iter(kwargs.get('etags') or", "__exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3,", "function for syslog priority LOG_NOTICE. The python logging lvl is", "message %r %% %r' % ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line)", "default_policies = [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args", "try: storage_policy._POLICIES = self.policies self._setup_rings() return f(*args, **kwargs) finally: storage_policy._POLICIES", "'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes', }) if self.status", "_store_in(store_name): def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn #", "{}] else: default_policies = [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'),", "who imports time directly by monkey patching it's imported reference", "type): return self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self, cls): \"\"\"", "StatsD logging methods: update_stats = _store_in('update_stats') increment = _store_in('increment') decrement", "False # True == False False >>> thing != True", "self._devs = [] for x in range(self.replicas): ip = '10.0.0.%s'", "12345) if not self.timestamp: # when timestamp is None, HeaderKeyDict", "dev1_updates, dev2_updates = devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id", "give_send=kwargs.get('give_send')) connect.code_iter = code_iter return connect @contextmanager def mocked_http_conn(*args, **kwargs):", "mock out the StatsD logging methods: update_stats = _store_in('update_stats') increment", "not isinstance(x, (tuple, list)): x = [x] * len(code_iter) container_ts_iter", "qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args,", "as pickle from gzip import GzipFile import mock as mocklib", "\"%(server)s %(levelname)s: %(message)s\") def handle(self, record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter):", "return self.lines_dict[level] def all_log_lines(self): return dict((level, msgs) for level, msgs", "@functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES =", "storage_policy._POLICIES storage_policy._POLICIES = self.policies def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES", "otherwise we exercise the real ring code, but ignore the", "= dict(kwargs) if 'exc_info' in kwargs and \\ not isinstance(kwargs['exc_info'],", "stub_fn(self, *args, **kwargs): return getattr(self.logger, name)(*args, **kwargs) return stub_fn #", "decrement = _store_in('decrement') timing = _store_in('timing') timing_since = _store_in('timing_since') transfer_rate", "% x, 'replication_ip': '10.0.0.%s' % x, 'port': self._base_port + x,", "it should be easy to detect if you have one", "**kwargs): \"\"\" Convenience function for syslog priority LOG_NOTICE. The python", "etag: if isinstance(self.body, str): etag = '\"' + md5(self.body).hexdigest() +", "pass def _handle(self, record): try: line = record.getMessage() except TypeError:", "be easy to detect if you have one of these", "fake_ring_args=fake_ring_args) if legacy_only: default_policies = [ StoragePolicy(0, name='legacy', is_default=True), ]", "by the given amount. It should be a little bit", "devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1,", "object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get", "captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs)", "wanted to do something smarter than just duck-type the str/buffer", "= FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status return response def", "self.give_send: self.give_send(self.connection_id, amt) am_slow, value = self.get_slow() if am_slow: if", "*args, **kwargs) def _log(self, level, msg, *args, **kwargs): store_name =", "len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter", "eventlet.green import socket from tempfile import mkdtemp from shutil import", "NOTICE from test import get_config from swift.common import swob, utils", "\"\"\" Why not mock.patch? In my case, when used as", "get two CRLFs; just got %r\" % rv) rv =", "_send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix')", "* len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers']) else:", "wrapped class NullLoggingHandler(logging.Handler): def emit(self, record): pass class UnmockTimeModule(object): \"\"\"", "= [msg] if any(args): cargs.extend(args) captured = dict(kwargs) if 'exc_info'", "// 100 == 2: headers['x-account-container-count'] = \\ kwargs.get('count', 12345) if", "f.write(str(content)) try: yield file_name finally: os.unlink(file_name) xattr_data = {} def", "isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return self.status def get_expect_status(self): expect_sleep", "_reload(self, *args, **kwargs): self._rtime = time.time() * 2 if hasattr(self,", "self.nodes), 'port': self.port, 'replication_port': self.port, } for i in range(self.devices)]", "\"Invalid log level '%s'; valid levels are %s\" % (level,", "Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies = [", "for r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object): def", "key, time=0): self.store[key] = self.store.setdefault(key, 0) + 1 return self.store[key]", "= c return rv def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport)", "del self.store[key] except Exception: pass return True def readuntil2crlfs(fd): rv", "is the cap, no matter if # this is set", "kwargs['facility'] self.statsd_client = None self.thread_locals = None self.parent = None", "self.lines_dict: raise KeyError( \"Invalid log level '%s'; valid levels are", "not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level,", "while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def get_response_status(self):", "\"\"\" When a FakeRing just won't do - you can", "float, time to eventlet sleep during response \"\"\" # connect", "def getexpect(self): expect_status = self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status", "self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp'] =", "iter(x) code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body',", "give_conn_fn = kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id'", "self.max_more_nodes = max_more_nodes self._part_shift = 32 - part_power # 9", "= policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or", "{})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers'])", "'w') as f: f.write(str(content)) try: yield tempdir finally: rmtree(tempdir) def", "devs = [dev1, dev2] part_shift = 30 with closing(GzipFile(path, 'wb'))", "int): try: fd = fd.fileno() except AttributeError: return os.stat(fd).st_ino return", "rv = rv + c if c == '\\r' and", "print('WARNING: unable to format log message %r %% %r' %", "if not thing_or_policies: return decorator else: # it's a thing,", "for metric in self.get_increments(): if metric not in counts: counts[metric]", "did not consume all fake ' 'expect status: %r' %", "NamedTemporaryFile import time import eventlet from eventlet.green import socket from", "past the initial 3) is the cap, no matter if", "6000} dev2 = {'id': 0, 'zone': 0, 'device': 'sdb1', 'ip':", "self.received < 4: self.received += 1 eventlet.sleep(value) def getheader(self, name,", "if not isinstance(x, (tuple, list)): x = [x] * len(code_iter)", "definitions. \"\"\" for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg", "return self._patch_method(thing) def _patch_class(self, cls): \"\"\" Creating a new class", "slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s], self.slowness)", "returns a status before reading # from the body (mostly", "self._next_sleep is not None: return True, self._next_sleep else: return False,", "etag=None, body='', timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None): if not isinstance(status,", "if self.response_sleep is not None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list:", "'replication_ip': '10.0.0.%d' % (i % self.nodes), 'port': self.port, 'replication_port': self.port,", "part_power # 9 total nodes (6 more past the initial", "time to eventlet sleep during response \"\"\" # connect exception", "port self.replicas = 6 self.part_power = part_power self._part_shift = 32", "self._clear() def set_name(self, name): # don't touch _handlers self._name =", "'give_content_type' in kwargs: if len(args) >= 7 and 'Content-Type' in", "self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes', })", "code_iter return connect @contextmanager def mocked_http_conn(*args, **kwargs): requests = []", "kwargs and \\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs),", "[x] * len(code_iter) container_ts_iter = iter(x) code_iter = iter(code_iter) conn_id_and_code_iter", "meet your tests needs. \"\"\" def __init__(self, replicas=6, devices=8, nodes=4,", "get by. \"\"\" def __init__(self, body, slowness): self.body = body", "% (i % self.nodes), 'port': self.port, 'replication_port': self.port, } for", "class that inherits from decorated class is the more common", "self.lines_dict[level] def all_log_lines(self): return dict((level, msgs) for level, msgs in", "crlfs += 1 lc = c return rv def connect_tcp(hostport):", "(i.e. in setup the global wasn't patched yet) \"\"\" def", "even if the client sent the Expect 100 header. #", "= code_iter return connect @contextmanager def mocked_http_conn(*args, **kwargs): requests =", "def _get_part_nodes(self, part): return [dict(node, index=i) for i, node in", "kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args, **kwargs) fake_conn.requests = requests with", "self.store.get(key) def keys(self): return self.store.keys() def set(self, key, value, time=0):", "return a MockTrue instance. >>> thing = MockTrue() >>> thing", "status[-1] self.explicit_expect_list = True else: self.expect_status, self.status = ([], status)", "% (i % self.nodes), 'replication_ip': '10.0.0.%d' % (i % self.nodes),", "7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status", "logging.time = UnmockTimeModule() class FakeLogger(logging.Logger, object): # a thread safe", "< len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def get_response_status(self): if self.response_sleep", "__getattribute__(self, *args, **kwargs): return self def __call__(self, *args, **kwargs): return", "not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)):", "lvl is set to 25, just above info. SysLogHandler is", "FakeRing's they can pass in their own fake_ring_args to patch_policies", "swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified':", "name) except AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get a", "status before reading # from the body (mostly an error", "= kwargs.get('body_iter', None) if body_iter: body_iter = iter(body_iter) def connect(*args,", "self._orig_POLICIES = storage_policy._POLICIES if not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES =", "'facility' in kwargs: self.facility = kwargs['facility'] self.statsd_client = None self.thread_locals", "list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over status %r' % left_over_status)", "more past the initial 3) is the cap, no matter", "for x in range(self.replicas, (self.replicas + self.max_more_nodes)): yield {'ip': '10.0.0.%s'", "= etag self.body = body self.headers = headers or {}", "2, 'id': x} def write_fake_ring(path, *devs): \"\"\" Pretty much just", "swift.common.ring import Ring, RingData from hashlib import md5 import logging.handlers", "if self.give_send: self.give_send(self.connection_id, amt) am_slow, value = self.get_slow() if am_slow:", "on the path If you set a part_power when you", "when a swift backend service returns a status before reading", "self._rtime = time.time() * 2 if hasattr(self, '_replica2part2dev_id'): return self._devs", "eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s], self.slowness) def __len__(self): return", "= expect_status return response def getheaders(self): etag = self.etag if", "error response) eventlet.wsgi will # respond with that status line", "file_name finally: os.unlink(file_name) xattr_data = {} def _get_inode(fd): if not", "module with an instance of this class \"\"\" _orig_time =", "= {} def _get_inode(fd): if not isinstance(fd, int): try: fd", "0) def _store_in(store_name): def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return", "connection. \"\"\" def __init__(self, status, expect_sleep=None, response_sleep=None): \"\"\" :param status:", "service returns a status before reading # from the body", "connect @contextmanager def mocked_http_conn(*args, **kwargs): requests = [] def capture_requests(ip,", "+ [''] * c)[:c] tempdir = mkdtemp() for path, content", "response \"\"\" # connect exception if isinstance(status, (Exception, eventlet.Timeout)): raise", "raise HTTPException() if body_iter is None: body = static_body or", "__eq__(self, other): return other is True def __ne__(self, other): return", "mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES = self.policies self._setup_rings()", "setUp - or if they'd prefer to get the same", "return SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body) def __radd__(self, other):", "expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter))", "self.replicas def _get_part_nodes(self, part): return [dict(node, index=i) for i, node", "k, v): inode = _get_inode(fd) data = xattr_data.get(inode, {}) data[k]", "logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical',", "_send_to_logger('increment') decrement = _send_to_logger('decrement') timing = _send_to_logger('timing') timing_since = _send_to_logger('timing_since')", "logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object):", "requests = [] def capture_requests(ip, port, method, path, headers, qs,", "'device': 'sd' + (chr(ord('a') + x)), 'zone': x % 3,", "= logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def handle(self, record): self._handle(record) print(self.formatter.format(record))", "MockTrue() >>> thing True >>> thing == True # True", "for i, node in enumerate(list(self._devs))] def get_more_nodes(self, part): for x", "% 2, 'id': x} def write_fake_ring(path, *devs): \"\"\" Pretty much", "update.items(): imports = key.split('.') attr = imports.pop(-1) module = __import__(imports[0],", "raise status if isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status =", "def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)):", "based on the path If you set a part_power when", "setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler =", "in writing, software # distributed under the License is distributed", "instead of setting the object_ring on the policy definitions. \"\"\"", "= {} def get(self, key): return self.store.get(key) def keys(self): return", "self.port, } for i in range(self.devices)] self._replica2part2dev_id = [ [None]", "self._replica2part2dev_id = [ [None] * 2 ** self.part_power for i", "responses # as expect statuses just like a real backend", "take longer by the given amount. It should be a", "msgs in self.lines_dict.items() if len(msgs) > 0) def _store_in(store_name): def", "def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter = logging.Formatter(", "can lead to some bled state. To help tests get", "_send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try: return object.__getattribute__(self,", "mocks update_stats = _send_to_logger('update_stats') increment = _send_to_logger('increment') decrement = _send_to_logger('decrement')", "= enumerate(code_iter) static_body = kwargs.get('body', None) body_iter = kwargs.get('body_iter', None)", "int or status int tuple to the \"codes\" iter you", "# limitations under the License. \"\"\" Swift tests \"\"\" from", "to trixy bits with node_iter's eventlet.sleep() def getresponse(self): exc =", "return self def getexpect(self): expect_status = self._status.get_expect_status() headers = dict(self.expect_headers)", "return headers.items() def get_slow(self): if 'slow' in kwargs and isinstance(kwargs['slow'],", "0 counts[metric] += 1 return counts def setFormatter(self, obj): self.formatter", "and isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep", "decorated class. \"\"\" orig_setUp = cls.setUp orig_tearDown = cls.tearDown def", "'info': [], 'warning': [], 'debug': [], 'notice': []} clear =", "to FakeLogger's mocks update_stats = _send_to_logger('update_stats') increment = _send_to_logger('increment') decrement", "contextmanager, closing from collections import defaultdict, Iterable import itertools from", "kwargs: self.facility = kwargs['facility'] self.statsd_client = None self.thread_locals = None", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "OF ANY KIND, either express or # implied. # See", "much just a two node, two replica, 2 part power", "when you setup your FakeRing the parts you get out", "another module who imports time directly by monkey patching it's", "License, Version 2.0 (the \"License\"); # you may not use", "AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'): \"\"\"get a named adapted", "== True True >>> thing == False # True ==", "'replication_port': self.port, } for i in range(self.devices)] self._replica2part2dev_id = [", "if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter =", "return other + self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def", "contents=''): # generate enough contents to fill the files c", "our fake_http_connect, if you hand in these instead of strings", "with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class", "self.connection_id = connection_id self.give_send = give_send if 'slow' in kwargs", "{'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': 6000}", "True False >>> thing != False # True != False", "default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator", "# True != True False >>> thing != False #", "in one of these instead of a status int or", "def get_slow(self): if 'slow' in kwargs and isinstance(kwargs['slow'], list): if", "time.time - you can restore unmolested behavior in a another", "fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator else: # it's a", "time=0): self.store[key] = self.store.setdefault(key, 0) + 1 return self.store[key] @contextmanager", "def delete(self, key): try: del self.store[key] except Exception: pass return", "write_fake_ring(path, *devs): \"\"\" Pretty much just a two node, two", "method called on an instance of MockTrue will return a", "the body (mostly an error response) eventlet.wsgi will # respond", "and isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def", ">>> thing != False # True != False True >>>", ":param status: the response status int, or a tuple of", "seems to cause infinite recursion when super is called from", "six.moves.http_client import HTTPException from swift.common import storage_policy from swift.common.storage_policy import", "the License for the specific language governing permissions and #", "thing, we return the wrapped thing instead of the decorator", "return [dict(node, index=i) for i, node in enumerate(list(self._devs))] def get_more_nodes(self,", "0) + 1 return self.store[key] @contextmanager def soft_lock(self, key, timeout=0,", "contents to fill the files c = len(files) contents =", "len(args) >= 7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('')", "= '4' headers.update(self.headers) return headers.items() def get_slow(self): if 'slow' in", "Even if a test mocks time.time - you can restore", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= self.policies self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self)", "will return a MockTrue instance. Any method called on an", "thing True >>> thing == True # True == True", "self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object):", "DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self, *args, **kwargs): return getattr(self.logger, name)(*args,", "decorator on the class it seemed to patch setUp at", "ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas': 14},", "' 'expect status: %r' % (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)):", "of a patched TestCase class where the FakeRing objects are", "fd.read(1) if not c: raise ValueError(\"didn't get two CRLFs; just", "simple stdout logging version of FakeLogger\"\"\" def __init__(self, *args, **kwargs):", "thing instead of the decorator return decorator(thing_or_policies) class PatchPolicies(object): \"\"\"", "def release(self): pass def createLock(self): pass def emit(self, record): pass", "def keys(self): return self.store.keys() def set(self, key, value, time=0): self.store[key]", "= 0 counts[metric] += 1 return counts def setFormatter(self, obj):", "from the body (mostly an error response) eventlet.wsgi will #", "def temptree(files, contents=''): # generate enough contents to fill the", "return mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies", "to format log message %r %% %r' % ( record.msg,", "'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag, 'x-works': 'yes', }) if", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "range import sys from contextlib import contextmanager, closing from collections", "= time.time() def set_replicas(self, replicas): self.replicas = replicas self._devs =", "c: raise ValueError(\"didn't get two CRLFs; just got %r\" %", "if any(args): cargs.extend(args) captured = dict(kwargs) if 'exc_info' in kwargs", "self.store.keys() def set(self, key, value, time=0): self.store[key] = value return", "of setting the object_ring on the policy definitions. \"\"\" for", "setUp cls.tearDown = tearDown return cls def _patch_method(self, f): @functools.wraps(f)", "_getxattr @contextmanager def temptree(files, contents=''): # generate enough contents to", "True != True False >>> thing != False # True", "*args, **kwargs): \"\"\" Convenience function for syslog priority LOG_NOTICE. The", "_store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self): return", "like # our backend services and return certain types of", "(Exception, eventlet.Timeout)): raise expect_status return expect_status class SlowBody(object): \"\"\" This", "swift.common import swob, utils from swift.common.ring import Ring, RingData from", "f(*args, **kwargs) finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def emit(self,", "legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies,", "= self.body[amt:] return rv def send(self, amt=None): if self.give_send: self.give_send(self.connection_id,", "key): return self.store.get(key) def keys(self): return self.store.keys() def set(self, key,", "def getheaders(self): etag = self.etag if not etag: if isinstance(self.body,", "def getresponse(self): exc = kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception,", "'_policies_patched', False): storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self)", "def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param part_power: make", "rv) rv = rv + c if c == '\\r'", "== 'time': return UnmockTimeModule._orig_time return getattr(time, name) # logging.LogRecord.__init__ calls", "None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing, type):", "= v xattr_data[inode] = data def _getxattr(fd, k): inode =", "= None self.parent = None store_in = { logging.ERROR: 'error',", "{})] * len(code_iter)) x = kwargs.get('missing_container', [False] * len(code_iter)) if", "# distributed under the License is distributed on an \"AS", "raise expect_status return expect_status class SlowBody(object): \"\"\" This will work", "MockTrue instance. >>> thing = MockTrue() >>> thing True >>>", "# Unless required by applicable law or agreed to in", "def mock(update): returns = [] deletes = [] for key,", "temptree(files, contents=''): # generate enough contents to fill the files", "is set to 25, just above info. SysLogHandler is monkey", "of a status int or status int tuple to the", "is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter)", "wrapper outside of the TestCase instance which can lead to", "self.give_send = give_send if 'slow' in kwargs and isinstance(kwargs['slow'], list):", "R replicas self.set_replicas(replicas) self._reload() def _reload(self): self._rtime = time.time() def", "if len(args) >= 7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else:", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass timestamps_iter = iter(kwargs.get('timestamps') or ['1']", "getattr(self.logger, name)(*args, **kwargs) return stub_fn # delegate to FakeLogger's mocks", "get_response_status(self): if self.response_sleep is not None: eventlet.sleep(self.response_sleep) if self.expect_status and", "used as a decorator on the class it seemed to", "len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def get_response_status(self): if self.response_sleep is", "methods in the decorated class. \"\"\" orig_setUp = cls.setUp orig_tearDown", "code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body', None)", "in counts: counts[metric] = 0 counts[metric] += 1 return counts", "that inherits from decorated class is the more common way", "**kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn # mock out the StatsD", "= iter(x) code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body =", "def __repr__(*args, **kwargs): return repr(True) def __eq__(self, other): return other", "def replica_count(self): return self.replicas def _get_part_nodes(self, part): return [dict(node, index=i)", "make reads take longer by the given amount. It should", "the Apache License, Version 2.0 (the \"License\"); # you may", "return dict((level, msgs) for level, msgs in self.lines_dict.items() if len(msgs)", "part power ring... \"\"\" dev1 = {'id': 0, 'zone': 0,", "level '%s'; valid levels are %s\" % (level, ', '.join(\"'%s'\"", "finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def emit(self, record): pass", "if am_slow: if self.sent < 4: self.sent += 1 eventlet.sleep(value)", "self def __call__(self, *args, **kwargs): return self def __repr__(*args, **kwargs):", "raise SystemExit('ERROR: unable to find suitable PyECLib type' ' (none", "Why not mock.patch? In my case, when used as a", "_orig_time = time.time def __getattribute__(self, name): if name == 'time':", "= '10.0.0.%s' % x port = self._base_port + x self._devs.append({", "(507, 412, 409): self.expect_status = [status] else: self.expect_status = [100,", "import os import copy import logging import errno from six.moves", "from numbers import Number from tempfile import NamedTemporaryFile import time", "eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status", "if left_over_status: raise AssertionError('left over status %r' % left_over_status) def", "self._status = status self.reason = 'Fake' self.host = '1.2.3.4' self.port", "level): if level not in self.lines_dict: raise KeyError( \"Invalid log", "def emit(self, record): pass def _handle(self, record): try: line =", "= [{}] elif with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec', is_default=True,", "Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the", "is not None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing): if", "port=6000, part_power=4): self.devices = devices self.nodes = nodes self.port =", "which can lead to some bled state. To help tests", "a single test a tempdir as argument to test method.", "if not self.timestamp: # when timestamp is None, HeaderKeyDict raises", "self._status.get_response_status() return self def getexpect(self): expect_status = self._status.get_expect_status() headers =", "ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas':", "isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self,", "__getattribute__(self, name): if name == 'time': return UnmockTimeModule._orig_time return getattr(time,", "9 total nodes (6 more past the initial 3) is", "we're capturing the args required to *build* a new FakeRing", "_store_in('timing') timing_since = _store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix')", "expect, can be a iter of floats :param response_sleep: float,", "100 header. # BufferedHttp and the proxy both see these", "try: fd = fd.fileno() except AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino", "'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6000} dev1_updates, dev2_updates", "and the proxy both see these error statuses # when", "reading # from the body (mostly an error response) eventlet.wsgi", "one to meet your tests needs. \"\"\" def __init__(self, replicas=6,", "instance of MockTrue will return a MockTrue instance. Any method", "in the decorated class. \"\"\" orig_setUp = cls.setUp orig_tearDown =", "= fake_http_connect(*args, **kwargs) fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield", "self.statsd_client = None self.thread_locals = None self.parent = None store_in", "they'd prefer to get the same \"reset\" behavior with custom", "one of these (or a subclass) for the body inside", "= UnmockTimeModule() class FakeLogger(logging.Logger, object): # a thread safe fake", "None # be nice to trixy bits with node_iter's eventlet.sleep()", "'method': method, 'path': path, 'headers': headers, 'qs': qs, 'ssl': ssl,", "ANY KIND, either express or # implied. # See the", "isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0) except IndexError: self._next_sleep =", "crlfs = 0 if lc == '\\r' and c ==", "eventlet.sleep(value) def getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self):", "(none of %r found in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES,", "f: file_name = f.name f.write(str(content)) try: yield file_name finally: os.unlink(file_name)", "can restore unmolested behavior in a another module who imports", "p in range(2 ** self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p]", "if c == '\\r' and lc != '\\n': crlfs =", "None) if body_iter: body_iter = iter(body_iter) def connect(*args, **ckwargs): if", "map this log lvl to the LOG_NOTICE syslog priority. \"\"\"", "= iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter", "in kwargs and isinstance(kwargs['slow'], list): if self._next_sleep is not None:", "'region': 1, 'zone': 1, 'weight': 1.0, 'id': i, 'device': 'sda%d'", "utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for", "# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under", "safe fake logger def __init__(self, *args, **kwargs): self._clear() self.name =", "\"\"\" Instances of MockTrue evaluate like True Any attr accessed", "100] # setup sleep attributes if not isinstance(expect_sleep, (list, tuple)):", "from contextlib import contextmanager, closing from collections import defaultdict, Iterable", "= self._status.get_response_status() return self def getexpect(self): expect_status = self._status.get_expect_status() headers", "response_status) :param expect_sleep: float, time to eventlet sleep during expect,", "storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args =", "xattr_data[inode] = data def _getxattr(fd, k): inode = _get_inode(fd) data", "i in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for p in", "just won't do - you can fabricate one to meet", "logging.CRITICAL: 'critical', NOTICE: 'notice', } def notice(self, msg, *args, **kwargs):", "will make reads take longer by the given amount. It", "like a real backend server would do. if self.status in", "= _send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try: return object.__getattribute__(self, name) except", "True >>> thing == True # True == True True", "cap, no matter if # this is set higher, or", "* len(code_iter)) x = kwargs.get('missing_container', [False] * len(code_iter)) if not", "easier to extend than the current slow kwarg - which", "to the LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE, msg, *args, **kwargs)", "%r' % (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return", "under the License is distributed on an \"AS IS\" BASIS,", "'give_connect' in kwargs: give_conn_fn = kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if", "thing = MockTrue() >>> thing True >>> thing == True", "duck-type the str/buffer api enough to get by. \"\"\" def", "import time import eventlet from eventlet.green import socket from tempfile", "= 0 self.received = 0 self.etag = etag self.body =", "record.getMessage() except TypeError: print('WARNING: unable to format log message %r", "headers['x-container-timestamp'] = '1' except StopIteration: pass am_slow, value = self.get_slow()", "(Exception, eventlet.Timeout)): raise status if isinstance(status, tuple): self.expect_status = list(status[:-1])", "decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why not mock.patch? In my case,", "here we're capturing the args required to *build* a new", "to do something smarter than just duck-type the str/buffer api", "is None: body = static_body or '' else: body =", "= [] def capture_requests(ip, port, method, path, headers, qs, ssl):", "def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError: return", "= logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in dir(original_syslog_handler): if attr.startswith('LOG'):", "def get_increments(self): return [call[0][0] for call in self.log_dict['increment']] def get_increment_counts(self):", "extend than the current slow kwarg - which inserts whitespace", "__call__(self, *args, **kwargs): return self def __repr__(*args, **kwargs): return repr(True)", "'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn = fake_http_connect(*args, **kwargs)", "def _setxattr(fd, k, v): inode = _get_inode(fd) data = xattr_data.get(inode,", "name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass timestamps_iter =", "infinite recursion when super is called from inside methods in", "data[k] = v xattr_data[inode] = data def _getxattr(fd, k): inode", "they can pass in their own fake_ring_args to patch_policies instead", "self._handle(record) def flush(self): pass def handleError(self, record): pass class DebugLogger(FakeLogger):", "> 0) def _store_in(store_name): def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs))", "R^2 for R replicas self.set_replicas(replicas) self._reload() def _reload(self): self._rtime =", "'sda1', 'ip': '127.0.0.1', 'port': 6000} dev2 = {'id': 0, 'zone':", "iter([kwargs.get('headers', {})] * len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter =", "'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE:", "= expect_headers or {} self.timestamp = timestamp self.connection_id = connection_id", "os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as f: f.write(str(content)) try: yield", "IOError\") return data import xattr xattr.setxattr = _setxattr xattr.getxattr =", "dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\", "= self.body[:amt] self.body = self.body[amt:] return rv def send(self, amt=None):", "not c: raise ValueError(\"didn't get two CRLFs; just got %r\"", "in kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep = kwargs['slow'].pop(0) except", "\"\"\" self._base_port = base_port self.max_more_nodes = max_more_nodes self._part_shift = 32", "eventlet.Timeout)): raise self.status return self.status def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0)", "args.append(tempdir) try: return f(*args, **kwargs) finally: rmtree(tempdir) return wrapped class", "which can be a problem in the particular case of", "longer by the given amount. It should be a little", "'zone': 1, 'weight': 1.0, 'id': i, 'device': 'sda%d' % i,", "time to eventlet sleep during expect, can be a iter", "api enough to get by. \"\"\" def __init__(self, body, slowness):", "EMPTY_ETAG = md5().hexdigest() # try not to import this module", "FakeRing the parts you get out of ring methods will", "connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return rv @contextmanager def tmpfile(content):", "and response stages of the connection. \"\"\" def __init__(self, status,", "both see these error statuses # when they call getexpect,", "for level, msgs in self.lines_dict.items() if len(msgs) > 0) def", "return rv def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return rv", "+ x self._devs.append({ 'ip': ip, 'replication_ip': ip, 'port': port, 'replication_port':", "self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies def __exit__(self, *args): storage_policy._POLICIES", "True # True != True False >>> thing != False", "'replication_port': self._base_port + x, 'device': 'sda', 'zone': x % 3,", "copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if", "be nice to trixy bits with node_iter's eventlet.sleep() def getresponse(self):", "where the FakeRing objects are scoped in the call to", "in setup the global wasn't patched yet) \"\"\" def __init__(self,", "logging.NOTSET if 'facility' in kwargs: self.facility = kwargs['facility'] self.statsd_client =", "= dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp response", "with_tempdir(f): \"\"\" Decorator to give a single test a tempdir", "expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return", "headers = dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp", "single test a tempdir as argument to test method. \"\"\"", "!= False True >>> thing.attribute True >>> thing.method() True >>>", "data = xattr_data.get(inode, {}) data[k] = v xattr_data[inode] = data", "status self.reason = 'Fake' self.host = '1.2.3.4' self.port = '1234'", "print_function import os import copy import logging import errno from", "HTTPException() if body_iter is None: body = static_body or ''", "is set higher, or R^2 for R replicas self.set_replicas(replicas) self._reload()", "the path If you set a part_power when you setup", "= status[-1] self.explicit_expect_list = True else: self.expect_status, self.status = ([],", "capture_requests(ip, port, method, path, headers, qs, ssl): req = {", "IndexError: self._next_sleep = None # be nice to trixy bits", "self.etag = etag self.body = body self.headers = headers or", "0: raise HTTPException() if body_iter is None: body = static_body", "_send_to_logger('set_statsd_prefix') def __getattribute__(self, name): try: return object.__getattribute__(self, name) except AttributeError:", "and c == '\\n': crlfs += 1 lc = c", "the License. # You may obtain a copy of the", "range(self.replicas, (self.replicas + self.max_more_nodes)): yield {'ip': '10.0.0.%s' % x, 'replication_ip':", "# See the License for the specific language governing permissions", "scoped in the call to the patch_policies wrapper outside of", "the object_ring on the policy definitions. \"\"\" for policy, fake_ring_arg", "from swift.common.ring import Ring, RingData from hashlib import md5 import", "def get_increment_counts(self): counts = {} for metric in self.get_increments(): if", "total nodes (6 more past the initial 3) is the", "{}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0, 1], [1,", "False: headers['x-container-timestamp'] = '1' except StopIteration: pass am_slow, value =", "a test mocks time.time - you can restore unmolested behavior", ">= 7 and 'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i,", "replicas self.set_replicas(replicas) self._reload() def _reload(self): self._rtime = time.time() def set_replicas(self,", "see these error statuses # when they call getexpect, so", "= nodes self.port = port self.replicas = 6 self.part_power =", "None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise Exception('Test did not", "412, 409): self.expect_status = [status] else: self.expect_status = [100, 100]", "will work with our fake_http_connect, if you hand in these", "eclib_name in VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable to find", "get_slow(self): if 'slow' in kwargs and isinstance(kwargs['slow'], list): if self._next_sleep", "emit(self, record): pass def _handle(self, record): try: line = record.getMessage()", "am_slow: if self.sent < 4: self.sent += 1 eventlet.sleep(value) return", "method. \"\"\" @functools.wraps(f) def wrapped(*args, **kwargs): tempdir = mkdtemp() args", "import NamedTemporaryFile import time import eventlet from eventlet.green import socket", "like their own personal playground - which can be a", "_send_to_logger('decrement') timing = _send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate')", "and isinstance(kwargs['slow'], list): if self._next_sleep is not None: return True,", "are %s\" % (level, ', '.join(\"'%s'\" % lvl for lvl", "'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES:", "'device': 'sda1', 'ip': '127.0.0.1', 'port': 6000} dev2 = {'id': 0,", "self.response_sleep = response_sleep def get_response_status(self): if self.response_sleep is not None:", "c if c == '\\r' and lc != '\\n': crlfs", "def debug_logger(name='test'): \"\"\"get a named adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(),", "= FakeStatus(status) self._status = status self.reason = 'Fake' self.host =", "if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in kwargs: if len(args)", "self._orig_POLICIES return mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES =", "@functools.wraps(f) def wrapped(*args, **kwargs): tempdir = mkdtemp() args = list(args)", "msg, *args, **kwargs): \"\"\" Convenience function for syslog priority LOG_NOTICE.", "other): return other is True def __ne__(self, other): return other", "return len(self.body) def __radd__(self, other): self.slowdown() return other + self.body", "class SlowBody(object): \"\"\" This will work with our fake_http_connect, if", "__call__(self, thing): if isinstance(thing, type): return self._patch_class(thing) else: return self._patch_method(thing)", "= time.time def __getattribute__(self, name): if name == 'time': return", "% 3, 'region': x % 2, 'id': x} def write_fake_ring(path,", "name): # don't touch _handlers self._name = name def acquire(self):", "the class it seemed to patch setUp at the wrong", "am_slow: if self.received < 4: self.received += 1 eventlet.sleep(value) def", "attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value(", "= [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE: if", "# Continue, even if the client sent the Expect 100", "a public interface def get_lines_for_level(self, level): if level not in", "stub_fn # mock out the StatsD logging methods: update_stats =", "1 return counts def setFormatter(self, obj): self.formatter = obj def", "1], [1, 0, 1, 0]] devs = [dev1, dev2] part_shift", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES", "* c)[:c] tempdir = mkdtemp() for path, content in zip(files,", "patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return", "def get_more_nodes(self, part): for x in range(self.replicas, (self.replicas + self.max_more_nodes)):", "def __eq__(self, other): return other is True def __ne__(self, other):", "not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched =", "writing, software # distributed under the License is distributed on", "return cls def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES", "'x-works': 'yes', }) if self.status // 100 == 2: headers['x-account-container-count']", "exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status()", "method, 'path': path, 'headers': headers, 'qs': qs, 'ssl': ssl, }", "dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0, 1], [1, 0,", "the body inside of FakeConn if we wanted to do", "\"codes\" iter you can add some eventlet sleep to the", "storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0,", "= [ [None] * 2 ** self.part_power for i in", "\"\"\" def __getattribute__(self, *args, **kwargs): return self def __call__(self, *args,", "import mkdtemp from shutil import rmtree from swift.common.utils import Timestamp,", "**ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in kwargs: if", "from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools import six.moves.cPickle", "\"\"\" # connect exception if isinstance(status, (Exception, eventlet.Timeout)): raise status", "record): self._handle(record) def flush(self): pass def handleError(self, record): pass class", "raise Exception('Test did not consume all fake ' 'expect status:", "= connection_id self.give_send = give_send if 'slow' in kwargs and", "just a two node, two replica, 2 part power ring...", "# True == False False >>> thing != True #", "self.status = status[-1] self.explicit_expect_list = True else: self.expect_status, self.status =", "self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def __init__(self, status, etag=None,", "from swift.common import storage_policy from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES)", "= {'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port':", "policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg is not None:", "'notice', } def notice(self, msg, *args, **kwargs): \"\"\" Convenience function", "to patch_policies instead of setting the object_ring on the policy", "connection_id self.give_send = give_send if 'slow' in kwargs and isinstance(kwargs['slow'],", "True, self._next_sleep else: return False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'],", "'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility' in kwargs: self.facility =", "else: self.expect_status, self.status = ([], status) self.explicit_expect_list = False if", "personal playground - which can be a problem in the", "self.part_power for i in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for", "i give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers = next(headers_iter) expect_headers", "def incr(self, key, time=0): self.store[key] = self.store.setdefault(key, 0) + 1", "headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter return connect @contextmanager", "x = [x] * len(code_iter) container_ts_iter = iter(x) code_iter =", "isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list =", "{ logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL:", "data import xattr xattr.setxattr = _setxattr xattr.getxattr = _getxattr @contextmanager", "actually be based on the path - otherwise we exercise", "test mocks time.time - you can restore unmolested behavior in", "instance of this class \"\"\" _orig_time = time.time def __getattribute__(self,", "if we wanted to do something smarter than just duck-type", "= iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body', None) body_iter", "KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter) is False: headers['x-container-timestamp'] =", "this class \"\"\" _orig_time = time.time def __getattribute__(self, name): if", "to 25, just above info. SysLogHandler is monkey patched to", "= [100, 100] # setup sleep attributes if not isinstance(expect_sleep,", "limitations under the License. \"\"\" Swift tests \"\"\" from __future__", "PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return decorator else: # it's", "nice to trixy bits with node_iter's eventlet.sleep() def getresponse(self): exc", "'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210', 'etag': etag,", "try: yield True finally: for module, attr, value in returns:", "False, 0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True, kwargs['slow']", "set(self, key, value, time=0): self.store[key] = value return True def", "return other is not True @contextmanager def mock(update): returns =", "a patched TestCase class where the FakeRing objects are scoped", "fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def __init__(self, status, etag=None, body='', timestamp='1',", "\"\"\" from __future__ import print_function import os import copy import", "= kwargs['facility'] self.statsd_client = None self.thread_locals = None self.parent =", "HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter) is False:", "closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class FabricatedRing(Ring):", "content in zip(files, contents): if os.path.isabs(path): path = '.' +", "the TestCase instance which can lead to some bled state.", "delegate to FakeLogger's mocks update_stats = _send_to_logger('update_stats') increment = _send_to_logger('increment')", "without having to think about it, here we're capturing the", "= _store_in('timing') timing_since = _store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix =", "[1, 0, 1, 0]] devs = [dev1, dev2] part_shift =", "wrapped(*args, **kwargs): tempdir = mkdtemp() args = list(args) args.append(tempdir) try:", "if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return expect_status class SlowBody(object):", "deletes = [] for key, value in update.items(): imports =", "__radd__(self, other): self.slowdown() return other + self.body def fake_http_connect(*code_iter, **kwargs):", "= logging.NOTSET if 'facility' in kwargs: self.facility = kwargs['facility'] self.statsd_client", "+ c if c == '\\r' and lc != '\\n':", "record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record) def flush(self): pass", "self.expect_status: # when a swift backend service returns a status", "to *build* a new FakeRing instances so we can ensure", "class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param", "self.body[:amt] self.body = self.body[amt:] return rv def send(self, amt=None): if", "list): if self._next_sleep is not None: return True, self._next_sleep else:", "give_send=None): if not isinstance(status, FakeStatus): status = FakeStatus(status) self._status =", "socket.socket() rv.connect(hostport) return rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False)", "be a little bit easier to extend than the current", "instance. Any method called on an instance of MockTrue will", "part_power: make part calculation based on the path If you", "ignore the result and return 1. \"\"\" self._base_port = base_port", "a status int or status int tuple to the \"codes\"", "= self.etag if not etag: if isinstance(self.body, str): etag =", "notice(self, msg, *args, **kwargs): \"\"\" Convenience function for syslog priority", "get_lines_for_level(self, level): if level not in self.lines_dict: raise KeyError( \"Invalid", "+ x, 'device': 'sda', 'zone': x % 3, 'region': x", "storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies = [ StoragePolicy(0,", "True def __ne__(self, other): return other is not True @contextmanager", "give_send if 'slow' in kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep", "use the policies rings like their own personal playground -", "language governing permissions and # limitations under the License. \"\"\"", "[], 'notice': []} clear = _clear # this is a", "cls): \"\"\" Creating a new class that inherits from decorated", "in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return dict((level, msgs) for", "handle(self, record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self,", "i, 'ip': '10.0.0.%d' % (i % self.nodes), 'replication_ip': '10.0.0.%d' %", "x % 2, 'id': x, }) @property def replica_count(self): return", "] dev_ids = itertools.cycle(range(self.devices)) for p in range(2 ** self.part_power):", "def createLock(self): pass def emit(self, record): pass def _handle(self, record):", "argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id']", "transfer_rate = _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self): return [call[0][0]", "_store_in('set_statsd_prefix') def get_increments(self): return [call[0][0] for call in self.log_dict['increment']] def", "= '1' except StopIteration: pass am_slow, value = self.get_slow() if", "during expect, can be a iter of floats :param response_sleep:", "@contextmanager def mocked_http_conn(*args, **kwargs): requests = [] def capture_requests(ip, port,", "else: self.expect_status = [100, 100] # setup sleep attributes if", "class FakeStatus(object): \"\"\" This will work with our fake_http_connect, if", "permissions and # limitations under the License. \"\"\" Swift tests", "captured = dict(kwargs) if 'exc_info' in kwargs and \\ not", "if 'slow' in kwargs and isinstance(kwargs['slow'], list): if self._next_sleep is", "**ckwargs) etag = next(etag_iter) headers = next(headers_iter) expect_headers = next(expect_headers_iter)", "bit easier to extend than the current slow kwarg -", "None self.thread_locals = None self.parent = None store_in = {", "self.devices = devices self.nodes = nodes self.port = port self.replicas", "by. \"\"\" def __init__(self, body, slowness): self.body = body self.slowness", "+ '\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length':", "= [x] * len(code_iter) container_ts_iter = iter(x) code_iter = iter(code_iter)", "\"\"\" orig_setUp = cls.setUp orig_tearDown = cls.tearDown def setUp(cls_self): self._orig_POLICIES", "we exercise the real ring code, but ignore the result", "for call in self.log_dict['increment']] def get_increment_counts(self): counts = {} for", "(list, tuple)): headers_iter = iter(kwargs['headers']) else: headers_iter = iter([kwargs.get('headers', {})]", "[ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE: if eclib_name", "in kwargs and \\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info()", "record): try: line = record.getMessage() except TypeError: print('WARNING: unable to", "= _send_to_logger('decrement') timing = _send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate =", "setattr(module, attr, value) for module, attr in deletes: delattr(module, attr)", "default_ring_args = [{}, {}] fake_ring_args = fake_ring_args or default_ring_args decorator", "the patch_policies wrapper outside of the TestCase instance which can", "# when a swift backend service returns a status before", "node, two replica, 2 part power ring... \"\"\" dev1 =", "return counts def setFormatter(self, obj): self.formatter = obj def close(self):", "sent the Expect 100 header. # BufferedHttp and the proxy", "response_sleep: float, time to eventlet sleep during response \"\"\" #", "governing permissions and # limitations under the License. \"\"\" Swift", "isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers',", "tuple): self.expect_status = list(status[:-1]) self.status = status[-1] self.explicit_expect_list = True", "return expect_status class SlowBody(object): \"\"\" This will work with our", "line = record.getMessage() except TypeError: print('WARNING: unable to format log", "node in enumerate(list(self._devs))] def get_more_nodes(self, part): for x in range(self.replicas,", "attr): returns.append((module, attr, getattr(module, attr))) else: deletes.append((module, attr)) setattr(module, attr,", "Our tests tend to use the policies rings like their", "fake_conn.requests = requests with mocklib.patch('swift.common.bufferedhttp.http_connect_raw', new=fake_conn): yield fake_conn left_over_status =", "not thing_or_policies: return decorator else: # it's a thing, we", "for modname in imports[1:]: module = getattr(module, modname) if hasattr(module,", "self.timestamp: # when timestamp is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp',", "else: default_policies = [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ]", "def set(self, key, value, time=0): self.store[key] = value return True", "\"\"\" self.log(NOTICE, msg, *args, **kwargs) def _log(self, level, msg, *args,", "if self.status in (507, 412, 409): self.expect_status = [status] else:", "next(expect_headers_iter) timestamp = next(timestamps_iter) if status <= 0: raise HTTPException()", "thing.method().attribute True \"\"\" def __getattribute__(self, *args, **kwargs): return self def", "**kwargs) finally: rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def emit(self, record):", "def __getattribute__(self, name): if name == 'time': return UnmockTimeModule._orig_time return", "return f(*args, **kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES return mywrapper def", "other is True def __ne__(self, other): return other is not", "not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap'", "= itertools.cycle(range(self.devices)) for p in range(2 ** self.part_power): for r", "lc = c return rv def connect_tcp(hostport): rv = socket.socket()", "pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class FabricatedRing(Ring): \"\"\" When a FakeRing", "try: yield file_name finally: os.unlink(file_name) xattr_data = {} def _get_inode(fd):", "len(code_iter)) if not isinstance(x, (tuple, list)): x = [x] *", "if you hand in these instead of strings it will", "if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter =", "\"\"\" Swift tests \"\"\" from __future__ import print_function import os", "body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter return", "get(self, key): return self.store.get(key) def keys(self): return self.store.keys() def set(self,", "'ip': ip, 'replication_ip': ip, 'port': port, 'replication_port': port, 'device': 'sd'", "(list(contents) + [''] * c)[:c] tempdir = mkdtemp() for path,", "update_stats = _store_in('update_stats') increment = _store_in('increment') decrement = _store_in('decrement') timing", "timing = _store_in('timing') timing_since = _store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix", "getresponse(self): exc = kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception, eventlet.Timeout)):", "headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status =", "thing.method() True >>> thing.attribute.method() True >>> thing.method().attribute True \"\"\" def", "0.01 if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return", "% ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record)", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "lc == '\\r' and c == '\\n': crlfs += 1", "range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for p in range(2 **", "' (none of %r found in %r)' % ( EC_TYPE_PREFERENCE,", "a FakeRing just won't do - you can fabricate one", "unmolested behavior in a another module who imports time directly", "len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep", "this module from swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch", "fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg is not None: policy.object_ring", "_patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs): self._orig_POLICIES = storage_policy._POLICIES try:", "that status line immediately instead of 100 # Continue, even", "[dev1, dev2] part_shift = 30 with closing(GzipFile(path, 'wb')) as f:", "on the class it seemed to patch setUp at the", "sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return dict((level, msgs) for level,", "[[0, 1, 0, 1], [1, 0, 1, 0]] devs =", "rv.connect(hostport) return rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False) as", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "args required to *build* a new FakeRing instances so we", "[], 'error': [], 'info': [], 'warning': [], 'debug': [], 'notice':", "and self.explicit_expect_list: raise Exception('Test did not consume all fake '", "( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies =", "= socket.socket() rv.connect(hostport) return rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w',", "initial 3) is the cap, no matter if # this", "the wrong time (i.e. in setup the global wasn't patched", "= storage_policy._POLICIES if not getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES = self.policies", "self.sent < 4: self.sent += 1 eventlet.sleep(value) return ' '", "if am_slow: if self.received < 4: self.received += 1 eventlet.sleep(value)", "or status int tuple to the \"codes\" iter you can", "'replication_ip': ip, 'port': port, 'replication_port': port, 'device': 'sd' + (chr(ord('a')", "0 if lc == '\\r' and c == '\\n': crlfs", "expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp,", "@contextmanager def temptree(files, contents=''): # generate enough contents to fill", "bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow, value = self.get_slow() if", "you get out of ring methods will actually be based", "2 ** self.part_power for i in range(self.replicas) ] dev_ids =", "= [[0, 1, 0, 1], [1, 0, 1, 0]] devs", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand',", "module from swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX", "attr, value) try: yield True finally: for module, attr, value", "will return a MockTrue instance. >>> thing = MockTrue() >>>", "would do. if self.status in (507, 412, 409): self.expect_status =", "based on the path - otherwise we exercise the real", "FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object): \"\"\" Instances", "rv = '' lc = '' crlfs = 0 while", "object): # a thread safe fake logger def __init__(self, *args,", "+ x, 'replication_port': self._base_port + x, 'device': 'sda', 'zone': x", "AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd, k, v): inode", "mkdtemp from shutil import rmtree from swift.common.utils import Timestamp, NOTICE", "just like a real backend server would do. if self.status", "timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter = code_iter return connect", "and return 1. \"\"\" self._base_port = base_port self.max_more_nodes = max_more_nodes", "if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as f: f.write(str(content))", "part): return [dict(node, index=i) for i, node in enumerate(list(self._devs))] def", "**kwargs) def _log(self, level, msg, *args, **kwargs): store_name = self.store_in[level]", "real ring code, but ignore the result and return 1.", "levels are %s\" % (level, ', '.join(\"'%s'\" % lvl for", "delete=False) as f: file_name = f.name f.write(str(content)) try: yield file_name", "None self.parent = None store_in = { logging.ERROR: 'error', logging.WARNING:", "xattr_data.get(inode, {}) data[k] = v xattr_data[inode] = data def _getxattr(fd,", "True else: self.expect_status, self.status = ([], status) self.explicit_expect_list = False", "def get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is not None:", "required to *build* a new FakeRing instances so we can", "None: body = static_body or '' else: body = next(body_iter)", "({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0, 1],", "iter(body_iter) def connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type'", "it's a thing, we return the wrapped thing instead of", "not isinstance(fd, int): try: fd = fd.fileno() except AttributeError: return", "import swob, utils from swift.common.ring import Ring, RingData from hashlib", "ip, 'port': port, 'replication_port': port, 'device': 'sd' + (chr(ord('a') +", "def _clear(self): self.log_dict = defaultdict(list) self.lines_dict = {'critical': [], 'error':", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "= storage_policy._POLICIES try: storage_policy._POLICIES = self.policies self._setup_rings() return f(*args, **kwargs)", "DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in", "= sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs) def", "return other is True def __ne__(self, other): return other is", "format log message %r %% %r' % ( record.msg, record.args))", "key.split('.') attr = imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for modname", "Any method called on an instance of MockTrue will return", "**kwargs): store_name = self.store_in[level] cargs = [msg] if any(args): cargs.extend(args)", "**kwargs): self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES = self.policies self._setup_rings() return", "tempdir as argument to test method. \"\"\" @functools.wraps(f) def wrapped(*args,", "raise KeyError( \"Invalid log level '%s'; valid levels are %s\"", "counts def setFormatter(self, obj): self.formatter = obj def close(self): self._clear()", "body (mostly an error response) eventlet.wsgi will # respond with", "specific language governing permissions and # limitations under the License.", "def soft_lock(self, key, timeout=0, retries=5): yield True def delete(self, key):", "zip(self.policies, self.fake_ring_args): if fake_ring_arg is not None: policy.object_ring = FakeRing(**fake_ring_arg)", "StoragePolicy(1, name='unu'), ] default_ring_args = [{}, {}] fake_ring_args = fake_ring_args", "2 part power ring... \"\"\" dev1 = {'id': 0, 'zone':", "kwargs['slow'].pop(0) except IndexError: self._next_sleep = None # be nice to", "import storage_policy from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools", "self.status in (507, 412, 409): self.expect_status = [status] else: self.expect_status", "= _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix = _send_to_logger('set_statsd_prefix') def __getattribute__(self,", "= '1234' self.sent = 0 self.received = 0 self.etag =", "if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status() return self def", "thing != False # True != False True >>> thing.attribute", "we wanted to do something smarter than just duck-type the", "kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1", "\\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger,", "FakeStatus(object): \"\"\" This will work with our fake_http_connect, if you", "'exc_info' in kwargs and \\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] =", "default_ring_args = [{'replicas': 14}, {}] else: default_policies = [ StoragePolicy(0,", "mock.patch? In my case, when used as a decorator on", "self.get_increments(): if metric not in counts: counts[metric] = 0 counts[metric]", "25, just above info. SysLogHandler is monkey patched to map", "you set a part_power when you setup your FakeRing the", "self.policies def __exit__(self, *args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def", "import HTTPException from swift.common import storage_policy from swift.common.storage_policy import (StoragePolicy,", "status: the response status int, or a tuple of ([expect_status,", ":param response_sleep: float, time to eventlet sleep during response \"\"\"", "in self.lines_dict.items() if len(msgs) > 0) def _store_in(store_name): def stub_fn(self,", "crlfs = 0 while crlfs < 2: c = fd.read(1)", "f.name f.write(str(content)) try: yield file_name finally: os.unlink(file_name) xattr_data = {}", "if os.path.isabs(path): path = '.' + path new_path = os.path.join(tempdir,", "the wrapped thing instead of the decorator return decorator(thing_or_policies) class", "list(args) args.append(tempdir) try: return f(*args, **kwargs) finally: rmtree(tempdir) return wrapped", "if not isinstance(fd, int): try: fd = fd.fileno() except AttributeError:", "# you may not use this file except in compliance", "power ring... \"\"\" dev1 = {'id': 0, 'zone': 0, 'device':", "in enumerate(list(self._devs))] def get_more_nodes(self, part): for x in range(self.replicas, (self.replicas", "response def getheaders(self): etag = self.etag if not etag: if", "= [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1,", "def tmpfile(content): with NamedTemporaryFile('w', delete=False) as f: file_name = f.name", "for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg is not", "the decorator return decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why not mock.patch?", "UnmockTimeModule(object): \"\"\" Even if a test mocks time.time - you", "call in self.log_dict['increment']] def get_increment_counts(self): counts = {} for metric", "1. \"\"\" self._base_port = base_port self.max_more_nodes = max_more_nodes self._part_shift =", "The python logging lvl is set to 25, just above", "[None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter = iter(kwargs['headers'])", "in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name", "hasattr(self, '_replica2part2dev_id'): return self._devs = [{ 'region': 1, 'zone': 1,", "2010-2012 OpenStack Foundation # # Licensed under the Apache License,", "x self._devs.append({ 'ip': ip, 'replication_ip': ip, 'port': port, 'replication_port': port,", "'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', } def notice(self, msg, *args,", "\"\"\" for policy, fake_ring_arg in zip(self.policies, self.fake_ring_args): if fake_ring_arg is", "True >>> thing.attribute.method() True >>> thing.method().attribute True \"\"\" def __getattribute__(self,", "two node, two replica, 2 part power ring... \"\"\" dev1", "'1.2.3.4' self.port = '1234' self.sent = 0 self.received = 0", "kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise", "eventlet.sleep(value) return ' ' rv = self.body[:amt] self.body = self.body[amt:]", "list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep = response_sleep def", "% x port = self._base_port + x self._devs.append({ 'ip': ip,", "...], response_status) :param expect_sleep: float, time to eventlet sleep during", "len(code_iter)) x = kwargs.get('missing_container', [False] * len(code_iter)) if not isinstance(x,", "# implied. # See the License for the specific language", "part calculation based on the path If you set a", "import itertools from numbers import Number from tempfile import NamedTemporaryFile", "x in range(self.replicas): ip = '10.0.0.%s' % x port =", "in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map =", "ec_segment_size=4096), StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas': 14}, {}] else:", "_handlers self._name = name def acquire(self): pass def release(self): pass", "qs, ssl): req = { 'ip': ip, 'port': port, 'method':", "= fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "to import this module from swift if not os.path.basename(sys.argv[0]).startswith('swift'): #", "return True def incr(self, key, time=0): self.store[key] = self.store.setdefault(key, 0)", "release(self): pass def createLock(self): pass def emit(self, record): pass def", "def connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in", "FakeLogger\"\"\" def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter =", "= [dev1, dev2] part_shift = 30 with closing(GzipFile(path, 'wb')) as", "value) try: yield True finally: for module, attr, value in", "% x, 'port': self._base_port + x, 'replication_port': self._base_port + x,", "tests tend to use the policies rings like their own", "delattr(module, attr) class FakeStatus(object): \"\"\" This will work with our", "self._devs.append({ 'ip': ip, 'replication_ip': ip, 'port': port, 'replication_port': port, 'device':", "MockTrue evaluate like True Any attr accessed on an instance", "for x in range(self.replicas): ip = '10.0.0.%s' % x port", "req = { 'ip': ip, 'port': port, 'method': method, 'path':", "= next(body_iter) return FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i,", "be a problem in the particular case of a patched", "in self.log_dict['increment']] def get_increment_counts(self): counts = {} for metric in", "method gets a clean ring setup. The TestCase can always", "under the Apache License, Version 2.0 (the \"License\"); # you", "set higher, or R^2 for R replicas self.set_replicas(replicas) self._reload() def", "def _setup_rings(self): \"\"\" Our tests tend to use the policies", "def close(self): self._clear() def set_name(self, name): # don't touch _handlers", "in range(self.replicas, (self.replicas + self.max_more_nodes)): yield {'ip': '10.0.0.%s' % x,", "[{}] elif with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE,", "status line immediately instead of 100 # Continue, even if", "with NamedTemporaryFile('w', delete=False) as f: file_name = f.name f.write(str(content)) try:", "msg, *args, **kwargs): store_name = self.store_in[level] cargs = [msg] if", "try: yield tempdir finally: rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator to", "attr in deletes: delattr(module, attr) class FakeStatus(object): \"\"\" This will", "contents = (list(contents) + [''] * c)[:c] tempdir = mkdtemp()", "in deletes: delattr(module, attr) class FakeStatus(object): \"\"\" This will work", "itertools.cycle(range(self.devices)) for p in range(2 ** self.part_power): for r in", "if 'slow' in kwargs and isinstance(kwargs['slow'], list): try: self._next_sleep =", "4: self.sent += 1 eventlet.sleep(value) return ' ' rv =", "utils from swift.common.ring import Ring, RingData from hashlib import md5", "StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args = [{}, {}]", "Any attr accessed on an instance of MockTrue will return", "exc = kwargs.get('raise_exc') if exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise", "fake_ring_arg is not None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self, thing):", "the \"codes\" iter you can add some eventlet sleep to", "new_path = os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if not os.path.exists(subdir):", "get the same \"reset\" behavior with custom FakeRing's they can", "line immediately instead of 100 # Continue, even if the", "SysLogHandler is monkey patched to map this log lvl to", "status = FakeStatus(status) self._status = status self.reason = 'Fake' self.host", "If you set a part_power when you setup your FakeRing", "is True def __ne__(self, other): return other is not True", "when super is called from inside methods in the decorated", "+= 1 return counts def setFormatter(self, obj): self.formatter = obj", "data = xattr_data.get(inode, {}).get(k) if not data: raise IOError(errno.ENODATA, \"Fake", "= _send_to_logger('increment') decrement = _send_to_logger('decrement') timing = _send_to_logger('timing') timing_since =", "}) @property def replica_count(self): return self.replicas def _get_part_nodes(self, part): return", "in setUp - or if they'd prefer to get the", "in kwargs: self.facility = kwargs['facility'] self.statsd_client = None self.thread_locals =", "import logging.handlers from six.moves.http_client import HTTPException from swift.common import storage_policy", "True == False False >>> thing != True # True", "kwargs: give_conn_fn = kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or", "or '' else: body = next(body_iter) return FakeConn(status, etag, body=body,", "+ x)), 'zone': x % 3, 'region': x % 2,", "for key, value in update.items(): imports = key.split('.') attr =", "body_iter is None: body = static_body or '' else: body", "in update.items(): imports = key.split('.') attr = imports.pop(-1) module =", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools import six.moves.cPickle as", "i, status = next(conn_id_and_code_iter) if 'give_connect' in kwargs: give_conn_fn =", "path - otherwise we exercise the real ring code, but", "class FakeMemcache(object): def __init__(self): self.store = {} def get(self, key):", "self.explicit_expect_list = True else: self.expect_status, self.status = ([], status) self.explicit_expect_list", "replicas=3, max_more_nodes=0, part_power=0, base_port=1000): \"\"\" :param part_power: make part calculation", "return bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow, value = self.get_slow()", "self.expect_sleep_list.append(None) self.response_sleep = response_sleep def get_response_status(self): if self.response_sleep is not", "instead of the decorator return decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why", "mkdtemp() args = list(args) args.append(tempdir) try: return f(*args, **kwargs) finally:", "directly by monkey patching it's imported reference to the module", "%(levelname)s: %(message)s\") def handle(self, record): self._handle(record) print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def", "to extend than the current slow kwarg - which inserts", "def __call__(self, *args, **kwargs): return self def __repr__(*args, **kwargs): return", "tempfile import NamedTemporaryFile import time import eventlet from eventlet.green import", "of this class \"\"\" _orig_time = time.time def __getattribute__(self, name):", "in (507, 412, 409): self.expect_status = [status] else: self.expect_status =", "enumerate(list(self._devs))] def get_more_nodes(self, part): for x in range(self.replicas, (self.replicas +", "True >>> thing.method() True >>> thing.attribute.method() True >>> thing.method().attribute True", "headers.pop('x-timestamp', None) try: if next(container_ts_iter) is False: headers['x-container-timestamp'] = '1'", "next(dev_ids) class FakeMemcache(object): def __init__(self): self.store = {} def get(self,", "self.log_dict[store_name].append((args, kwargs)) return stub_fn # mock out the StatsD logging", "def __init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies", "kwargs.get('body_iter', None) if body_iter: body_iter = iter(body_iter) def connect(*args, **ckwargs):", "but it seems to cause infinite recursion when super is", "self._base_port = base_port self.max_more_nodes = max_more_nodes self._part_shift = 32 -", "prefer to get the same \"reset\" behavior with custom FakeRing's", "evaluate like True Any attr accessed on an instance of", "if 'facility' in kwargs: self.facility = kwargs['facility'] self.statsd_client = None", "as argument to test method. \"\"\" @functools.wraps(f) def wrapped(*args, **kwargs):", "work with our fake_http_connect, if you hand in these instead", "\"\"\" _orig_time = time.time def __getattribute__(self, name): if name ==", "decorated class is the more common way I've seen class", "DebugLogger(FakeLogger): \"\"\"A simple stdout logging version of FakeLogger\"\"\" def __init__(self,", "_send_to_logger(name): def stub_fn(self, *args, **kwargs): return getattr(self.logger, name)(*args, **kwargs) return", "import Timestamp, NOTICE from test import get_config from swift.common import", "self.give_send(self.connection_id, amt) am_slow, value = self.get_slow() if am_slow: if self.received", "devices self.nodes = nodes self.port = port self.replicas = 6", "dev2 = {'id': 0, 'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1',", "eventlet sleep during expect, can be a iter of floats", "raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status = self._status.get_response_status() return", "default) def close(self): pass timestamps_iter = iter(kwargs.get('timestamps') or ['1'] *", "hand in these instead of strings it will make reads", "%r\" % rv) rv = rv + c if c", "] default_ring_args = [{}, {}] fake_ring_args = fake_ring_args or default_ring_args", "setup. The TestCase can always \"tweak\" these fresh rings in", "if not isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep] * len(self.expect_status)", "self.part_power self._reload() def _reload(self, *args, **kwargs): self._rtime = time.time() *", "md5 import logging.handlers from six.moves.http_client import HTTPException from swift.common import", "is monkey patched to map this log lvl to the", "do - you can fabricate one to meet your tests", "etag = '\"' + md5(self.body).hexdigest() + '\"' else: etag =", "import GzipFile import mock as mocklib import inspect EMPTY_ETAG =", "= self.store.setdefault(key, 0) + 1 return self.store[key] @contextmanager def soft_lock(self,", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "sys from contextlib import contextmanager, closing from collections import defaultdict,", "'' lc = '' crlfs = 0 while crlfs <", "either express or # implied. # See the License for", "headers['x-account-container-count'] = \\ kwargs.get('count', 12345) if not self.timestamp: # when", "**kwargs): return self def __repr__(*args, **kwargs): return repr(True) def __eq__(self,", "key, value in update.items(): imports = key.split('.') attr = imports.pop(-1)", "return object.__getattribute__(self, name) except AttributeError: return getattr(self.__dict__['logger'], name) def debug_logger(name='test'):", "suitable PyECLib type' ' (none of %r found in %r)'", "3) is the cap, no matter if # this is", "for i in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices)) for p", "timing = _send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix", "== True # True == True True >>> thing ==", "return self def __call__(self, *args, **kwargs): return self def __repr__(*args,", "= key.split('.') attr = imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for", "proxy both see these error statuses # when they call", "self._part_shift = 32 - self.part_power self._reload() def _reload(self, *args, **kwargs):", "statuses # when they call getexpect, so our FakeConn tries", "os.path.isabs(path): path = '.' + path new_path = os.path.join(tempdir, path)", "if name == 'time': return UnmockTimeModule._orig_time return getattr(time, name) #", "deletes: delattr(module, attr) class FakeStatus(object): \"\"\" This will work with", "% i, 'ip': '10.0.0.%d' % (i % self.nodes), 'replication_ip': '10.0.0.%d'", "0, 1, 0]] devs = [dev1, dev2] part_shift = 30", "'\"' + md5(self.body).hexdigest() + '\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers", "100 == 2: headers['x-account-container-count'] = \\ kwargs.get('count', 12345) if not", "Apache License, Version 2.0 (the \"License\"); # you may not", "def wrapped(*args, **kwargs): tempdir = mkdtemp() args = list(args) args.append(tempdir)", "etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test',", "for lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return dict((level,", "__init__(self, replicas=6, devices=8, nodes=4, port=6000, part_power=4): self.devices = devices self.nodes", "expect_status = self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status == 409:", "[{}, {}] fake_ring_args = fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies,", "= self._status.get_expect_status() headers = dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp']", "class is the more common way I've seen class decorators", "Pretty much just a two node, two replica, 2 part", "getexpect, so our FakeConn tries to act like # our", "= self.get_slow() if am_slow: headers['content-length'] = '4' headers.update(self.headers) return headers.items()", "self)._log(level, msg, *args, **kwargs) def _clear(self): self.log_dict = defaultdict(list) self.lines_dict", "+ (chr(ord('a') + x)), 'zone': x % 3, 'region': x", "== '\\r' and lc != '\\n': crlfs = 0 if", "else: kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter) if 'give_connect' in kwargs:", "True @contextmanager def mock(update): returns = [] deletes = []", "yield fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over", "mkdtemp() for path, content in zip(files, contents): if os.path.isabs(path): path", "len(self.body) def __radd__(self, other): self.slowdown() return other + self.body def", "an error response) eventlet.wsgi will # respond with that status", "[], 'info': [], 'warning': [], 'debug': [], 'notice': []} clear", "0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': 6000} dev1_updates, dev2_updates =", "+ md5(self.body).hexdigest() + '\"' else: etag = '\"68b329da9893e34099c7d8ad5cb9c940\"' headers =", "'ip': '127.0.0.1', 'port': 6000} dev1_updates, dev2_updates = devs or ({},", "of the decorator return decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why not", "self.set_replicas(replicas) self._reload() def _reload(self): self._rtime = time.time() def set_replicas(self, replicas):", "self.sent = 0 self.received = 0 self.etag = etag self.body", "yield {'ip': '10.0.0.%s' % x, 'replication_ip': '10.0.0.%s' % x, 'port':", "instance. >>> thing = MockTrue() >>> thing True >>> thing", "self.port = port self.replicas = 6 self.part_power = part_power self._part_shift", "give a single test a tempdir as argument to test", "setup the global wasn't patched yet) \"\"\" def __init__(self, policies,", "time=0): self.store[key] = value return True def incr(self, key, time=0):", "to cause infinite recursion when super is called from inside", "fake_ring_args to patch_policies instead of setting the object_ring on the", "Continue, even if the client sent the Expect 100 header.", "x port = self._base_port + x self._devs.append({ 'ip': ip, 'replication_ip':", "= timestamp self.connection_id = connection_id self.give_send = give_send if 'slow'", "for module, attr in deletes: delattr(module, attr) class FakeStatus(object): \"\"\"", "MockTrue will return a MockTrue instance. >>> thing = MockTrue()", "'yes', }) if self.status // 100 == 2: headers['x-account-container-count'] =", "= self.timestamp response = FakeConn(expect_status, timestamp=self.timestamp, headers=headers) response.status = expect_status", "x, 'replication_ip': '10.0.0.%s' % x, 'port': self._base_port + x, 'replication_port':", "raise ValueError(\"didn't get two CRLFs; just got %r\" % rv)", "KIND, either express or # implied. # See the License", "store_name = self.store_in[level] cargs = [msg] if any(args): cargs.extend(args) captured", "FakeConn tries to act like # our backend services and", "imports[1:]: module = getattr(module, modname) if hasattr(module, attr): returns.append((module, attr,", "amount. It should be a little bit easier to extend", "kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow, value =", "will work with our fake_http_connect, if you hand in one", "get better isolation without having to think about it, here", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "it will make reads take longer by the given amount.", "self.port, 'replication_port': self.port, } for i in range(self.devices)] self._replica2part2dev_id =", "attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger", "Number from tempfile import NamedTemporaryFile import time import eventlet from", "yield True def delete(self, key): try: del self.store[key] except Exception:", "just above info. SysLogHandler is monkey patched to map this", "expect_headers=None, connection_id=None, give_send=None): if not isinstance(status, FakeStatus): status = FakeStatus(status)", "= 'Fake' self.host = '1.2.3.4' self.port = '1234' self.sent =", "rmtree(tempdir) return wrapped class NullLoggingHandler(logging.Handler): def emit(self, record): pass class", "**kwargs): return getattr(self.logger, name)(*args, **kwargs) return stub_fn # delegate to", "FakeMemcache(object): def __init__(self): self.store = {} def get(self, key): return", "other + self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def __init__(self,", "a status before reading # from the body (mostly an", "some eventlet sleep to the expect and response stages of", "= '\"68b329da9893e34099c7d8ad5cb9c940\"' headers = swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp':", "kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter) if 'give_connect' in kwargs: give_conn_fn", "= [ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args =", "swift if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX", "thing_or_policies: return decorator else: # it's a thing, we return", "if isinstance(self.body, str): etag = '\"' + md5(self.body).hexdigest() + '\"'", "return self.store.keys() def set(self, key, value, time=0): self.store[key] = value", "status: %r' % (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status", "iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body', None) body_iter =", "inside of FakeConn if we wanted to do something smarter", "kwargs and isinstance(kwargs['slow'], list): if self._next_sleep is not None: return", "all_log_lines(self): return dict((level, msgs) for level, msgs in self.lines_dict.items() if", "part): for x in range(self.replicas, (self.replicas + self.max_more_nodes)): yield {'ip':", "my case, when used as a decorator on the class", "if fake_ring_arg is not None: policy.object_ring = FakeRing(**fake_ring_arg) def __call__(self,", "1.0, 'id': i, 'device': 'sda%d' % i, 'ip': '10.0.0.%d' %", "python logging lvl is set to 25, just above info.", "tempdir = mkdtemp() args = list(args) args.append(tempdir) try: return f(*args,", "is a public interface def get_lines_for_level(self, level): if level not", "args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter) if 'give_connect'", "a MockTrue instance. Any method called on an instance of", "call to the patch_policies wrapper outside of the TestCase instance", "itertools from numbers import Number from tempfile import NamedTemporaryFile import", "decorator else: # it's a thing, we return the wrapped", "in zip(self.policies, self.fake_ring_args): if fake_ring_arg is not None: policy.object_ring =", "expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status", "you hand in one of these instead of a status", "get_expect_status(self): expect_sleep = self.expect_sleep_list.pop(0) if expect_sleep is not None: eventlet.sleep(expect_sleep)", "TestCase can always \"tweak\" these fresh rings in setUp -", "cls_self._policies_patched = True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES", "= slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s],", "eventlet from eventlet.green import socket from tempfile import mkdtemp from", "= __import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]: module = getattr(module,", "fake_http_connect, if you hand in one of these instead of", "len(msgs) > 0) def _store_in(store_name): def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args,", "= fd.read(1) if not c: raise ValueError(\"didn't get two CRLFs;", "setup your FakeRing the parts you get out of ring", "can be a iter of floats :param response_sleep: float, time", "def setUp(cls_self): self._orig_POLICIES = storage_policy._POLICIES if not getattr(cls_self, '_policies_patched', False):", "call getexpect, so our FakeConn tries to act like #", "as a decorator on the class it seemed to patch", "class FakeLogger(logging.Logger, object): # a thread safe fake logger def", "_get_inode(fd) data = xattr_data.get(inode, {}).get(k) if not data: raise IOError(errno.ENODATA,", "or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if not thing_or_policies: return", "dev1 = {'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1',", "gzip import GzipFile import mock as mocklib import inspect EMPTY_ETAG", "the call to the patch_policies wrapper outside of the TestCase", "dev2] part_shift = 30 with closing(GzipFile(path, 'wb')) as f: pickle.dump(RingData(replica2part2dev_id,", "pass return True def readuntil2crlfs(fd): rv = '' lc =", "%% %r' % ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self,", "in these instead of strings it will make reads take", "= self.store_in[level] cargs = [msg] if any(args): cargs.extend(args) captured =", "get_increments(self): return [call[0][0] for call in self.log_dict['increment']] def get_increment_counts(self): counts", "'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at': '9876543210',", "be based on the path - otherwise we exercise the", "xattr_data.get(inode, {}).get(k) if not data: raise IOError(errno.ENODATA, \"Fake IOError\") return", "if isinstance(self.status, (Exception, eventlet.Timeout)): raise self.status return self.status def get_expect_status(self):", "of these (or a subclass) for the body inside of", "getattr(cls_self, '_policies_patched', False): storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched = True", "len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None] * len(code_iter)) if isinstance(kwargs.get('headers'),", "patching it's imported reference to the module with an instance", "FakeRing(**fake_ring_arg) def __call__(self, thing): if isinstance(thing, type): return self._patch_class(thing) else:", "__init__(self, status, etag=None, body='', timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None): if", "except IndexError: self._next_sleep = None # be nice to trixy", "key): try: del self.store[key] except Exception: pass return True def", "c)[:c] tempdir = mkdtemp() for path, content in zip(files, contents):", "self.store[key] = value return True def incr(self, key, time=0): self.store[key]", "isinstance(thing_or_policies, ( Iterable, storage_policy.StoragePolicyCollection)): return PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies", "named adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler", "= kwargs['slow'].pop(0) except IndexError: self._next_sleep = None # be nice", "'\\n': crlfs = 0 if lc == '\\r' and c", "c = len(files) contents = (list(contents) + [''] * c)[:c]", "storage_policy._POLICIES try: storage_policy._POLICIES = self.policies self._setup_rings() return f(*args, **kwargs) finally:", "expect_status return expect_status class SlowBody(object): \"\"\" This will work with", "_patch_class(self, cls): \"\"\" Creating a new class that inherits from", "dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0, 1], [1, 0, 1,", "def handleError(self, record): pass class DebugLogger(FakeLogger): \"\"\"A simple stdout logging", "self.port = '1234' self.sent = 0 self.received = 0 self.etag", "_setxattr xattr.getxattr = _getxattr @contextmanager def temptree(files, contents=''): # generate", "finally: storage_policy._POLICIES = self._orig_POLICIES return mywrapper def __enter__(self): self._orig_POLICIES =", "in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag = next(etag_iter)", "next(etag_iter) headers = next(headers_iter) expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter)", "xattr.getxattr = _getxattr @contextmanager def temptree(files, contents=''): # generate enough", "mock as mocklib import inspect EMPTY_ETAG = md5().hexdigest() # try", "the decorated class. \"\"\" orig_setUp = cls.setUp orig_tearDown = cls.tearDown", "path new_path = os.path.join(tempdir, path) subdir = os.path.dirname(new_path) if not", "# a thread safe fake logger def __init__(self, *args, **kwargs):", "use this file except in compliance with the License. #", "self.formatter = obj def close(self): self._clear() def set_name(self, name): #", "__init__(self, *args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET", "a new class that inherits from decorated class is the", "path, 'headers': headers, 'qs': qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect',", "in returns: setattr(module, attr, value) for module, attr in deletes:", "part_power when you setup your FakeRing the parts you get", "dict(self.expect_headers) if expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp response =", "name) def debug_logger(name='test'): \"\"\"get a named adapted debug logger\"\"\" return", "headers = next(headers_iter) expect_headers = next(expect_headers_iter) timestamp = next(timestamps_iter) if", "import copy import logging import errno from six.moves import range", "their own fake_ring_args to patch_policies instead of setting the object_ring", "_handle(self, record): try: line = record.getMessage() except TypeError: print('WARNING: unable", "swift.common import storage_policy from swift.common.storage_policy import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import", "# True == True True >>> thing == False #", "getattr(module, attr))) else: deletes.append((module, attr)) setattr(module, attr, value) try: yield", "work with our fake_http_connect, if you hand in one of", "tuple to the \"codes\" iter you can add some eventlet", "# when they call getexpect, so our FakeConn tries to", "path If you set a part_power when you setup your", "== 2: headers['x-account-container-count'] = \\ kwargs.get('count', 12345) if not self.timestamp:", "!= '\\n': crlfs = 0 if lc == '\\r' and", "< 4: self.sent += 1 eventlet.sleep(value) return ' ' rv", "c = fd.read(1) if not c: raise ValueError(\"didn't get two", "self._clear() self.name = 'swift.unit.fake_logger' self.level = logging.NOTSET if 'facility' in", "imported reference to the module with an instance of this", "the License. \"\"\" Swift tests \"\"\" from __future__ import print_function", "_store_in('increment') decrement = _store_in('decrement') timing = _store_in('timing') timing_since = _store_in('timing_since')", "isinstance(thing, type): return self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self, cls):", "True def delete(self, key): try: del self.store[key] except Exception: pass", "= response_sleep def get_response_status(self): if self.response_sleep is not None: eventlet.sleep(self.response_sleep)", "the policies rings like their own personal playground - which", "self.policies self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES", "- you can fabricate one to meet your tests needs.", "client sent the Expect 100 header. # BufferedHttp and the", "'ip': '10.0.0.%d' % (i % self.nodes), 'replication_ip': '10.0.0.%d' % (i", "self.received += 1 eventlet.sleep(value) def getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name,", "attr, getattr(module, attr))) else: deletes.append((module, attr)) setattr(module, attr, value) try:", "*args): storage_policy._POLICIES = self._orig_POLICIES class FakeRing(Ring): def __init__(self, replicas=3, max_more_nodes=0,", "a thing, we return the wrapped thing instead of the", "x)), 'zone': x % 3, 'region': x % 2, 'id':", "metric not in counts: counts[metric] = 0 counts[metric] += 1", "if 'give_connect' in kwargs: give_conn_fn = kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn)", "% rv) rv = rv + c if c ==", "FakeLogger.__init__(self, *args, **kwargs) self.formatter = logging.Formatter( \"%(server)s %(levelname)s: %(message)s\") def", "not consume all fake ' 'expect status: %r' % (self.expect_status,))", "= [] for x in range(self.replicas): ip = '10.0.0.%s' %", "in compliance with the License. # You may obtain a", "key, timeout=0, retries=5): yield True def delete(self, key): try: del", "software # distributed under the License is distributed on an", "= mkdtemp() args = list(args) args.append(tempdir) try: return f(*args, **kwargs)", "isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise", "self.body = body self.headers = headers or {} self.expect_headers =", "sleep attributes if not isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep]", "_store_in('decrement') timing = _store_in('timing') timing_since = _store_in('timing_since') transfer_rate = _store_in('transfer_rate')", "it's imported reference to the module with an instance of", "([], status) self.explicit_expect_list = False if not self.expect_status: # when", "True >>> thing.method().attribute True \"\"\" def __getattribute__(self, *args, **kwargs): return", "# this is set higher, or R^2 for R replicas", "4: self.received += 1 eventlet.sleep(value) def getheader(self, name, default=None): return", "not etag: if isinstance(self.body, str): etag = '\"' + md5(self.body).hexdigest()", "time (i.e. in setup the global wasn't patched yet) \"\"\"", "in zip(files, contents): if os.path.isabs(path): path = '.' + path", "[expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status):", "0 self.received = 0 self.etag = etag self.body = body", "__init__(self): self.store = {} def get(self, key): return self.store.get(key) def", "logging lvl is set to 25, just above info. SysLogHandler", "# True != False True >>> thing.attribute True >>> thing.method()", "status <= 0: raise HTTPException() if body_iter is None: body", "= True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp", "eventlet.Timeout)): raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status", "subdir = os.path.dirname(new_path) if not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w')", "self.policies = policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args", "default_policies = [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096),", "errno from six.moves import range import sys from contextlib import", "% self.nodes), 'port': self.port, 'replication_port': self.port, } for i in", "to eventlet sleep during response \"\"\" # connect exception if", "nodes=4, port=6000, part_power=4): self.devices = devices self.nodes = nodes self.port", "default_ring_args = [{}] elif with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec',", "debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler():", "and \\ not isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured))", "self.expect_headers = expect_headers or {} self.timestamp = timestamp self.connection_id =", "xattr.setxattr = _setxattr xattr.getxattr = _getxattr @contextmanager def temptree(files, contents=''):", "0.1 def read(self, amt=None): am_slow, value = self.get_slow() if am_slow:", "connect(*args, **ckwargs): if kwargs.get('slow_connect', False): eventlet.sleep(0.1) if 'give_content_type' in kwargs:", "am_slow: headers['content-length'] = '4' headers.update(self.headers) return headers.items() def get_slow(self): if", "print(self.formatter.format(record)) class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self, *args, **kwargs): return", "get_config from swift.common import swob, utils from swift.common.ring import Ring,", "custom FakeRing's they can pass in their own fake_ring_args to", "def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s], self.slowness) def", "value in returns: setattr(module, attr, value) for module, attr in", "original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for attr in dir(original_syslog_handler): if", "response) eventlet.wsgi will # respond with that status line immediately", "\"\"\" dev1 = {'id': 0, 'zone': 0, 'device': 'sda1', 'ip':", "policies rings like their own personal playground - which can", "slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return SlowBody(self.body[s], self.slowness) def __len__(self):", "for p in range(2 ** self.part_power): for r in range(self.replicas):", "ring setup. The TestCase can always \"tweak\" these fresh rings", "ring code, but ignore the result and return 1. \"\"\"", "return rv def send(self, amt=None): if self.give_send: self.give_send(self.connection_id, amt) am_slow,", "if expect_status == 409: headers['X-Backend-Timestamp'] = self.timestamp response = FakeConn(expect_status,", "the parts you get out of ring methods will actually", "= [] for key, value in update.items(): imports = key.split('.')", "is_default=True), ] default_ring_args = [{}] elif with_ec_default: default_policies = [", "def __getattribute__(self, *args, **kwargs): return self def __call__(self, *args, **kwargs):", "services and return certain types of responses # as expect", "PyECLib type' ' (none of %r found in %r)' %", "return self.store[key] @contextmanager def soft_lock(self, key, timeout=0, retries=5): yield True", "the FakeRing objects are scoped in the call to the", "self.expect_status = [100, 100] # setup sleep attributes if not", "(Exception, eventlet.Timeout)): raise self.status return self.status def get_expect_status(self): expect_sleep =", "if metric not in counts: counts[metric] = 0 counts[metric] +=", "iter([kwargs.get('expect_headers', {})] * len(code_iter)) x = kwargs.get('missing_container', [False] * len(code_iter))", "False): eventlet.sleep(0.1) if 'give_content_type' in kwargs: if len(args) >= 7", "_get_part_nodes(self, part): return [dict(node, index=i) for i, node in enumerate(list(self._devs))]", "to use the policies rings like their own personal playground", "handle(self, record): self._handle(record) def flush(self): pass def handleError(self, record): pass", "VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None):", "code, but ignore the result and return 1. \"\"\" self._base_port", "in their own fake_ring_args to patch_policies instead of setting the", "thread safe fake logger def __init__(self, *args, **kwargs): self._clear() self.name", "a real backend server would do. if self.status in (507,", "} for i in range(self.devices)] self._replica2part2dev_id = [ [None] *", "eventlet sleep to the expect and response stages of the", "setattr(module, attr, value) try: yield True finally: for module, attr,", "with the License. # You may obtain a copy of", "get_more_nodes(self, part): for x in range(self.replicas, (self.replicas + self.max_more_nodes)): yield", "(mostly an error response) eventlet.wsgi will # respond with that", "import rmtree from swift.common.utils import Timestamp, NOTICE from test import", "legacy_only: default_policies = [ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args =", "= list(args) args.append(tempdir) try: return f(*args, **kwargs) finally: rmtree(tempdir) return", "def send(self, amt=None): if self.give_send: self.give_send(self.connection_id, amt) am_slow, value =", "self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self) def tearDown(cls_self): orig_tearDown(cls_self) storage_policy._POLICIES =", "six.moves import range import sys from contextlib import contextmanager, closing", "self.max_more_nodes)): yield {'ip': '10.0.0.%s' % x, 'replication_ip': '10.0.0.%s' % x,", "if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map)", "tests get better isolation without having to think about it,", "= status self.reason = 'Fake' self.host = '1.2.3.4' self.port =", "def with_tempdir(f): \"\"\" Decorator to give a single test a", "'Fake' self.host = '1.2.3.4' self.port = '1234' self.sent = 0", "if self.status // 100 == 2: headers['x-account-container-count'] = \\ kwargs.get('count',", "port, method, path, headers, qs, ssl): req = { 'ip':", "%r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def", "a new FakeRing instances so we can ensure each test", "eventlet.sleep(0.1) if 'give_content_type' in kwargs: if len(args) >= 7 and", "[status] else: self.expect_status = [100, 100] # setup sleep attributes", "x, }) @property def replica_count(self): return self.replicas def _get_part_nodes(self, part):", "name) # logging.LogRecord.__init__ calls time.time logging.time = UnmockTimeModule() class FakeLogger(logging.Logger,", "= self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return expect_status", "'\\n': crlfs += 1 lc = c return rv def", "tests \"\"\" from __future__ import print_function import os import copy", "FakeLogger.priority_map = \\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog',", "with our fake_http_connect, if you hand in one of these", "TypeError: print('WARNING: unable to format log message %r %% %r'", "cause infinite recursion when super is called from inside methods", "or {} self.timestamp = timestamp self.connection_id = connection_id self.give_send =", "from six.moves import range import sys from contextlib import contextmanager,", "= obj def close(self): self._clear() def set_name(self, name): # don't", "raise exc raise Exception('test') if kwargs.get('raise_timeout_exc'): raise eventlet.Timeout() self.status =", "except in compliance with the License. # You may obtain", "for syslog priority LOG_NOTICE. The python logging lvl is set", "default_policies = [ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args = [{}]", "the path - otherwise we exercise the real ring code,", "name='legacy', is_default=True), ] default_ring_args = [{}] elif with_ec_default: default_policies =", "kwarg - which inserts whitespace in the response. Also it", "pickle from gzip import GzipFile import mock as mocklib import", "part_shift), f) class FabricatedRing(Ring): \"\"\" When a FakeRing just won't", "make part calculation based on the path If you set", "list)): x = [x] * len(code_iter) container_ts_iter = iter(x) code_iter", "f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class FabricatedRing(Ring): \"\"\" When a", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "[ [None] * 2 ** self.part_power for i in range(self.replicas)", "'127.0.0.1', 'port': 6000} dev1_updates, dev2_updates = devs or ({}, {})", "StoragePolicy(1, name='unu'), ] default_ring_args = [{'replicas': 14}, {}] else: default_policies", "= [{ 'region': 1, 'zone': 1, 'weight': 1.0, 'id': i,", "for i in range(self.devices)] self._replica2part2dev_id = [ [None] * 2", "__import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]: module = getattr(module, modname)", "] for eclib_name in EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break", "with node_iter's eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc') if exc:", "' rv = self.body[:amt] self.body = self.body[amt:] return rv def", "# don't touch _handlers self._name = name def acquire(self): pass", "except AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd, k, v):", "def _handle(self, record): try: line = record.getMessage() except TypeError: print('WARNING:", "len(code_iter)) if isinstance(kwargs.get('expect_headers'), (list, tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter", "32 - self.part_power self._reload() def _reload(self, *args, **kwargs): self._rtime =", "rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator to give a single test", "some bled state. To help tests get better isolation without", "you can restore unmolested behavior in a another module who", "left_over_status = list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over status %r'", "your FakeRing the parts you get out of ring methods", "if hasattr(module, attr): returns.append((module, attr, getattr(module, attr))) else: deletes.append((module, attr))", "== False False >>> thing != True # True !=", "setting the object_ring on the policy definitions. \"\"\" for policy,", "attr)) setattr(module, attr, value) try: yield True finally: for module,", "of MockTrue will return a MockTrue instance. >>> thing =", "= inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id'] =", "module, attr, value in returns: setattr(module, attr, value) for module,", "return 1. \"\"\" self._base_port = base_port self.max_more_nodes = max_more_nodes self._part_shift", "{} def _get_inode(fd): if not isinstance(fd, int): try: fd =", "- which can be a problem in the particular case", "xattr xattr.setxattr = _setxattr xattr.getxattr = _getxattr @contextmanager def temptree(files,", "the global wasn't patched yet) \"\"\" def __init__(self, policies, fake_ring_args=None):", "attr = imports.pop(-1) module = __import__(imports[0], fromlist=imports[1:]) for modname in", "just got %r\" % rv) rv = rv + c", "self._base_port + x, 'device': 'sda', 'zone': x % 3, 'region':", "_clear # this is a public interface def get_lines_for_level(self, level):", "store_in = { logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG:", "1, 0, 1], [1, 0, 1, 0]] devs = [dev1,", "inode = _get_inode(fd) data = xattr_data.get(inode, {}).get(k) if not data:", "to map this log lvl to the LOG_NOTICE syslog priority.", "when they call getexpect, so our FakeConn tries to act", "return a MockTrue instance. Any method called on an instance", "level, msg, *args, **kwargs): store_name = self.store_in[level] cargs = [msg]", "'False')): fake_syslog_handler() class MockTrue(object): \"\"\" Instances of MockTrue evaluate like", "logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for", "or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id = [[0, 1, 0,", "= self._orig_POLICIES return mywrapper def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES", "yet) \"\"\" def __init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies", "given amount. It should be a little bit easier to", "not True @contextmanager def mock(update): returns = [] deletes =", "return True, kwargs['slow'] return bool(kwargs.get('slow')), 0.1 def read(self, amt=None): am_slow,", "and # limitations under the License. \"\"\" Swift tests \"\"\"", "def stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn # mock", "kwargs['give_connect'] argspec = inspect.getargspec(give_conn_fn) if argspec.keywords or 'connection_id' in argspec.args:", "to find suitable PyECLib type' ' (none of %r found", "(6 more past the initial 3) is the cap, no", "static_body or '' else: body = next(body_iter) return FakeConn(status, etag,", "import contextmanager, closing from collections import defaultdict, Iterable import itertools", "the proxy both see these error statuses # when they", "all fake ' 'expect status: %r' % (self.expect_status,)) if isinstance(self.status,", "+= 1 eventlet.sleep(value) return ' ' rv = self.body[:amt] self.body", "= iter(kwargs.get('etags') or [None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)):", "self.status // 100 == 2: headers['x-account-container-count'] = \\ kwargs.get('count', 12345)", "other): return other is not True @contextmanager def mock(update): returns", "raises KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter) is False: headers['x-container-timestamp']", "storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None] * len(self.policies) def _setup_rings(self):", "return stub_fn # mock out the StatsD logging methods: update_stats", "expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter)) x = kwargs.get('missing_container', [False]", "for module, attr, value in returns: setattr(module, attr, value) for", "logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', } def notice(self, msg,", "import functools import six.moves.cPickle as pickle from gzip import GzipFile", "= i give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers = next(headers_iter)", "'sda%d' % i, 'ip': '10.0.0.%d' % (i % self.nodes), 'replication_ip':", "methods will actually be based on the path - otherwise", "try: line = record.getMessage() except TypeError: print('WARNING: unable to format", "inserts whitespace in the response. Also it should be easy", "are scoped in the call to the patch_policies wrapper outside", "class \"\"\" _orig_time = time.time def __getattribute__(self, name): if name", "ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4, ec_segment_size=4096), StoragePolicy(1, name='unu'), ]", "an instance of this class \"\"\" _orig_time = time.time def", "the LOG_NOTICE syslog priority. \"\"\" self.log(NOTICE, msg, *args, **kwargs) def", "iter of floats :param response_sleep: float, time to eventlet sleep", "def acquire(self): pass def release(self): pass def createLock(self): pass def", "import Number from tempfile import NamedTemporaryFile import time import eventlet", "\"\"\" def __init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies =", "(tuple, list)): x = [x] * len(code_iter) container_ts_iter = iter(x)", "update_stats = _send_to_logger('update_stats') increment = _send_to_logger('increment') decrement = _send_to_logger('decrement') timing", "'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing', 'x-delete-at':", "the client sent the Expect 100 header. # BufferedHttp and", "def __call__(self, thing): if isinstance(thing, type): return self._patch_class(thing) else: return", "conn_id_and_code_iter = enumerate(code_iter) static_body = kwargs.get('body', None) body_iter = kwargs.get('body_iter',", "accessed on an instance of MockTrue will return a MockTrue", "amt=None): am_slow, value = self.get_slow() if am_slow: if self.sent <", "orig_setUp = cls.setUp orig_tearDown = cls.tearDown def setUp(cls_self): self._orig_POLICIES =", "= iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter)) x", "def _log(self, level, msg, *args, **kwargs): store_name = self.store_in[level] cargs", "def __init__(self, status, etag=None, body='', timestamp='1', headers=None, expect_headers=None, connection_id=None, give_send=None):", "header. # BufferedHttp and the proxy both see these error", "% (level, ', '.join(\"'%s'\" % lvl for lvl in sorted(self.lines_dict))))", "FakeLogger's mocks update_stats = _send_to_logger('update_stats') increment = _send_to_logger('increment') decrement =", "you hand in these instead of strings it will make", "return DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler def fake_syslog_handler(): for attr", "connection_id=None, give_send=None): if not isinstance(status, FakeStatus): status = FakeStatus(status) self._status", "for path, content in zip(files, contents): if os.path.isabs(path): path =", "stub_fn(self, *args, **kwargs): self.log_dict[store_name].append((args, kwargs)) return stub_fn # mock out", "self.response_sleep is not None: eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise", "= '1.2.3.4' self.port = '1234' self.sent = 0 self.received =", "CONDITIONS OF ANY KIND, either express or # implied. #", "None store_in = { logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info',", "open(new_path, 'w') as f: f.write(str(content)) try: yield tempdir finally: rmtree(tempdir)", "(level, ', '.join(\"'%s'\" % lvl for lvl in sorted(self.lines_dict)))) return", "attr, value) for module, attr in deletes: delattr(module, attr) class", "+ self.body def fake_http_connect(*code_iter, **kwargs): class FakeConn(object): def __init__(self, status,", "= list(fake_conn.code_iter) if left_over_status: raise AssertionError('left over status %r' %", "**kwargs): tempdir = mkdtemp() args = list(args) args.append(tempdir) try: return", "replica, 2 part power ring... \"\"\" dev1 = {'id': 0,", "= eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, (", "'weight': 1.0, 'id': i, 'device': 'sda%d' % i, 'ip': '10.0.0.%d'", "thing == True # True == True True >>> thing", "@property def replica_count(self): return self.replicas def _get_part_nodes(self, part): return [dict(node,", "tempdir finally: rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator to give a", "the response. Also it should be easy to detect if", "easy to detect if you have one of these (or", "adapted debug logger\"\"\" return DebugLogAdapter(DebugLogger(), name) original_syslog_handler = logging.handlers.SysLogHandler def", "orig_tearDown(cls_self) storage_policy._POLICIES = self._orig_POLICIES cls.setUp = setUp cls.tearDown = tearDown", "None) body_iter = kwargs.get('body_iter', None) if body_iter: body_iter = iter(body_iter)", "pass timestamps_iter = iter(kwargs.get('timestamps') or ['1'] * len(code_iter)) etag_iter =", "isinstance(fd, int): try: fd = fd.fileno() except AttributeError: return os.stat(fd).st_ino", "headers, 'qs': qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn", "_reload(self): self._rtime = time.time() def set_replicas(self, replicas): self.replicas = replicas", "'.' + path new_path = os.path.join(tempdir, path) subdir = os.path.dirname(new_path)", "logging version of FakeLogger\"\"\" def __init__(self, *args, **kwargs): FakeLogger.__init__(self, *args,", "self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None] * len(self.policies)", "decorator return decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why not mock.patch? In", "def connect_tcp(hostport): rv = socket.socket() rv.connect(hostport) return rv @contextmanager def", "{}) data[k] = v xattr_data[inode] = data def _getxattr(fd, k):", "# as expect statuses just like a real backend server", "like True Any attr accessed on an instance of MockTrue", "slow kwarg - which inserts whitespace in the response. Also", "% 3, 'region': x % 2, 'id': x, }) @property", "an instance of MockTrue will return a MockTrue instance. >>>", "'qs': qs, 'ssl': ssl, } requests.append(req) kwargs.setdefault('give_connect', capture_requests) fake_conn =", "is called from inside methods in the decorated class. \"\"\"", "return decorator(thing_or_policies) class PatchPolicies(object): \"\"\" Why not mock.patch? In my", "except StopIteration: pass am_slow, value = self.get_slow() if am_slow: headers['content-length']", "import xattr xattr.setxattr = _setxattr xattr.getxattr = _getxattr @contextmanager def", "self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object): def __init__(self): self.store = {}", "as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class FabricatedRing(Ring): \"\"\" When", "def __init__(self): self.store = {} def get(self, key): return self.store.get(key)", "not isinstance(expect_sleep, (list, tuple)): expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list", "max_more_nodes self._part_shift = 32 - part_power # 9 total nodes", ">>> thing.method().attribute True \"\"\" def __getattribute__(self, *args, **kwargs): return self", "= _store_in('timing_since') transfer_rate = _store_in('transfer_rate') set_statsd_prefix = _store_in('set_statsd_prefix') def get_increments(self):", "next(timestamps_iter) if status <= 0: raise HTTPException() if body_iter is", "instance which can lead to some bled state. To help", "[] for x in range(self.replicas): ip = '10.0.0.%s' % x", "to act like # our backend services and return certain", "on the path - otherwise we exercise the real ring", "six.moves.cPickle as pickle from gzip import GzipFile import mock as", "'ip': ip, 'port': port, 'method': method, 'path': path, 'headers': headers,", "with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10, ec_nparity=4,", "syslog priority LOG_NOTICE. The python logging lvl is set to", "{'critical': [], 'error': [], 'info': [], 'warning': [], 'debug': [],", "set_replicas(self, replicas): self.replicas = replicas self._devs = [] for x", "captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs) def _clear(self): self.log_dict =", "'Content-Type' in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter)", "a part_power when you setup your FakeRing the parts you", "headers=None, expect_headers=None, connection_id=None, give_send=None): if not isinstance(status, FakeStatus): status =", "if isinstance(thing, type): return self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self,", "= fake_ring_args or [None] * len(self.policies) def _setup_rings(self): \"\"\" Our", "headers.update(self.headers) return headers.items() def get_slow(self): if 'slow' in kwargs and", "fresh rings in setUp - or if they'd prefer to", "= [status] else: self.expect_status = [100, 100] # setup sleep", "True def incr(self, key, time=0): self.store[key] = self.store.setdefault(key, 0) +", "def _patch_class(self, cls): \"\"\" Creating a new class that inherits", "module = __import__(imports[0], fromlist=imports[1:]) for modname in imports[1:]: module =", "self.reason = 'Fake' self.host = '1.2.3.4' self.port = '1234' self.sent", "eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc') if exc: if isinstance(exc,", "can fabricate one to meet your tests needs. \"\"\" def", "float, time to eventlet sleep during expect, can be a", "class DebugLogAdapter(utils.LogAdapter): def _send_to_logger(name): def stub_fn(self, *args, **kwargs): return getattr(self.logger,", "of %r found in %r)' % ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, ))", "Convenience function for syslog priority LOG_NOTICE. The python logging lvl", "def __init__(self, replicas=6, devices=8, nodes=4, port=6000, part_power=4): self.devices = devices", "send(self, amt=None): if self.give_send: self.give_send(self.connection_id, amt) am_slow, value = self.get_slow()", "raise IOError(errno.ENODATA, \"Fake IOError\") return data import xattr xattr.setxattr =", "retries=5): yield True def delete(self, key): try: del self.store[key] except", "module who imports time directly by monkey patching it's imported", "this is a public interface def get_lines_for_level(self, level): if level", "expect_status return response def getheaders(self): etag = self.etag if not", "am_slow, value = self.get_slow() if am_slow: if self.received < 4:", "little bit easier to extend than the current slow kwarg", "= 'endcap' EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name", "own personal playground - which can be a problem in", "not self.timestamp: # when timestamp is None, HeaderKeyDict raises KeyError", "result and return 1. \"\"\" self._base_port = base_port self.max_more_nodes =", "FakeRing just won't do - you can fabricate one to", "attr, value in returns: setattr(module, attr, value) for module, attr", "key, value, time=0): self.store[key] = value return True def incr(self,", "msg, *args, **kwargs) def _clear(self): self.log_dict = defaultdict(list) self.lines_dict =", "self.log_dict['increment']] def get_increment_counts(self): counts = {} for metric in self.get_increments():", "sleep during expect, can be a iter of floats :param", "= '' lc = '' crlfs = 0 while crlfs", "self.fake_ring_args): if fake_ring_arg is not None: policy.object_ring = FakeRing(**fake_ring_arg) def", "unable to format log message %r %% %r' % (", "'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp,", ":param expect_sleep: float, time to eventlet sleep during expect, can", "self.expect_sleep_list.pop(0) if expect_sleep is not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0)", "in self.lines_dict: raise KeyError( \"Invalid log level '%s'; valid levels", "FakeStatus): status = FakeStatus(status) self._status = status self.reason = 'Fake'", "record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record): self._handle(record) def flush(self):", "'region': x % 2, 'id': x, }) @property def replica_count(self):", "tests needs. \"\"\" def __init__(self, replicas=6, devices=8, nodes=4, port=6000, part_power=4):", "decorators done - but it seems to cause infinite recursion", "with custom FakeRing's they can pass in their own fake_ring_args", "sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg, *args, **kwargs) def _clear(self):", "1 eventlet.sleep(value) def getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default) def", "self._devs = [{ 'region': 1, 'zone': 1, 'weight': 1.0, 'id':", "\"\"\" def __init__(self, status, expect_sleep=None, response_sleep=None): \"\"\" :param status: the", "self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self, cls): \"\"\" Creating a", "EC_TYPE_PREFERENCE = [ 'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE:", "info. SysLogHandler is monkey patched to map this log lvl", "error statuses # when they call getexpect, so our FakeConn", "argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs)", "the module with an instance of this class \"\"\" _orig_time", "cargs = [msg] if any(args): cargs.extend(args) captured = dict(kwargs) if", "import (StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools import six.moves.cPickle as pickle", "if legacy_only: default_policies = [ StoragePolicy(0, name='legacy', is_default=True), ] default_ring_args", "= data def _getxattr(fd, k): inode = _get_inode(fd) data =", "True >>> thing.attribute True >>> thing.method() True >>> thing.attribute.method() True", "etag self.body = body self.headers = headers or {} self.expect_headers", "or a tuple of ([expect_status, ...], response_status) :param expect_sleep: float,", "eventlet.wsgi will # respond with that status line immediately instead", "class. \"\"\" orig_setUp = cls.setUp orig_tearDown = cls.tearDown def setUp(cls_self):", "dev2_updates = devs or ({}, {}) dev1.update(dev1_updates) dev2.update(dev2_updates) replica2part2dev_id =", "fake_ring_args = fake_ring_args or default_ring_args decorator = PatchPolicies(default_policies, fake_ring_args=fake_ring_args) if", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= self.get_slow() if am_slow: if self.sent < 4: self.sent +=", "= 6 self.part_power = part_power self._part_shift = 32 - self.part_power", "monkey patching it's imported reference to the module with an", "__init__(self, *args, **kwargs): FakeLogger.__init__(self, *args, **kwargs) self.formatter = logging.Formatter( \"%(server)s", "100 # Continue, even if the client sent the Expect", "behavior with custom FakeRing's they can pass in their own", "logging.handlers from six.moves.http_client import HTTPException from swift.common import storage_policy from", "of MockTrue evaluate like True Any attr accessed on an", "setFormatter(self, obj): self.formatter = obj def close(self): self._clear() def set_name(self,", "get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object): \"\"\" Instances of MockTrue evaluate", "This will work with our fake_http_connect, if you hand in", "def __enter__(self): self._orig_POLICIES = storage_policy._POLICIES storage_policy._POLICIES = self.policies def __exit__(self,", "state. To help tests get better isolation without having to", "*args, **kwargs): return self def __call__(self, *args, **kwargs): return self", "self.fake_ring_args = fake_ring_args or [None] * len(self.policies) def _setup_rings(self): \"\"\"", "list(status[:-1]) self.status = status[-1] self.explicit_expect_list = True else: self.expect_status, self.status", "eclib_name def patch_policies(thing_or_policies=None, legacy_only=False, with_ec_default=False, fake_ring_args=None): if isinstance(thing_or_policies, ( Iterable,", "* len(code_iter)) if not isinstance(x, (tuple, list)): x = [x]", "import logging import errno from six.moves import range import sys", "not data: raise IOError(errno.ENODATA, \"Fake IOError\") return data import xattr", "f.write(str(content)) try: yield tempdir finally: rmtree(tempdir) def with_tempdir(f): \"\"\" Decorator", "time.time def __getattribute__(self, name): if name == 'time': return UnmockTimeModule._orig_time", "don't touch _handlers self._name = name def acquire(self): pass def", "% ( EC_TYPE_PREFERENCE, VALID_EC_TYPES, )) DEFAULT_TEST_EC_TYPE = eclib_name def patch_policies(thing_or_policies=None,", "to the expect and response stages of the connection. \"\"\"", "else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] * len(code_iter)) x = kwargs.get('missing_container',", "= value return True def incr(self, key, time=0): self.store[key] =", "os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE", "test a tempdir as argument to test method. \"\"\" @functools.wraps(f)", "def capture_requests(ip, port, method, path, headers, qs, ssl): req =", "c == '\\n': crlfs += 1 lc = c return", "def stub_fn(self, *args, **kwargs): return getattr(self.logger, name)(*args, **kwargs) return stub_fn", "* len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None)", "# our backend services and return certain types of responses", "= _store_in('decrement') timing = _store_in('timing') timing_since = _store_in('timing_since') transfer_rate =", "= body self.headers = headers or {} self.expect_headers = expect_headers", "TestCase class where the FakeRing objects are scoped in the", "in a another module who imports time directly by monkey", "no matter if # this is set higher, or R^2", "part_power=0, base_port=1000): \"\"\" :param part_power: make part calculation based on", "policies else: self.policies = storage_policy.StoragePolicyCollection(policies) self.fake_ring_args = fake_ring_args or [None]", "objects are scoped in the call to the patch_policies wrapper", "except TypeError: print('WARNING: unable to format log message %r %%", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or #", "\\ copy.deepcopy(logging.handlers.SysLogHandler.priority_map) logging.handlers.SysLogHandler = FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler()", "from decorated class is the more common way I've seen", "len(code_iter) container_ts_iter = iter(x) code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter)", "value, time=0): self.store[key] = value return True def incr(self, key,", "os.makedirs(subdir) with open(new_path, 'w') as f: f.write(str(content)) try: yield tempdir", "we can ensure each test method gets a clean ring", "so our FakeConn tries to act like # our backend", "recursion when super is called from inside methods in the", "self.facility = kwargs['facility'] self.statsd_client = None self.thread_locals = None self.parent", "isinstance(expect_status, (Exception, eventlet.Timeout)): raise expect_status return expect_status class SlowBody(object): \"\"\"", "= fd.fileno() except AttributeError: return os.stat(fd).st_ino return os.fstat(fd).st_ino def _setxattr(fd,", "return swob.HeaderKeyDict(self.getheaders()).get(name, default) def close(self): pass timestamps_iter = iter(kwargs.get('timestamps') or", "can add some eventlet sleep to the expect and response", "Version 2.0 (the \"License\"); # you may not use this", "new FakeRing instances so we can ensure each test method", "None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try: if next(container_ts_iter) is", "the files c = len(files) contents = (list(contents) + ['']", "isinstance(kwargs['exc_info'], tuple): captured['exc_info'] = sys.exc_info() self.log_dict[store_name].append((tuple(cargs), captured)) super(FakeLogger, self)._log(level, msg,", "'expect status: %r' % (self.expect_status,)) if isinstance(self.status, (Exception, eventlet.Timeout)): raise", "def all_log_lines(self): return dict((level, msgs) for level, msgs in self.lines_dict.items()", "False >>> thing != False # True != False True", "attr in dir(original_syslog_handler): if attr.startswith('LOG'): setattr(FakeLogger, attr, copy.copy(getattr(logging.handlers.SysLogHandler, attr))) FakeLogger.priority_map", "lc != '\\n': crlfs = 0 if lc == '\\r'", "def __len__(self): return len(self.body) def __radd__(self, other): self.slowdown() return other", ">>> thing == False # True == False False >>>", "** self.part_power for i in range(self.replicas) ] dev_ids = itertools.cycle(range(self.devices))", "r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class FakeMemcache(object): def __init__(self):", "if not os.path.basename(sys.argv[0]).startswith('swift'): # never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX =", "self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness) def __getitem__(self, s): return", "self._orig_POLICIES = storage_policy._POLICIES try: storage_policy._POLICIES = self.policies self._setup_rings() return f(*args,", "act like # our backend services and return certain types", "self.expect_sleep_list = list(expect_sleep) while len(self.expect_sleep_list) < len(self.expect_status): self.expect_sleep_list.append(None) self.response_sleep =", "32 - part_power # 9 total nodes (6 more past", "= swob.HeaderKeyDict({ 'content-length': len(self.body), 'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp,", "['1'] * len(code_iter)) etag_iter = iter(kwargs.get('etags') or [None] * len(code_iter))", "\"\"\" def __init__(self, replicas=6, devices=8, nodes=4, port=6000, part_power=4): self.devices =", "[], 'debug': [], 'notice': []} clear = _clear # this", "by applicable law or agreed to in writing, software #", "if not self.expect_status: # when a swift backend service returns", "_setup_rings(self): \"\"\" Our tests tend to use the policies rings", "fabricate one to meet your tests needs. \"\"\" def __init__(self,", "True \"\"\" def __getattribute__(self, *args, **kwargs): return self def __call__(self,", "lvl in sorted(self.lines_dict)))) return self.lines_dict[level] def all_log_lines(self): return dict((level, msgs)", "swift.common.utils import Timestamp, NOTICE from test import get_config from swift.common", "def __radd__(self, other): self.slowdown() return other + self.body def fake_http_connect(*code_iter,", "rings like their own personal playground - which can be", "'id': x, }) @property def replica_count(self): return self.replicas def _get_part_nodes(self,", "None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception, eventlet.Timeout)): raise", "fill the files c = len(files) contents = (list(contents) +", "real backend server would do. if self.status in (507, 412,", "FakeRing objects are scoped in the call to the patch_policies", "counts[metric] += 1 return counts def setFormatter(self, obj): self.formatter =", "name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args = [{}, {}] fake_ring_args", "__init__(self, body, slowness): self.body = body self.slowness = slowness def", "should be a little bit easier to extend than the", "return self._patch_class(thing) else: return self._patch_method(thing) def _patch_class(self, cls): \"\"\" Creating", "soft_lock(self, key, timeout=0, retries=5): yield True def delete(self, key): try:", "pass def emit(self, record): pass def _handle(self, record): try: line", "ring... \"\"\" dev1 = {'id': 0, 'zone': 0, 'device': 'sda1',", "def _reload(self): self._rtime = time.time() def set_replicas(self, replicas): self.replicas =", "OR CONDITIONS OF ANY KIND, either express or # implied.", ">>> thing True >>> thing == True # True ==", "in args[6]: kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter) if", "** self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids) class", ":param part_power: make part calculation based on the path If", "def _getxattr(fd, k): inode = _get_inode(fd) data = xattr_data.get(inode, {}).get(k)", "} def notice(self, msg, *args, **kwargs): \"\"\" Convenience function for", "return [call[0][0] for call in self.log_dict['increment']] def get_increment_counts(self): counts =", "Foundation # # Licensed under the Apache License, Version 2.0", "returns: setattr(module, attr, value) for module, attr in deletes: delattr(module,", "closing from collections import defaultdict, Iterable import itertools from numbers", "_clear(self): self.log_dict = defaultdict(list) self.lines_dict = {'critical': [], 'error': [],", "= _setxattr xattr.getxattr = _getxattr @contextmanager def temptree(files, contents=''): #", "IOError(errno.ENODATA, \"Fake IOError\") return data import xattr xattr.setxattr = _setxattr", "ip, 'replication_ip': ip, 'port': port, 'replication_port': port, 'device': 'sd' +", "self._setup_rings() return f(*args, **kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES return mywrapper", "self._name = name def acquire(self): pass def release(self): pass def", "try: if next(container_ts_iter) is False: headers['x-container-timestamp'] = '1' except StopIteration:", "self.body = self.body[amt:] return rv def send(self, amt=None): if self.give_send:", "SlowBody(object): \"\"\" This will work with our fake_http_connect, if you", "deletes.append((module, attr)) setattr(module, attr, value) try: yield True finally: for", "hand in one of these instead of a status int", "pass def createLock(self): pass def emit(self, record): pass def _handle(self,", "new=fake_conn): yield fake_conn left_over_status = list(fake_conn.code_iter) if left_over_status: raise AssertionError('left", "x % 2, 'id': x} def write_fake_ring(path, *devs): \"\"\" Pretty", "c == '\\r' and lc != '\\n': crlfs = 0", "timestamp = next(timestamps_iter) if status <= 0: raise HTTPException() if", "'zone': x % 3, 'region': x % 2, 'id': x,", "x, 'device': 'sda', 'zone': x % 3, 'region': x %", "in the call to the patch_policies wrapper outside of the", "a little bit easier to extend than the current slow", "= self._orig_POLICIES cls.setUp = setUp cls.tearDown = tearDown return cls", "fake_http_connect, if you hand in these instead of strings it", "'liberasurecode_rs_vand', 'jerasure_rs_vand', ] for eclib_name in EC_TYPE_PREFERENCE: if eclib_name in", "__init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else:", "isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status = status[-1] self.explicit_expect_list =", "= None store_in = { logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO:", "decrement = _send_to_logger('decrement') timing = _send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate", "x = kwargs.get('missing_container', [False] * len(code_iter)) if not isinstance(x, (tuple,", "the initial 3) is the cap, no matter if #", "data: raise IOError(errno.ENODATA, \"Fake IOError\") return data import xattr xattr.setxattr", "== False # True == False False >>> thing !=", "from __future__ import print_function import os import copy import logging", "headers or {} self.expect_headers = expect_headers or {} self.timestamp =", "kwargs.get('body', None) body_iter = kwargs.get('body_iter', None) if body_iter: body_iter =", "applicable law or agreed to in writing, software # distributed", "i, 'device': 'sda%d' % i, 'ip': '10.0.0.%d' % (i %", "self.sent += 1 eventlet.sleep(value) return ' ' rv = self.body[:amt]", "self.replicas = 6 self.part_power = part_power self._part_shift = 32 -", "incr(self, key, time=0): self.store[key] = self.store.setdefault(key, 0) + 1 return", "not os.path.exists(subdir): os.makedirs(subdir) with open(new_path, 'w') as f: f.write(str(content)) try:", "range(2 ** self.part_power): for r in range(self.replicas): self._replica2part2dev_id[r][p] = next(dev_ids)", "self._rtime = time.time() def set_replicas(self, replicas): self.replicas = replicas self._devs", "+= 1 eventlet.sleep(value) def getheader(self, name, default=None): return swob.HeaderKeyDict(self.getheaders()).get(name, default)", "not in self.lines_dict: raise KeyError( \"Invalid log level '%s'; valid", "left_over_status: raise AssertionError('left over status %r' % left_over_status) def make_timestamp_iter():", "StopIteration: pass am_slow, value = self.get_slow() if am_slow: headers['content-length'] =", "'wb')) as f: pickle.dump(RingData(replica2part2dev_id, devs, part_shift), f) class FabricatedRing(Ring): \"\"\"", "self.part_power = part_power self._part_shift = 32 - self.part_power self._reload() def", "subclass) for the body inside of FakeConn if we wanted", "'path': path, 'headers': headers, 'qs': qs, 'ssl': ssl, } requests.append(req)", "VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable to find suitable PyECLib", "def emit(self, record): pass class UnmockTimeModule(object): \"\"\" Even if a", "_log(self, level, msg, *args, **kwargs): store_name = self.store_in[level] cargs =", "<= 0: raise HTTPException() if body_iter is None: body =", "storage_policy._POLICIES = self.policies self._setup_rings() cls_self._policies_patched = True orig_setUp(cls_self) def tearDown(cls_self):", "'' crlfs = 0 while crlfs < 2: c =", "valid levels are %s\" % (level, ', '.join(\"'%s'\" % lvl", "calculation based on the path If you set a part_power", "= { logging.ERROR: 'error', logging.WARNING: 'warning', logging.INFO: 'info', logging.DEBUG: 'debug',", "FakeConn(status, etag, body=body, timestamp=timestamp, headers=headers, expect_headers=expect_headers, connection_id=i, give_send=kwargs.get('give_send')) connect.code_iter =", "never patch HASH_PATH_SUFFIX AGAIN! utils.HASH_PATH_SUFFIX = 'endcap' EC_TYPE_PREFERENCE = [", "= base_port self.max_more_nodes = max_more_nodes self._part_shift = 32 - part_power", "lc = '' crlfs = 0 while crlfs < 2:", "collections import defaultdict, Iterable import itertools from numbers import Number", "if exc: if isinstance(exc, (Exception, eventlet.Timeout)): raise exc raise Exception('test')", "self.store.setdefault(key, 0) + 1 return self.store[key] @contextmanager def soft_lock(self, key,", "return response def getheaders(self): etag = self.etag if not etag:", "# You may obtain a copy of the License at", "ckwargs['connection_id'] = i give_conn_fn(*args, **ckwargs) etag = next(etag_iter) headers =", "should be easy to detect if you have one of", "*devs): \"\"\" Pretty much just a two node, two replica,", "NOTICE: 'notice', } def notice(self, msg, *args, **kwargs): \"\"\" Convenience", "any(args): cargs.extend(args) captured = dict(kwargs) if 'exc_info' in kwargs and", "hasattr(module, attr): returns.append((module, attr, getattr(module, attr))) else: deletes.append((module, attr)) setattr(module,", "getheaders(self): etag = self.etag if not etag: if isinstance(self.body, str):", "%r' % left_over_status) def make_timestamp_iter(): return iter(Timestamp(t) for t in", "out the StatsD logging methods: update_stats = _store_in('update_stats') increment =", "% self.nodes), 'replication_ip': '10.0.0.%d' % (i % self.nodes), 'port': self.port,", "def __getitem__(self, s): return SlowBody(self.body[s], self.slowness) def __len__(self): return len(self.body)", "'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': 6000} dev2 =", "zip(files, contents): if os.path.isabs(path): path = '.' + path new_path", "if isinstance(status, tuple): self.expect_status = list(status[:-1]) self.status = status[-1] self.explicit_expect_list", "eventlet.sleep(self.response_sleep) if self.expect_status and self.explicit_expect_list: raise Exception('Test did not consume", "or {} self.expect_headers = expect_headers or {} self.timestamp = timestamp", "!= False # True != False True >>> thing.attribute True", "wrapped thing instead of the decorator return decorator(thing_or_policies) class PatchPolicies(object):", "container_ts_iter = iter(x) code_iter = iter(code_iter) conn_id_and_code_iter = enumerate(code_iter) static_body", "It should be a little bit easier to extend than", "fake ' 'expect status: %r' % (self.expect_status,)) if isinstance(self.status, (Exception,", "import Ring, RingData from hashlib import md5 import logging.handlers from", "tuple)): expect_headers_iter = iter(kwargs['expect_headers']) else: expect_headers_iter = iter([kwargs.get('expect_headers', {})] *", "hashlib import md5 import logging.handlers from six.moves.http_client import HTTPException from", "is not None: eventlet.sleep(expect_sleep) expect_status = self.expect_status.pop(0) if isinstance(expect_status, (Exception,", "= {'id': 0, 'zone': 0, 'device': 'sdb1', 'ip': '127.0.0.1', 'port':", "the particular case of a patched TestCase class where the", "*args, **kwargs): self._rtime = time.time() * 2 if hasattr(self, '_replica2part2dev_id'):", "int tuple to the \"codes\" iter you can add some", "static_body = kwargs.get('body', None) body_iter = kwargs.get('body_iter', None) if body_iter:", "[ StoragePolicy(0, name='nulo', is_default=True), StoragePolicy(1, name='unu'), ] default_ring_args = [{},", "patched yet) \"\"\" def __init__(self, policies, fake_ring_args=None): if isinstance(policies, storage_policy.StoragePolicyCollection):", "**kwargs) return stub_fn # delegate to FakeLogger's mocks update_stats =", "expect and response stages of the connection. \"\"\" def __init__(self,", "tuple)): expect_sleep = [expect_sleep] * len(self.expect_status) self.expect_sleep_list = list(expect_sleep) while", "if kwargs.get('slow') and isinstance(kwargs['slow'], Number): return True, kwargs['slow'] return bool(kwargs.get('slow')),", "1, 'zone': 1, 'weight': 1.0, 'id': i, 'device': 'sda%d' %", "= [{'replicas': 14}, {}] else: default_policies = [ StoragePolicy(0, name='nulo',", "if am_slow: headers['content-length'] = '4' headers.update(self.headers) return headers.items() def get_slow(self):", "rv @contextmanager def tmpfile(content): with NamedTemporaryFile('w', delete=False) as f: file_name", "instead of a status int or status int tuple to", "x % 3, 'region': x % 2, 'id': x, })", "if argspec.keywords or 'connection_id' in argspec.args: ckwargs['connection_id'] = i give_conn_fn(*args,", "counts: counts[metric] = 0 counts[metric] += 1 return counts def", "= FakeLogger if utils.config_true_value( get_config('unit_test').get('fake_syslog', 'False')): fake_syslog_handler() class MockTrue(object): \"\"\"", "logger def __init__(self, *args, **kwargs): self._clear() self.name = 'swift.unit.fake_logger' self.level", "def _send_to_logger(name): def stub_fn(self, *args, **kwargs): return getattr(self.logger, name)(*args, **kwargs)", "logging.INFO: 'info', logging.DEBUG: 'debug', logging.CRITICAL: 'critical', NOTICE: 'notice', } def", "+ self.max_more_nodes)): yield {'ip': '10.0.0.%s' % x, 'replication_ip': '10.0.0.%s' %", "detect if you have one of these (or a subclass)", "'content-type': 'x-application/test', 'x-timestamp': self.timestamp, 'x-backend-timestamp': self.timestamp, 'last-modified': self.timestamp, 'x-object-meta-test': 'testing',", "@contextmanager def soft_lock(self, key, timeout=0, retries=5): yield True def delete(self,", "return getattr(self.logger, name)(*args, **kwargs) return stub_fn # delegate to FakeLogger's", "EC_TYPE_PREFERENCE: if eclib_name in VALID_EC_TYPES: break else: raise SystemExit('ERROR: unable", "isolation without having to think about it, here we're capturing", "# respond with that status line immediately instead of 100", "trixy bits with node_iter's eventlet.sleep() def getresponse(self): exc = kwargs.get('raise_exc')", "it seems to cause infinite recursion when super is called", "timestamp is None, HeaderKeyDict raises KeyError headers.pop('x-timestamp', None) try: if", "from gzip import GzipFile import mock as mocklib import inspect", "isinstance(x, (tuple, list)): x = [x] * len(code_iter) container_ts_iter =", "if hasattr(self, '_replica2part2dev_id'): return self._devs = [{ 'region': 1, 'zone':", "response status int, or a tuple of ([expect_status, ...], response_status)", "a iter of floats :param response_sleep: float, time to eventlet", "= 0 if lc == '\\r' and c == '\\n':", "\"License\"); # you may not use this file except in", "%r' % ( record.msg, record.args)) raise self.lines_dict[record.levelname.lower()].append(line) def handle(self, record):", "tend to use the policies rings like their own personal", "\"\"\" :param status: the response status int, or a tuple", "# setup sleep attributes if not isinstance(expect_sleep, (list, tuple)): expect_sleep", "they call getexpect, so our FakeConn tries to act like", "**kwargs): self._rtime = time.time() * 2 if hasattr(self, '_replica2part2dev_id'): return", "value = self.get_slow() if am_slow: if self.sent < 4: self.sent", "obj def close(self): self._clear() def set_name(self, name): # don't touch", "strings it will make reads take longer by the given", "slowness): self.body = body self.slowness = slowness def slowdown(self): eventlet.sleep(self.slowness)", "= _send_to_logger('timing') timing_since = _send_to_logger('timing_since') transfer_rate = _send_to_logger('transfer_rate') set_statsd_prefix =", "i in range(self.devices)] self._replica2part2dev_id = [ [None] * 2 **", "True == True True >>> thing == False # True", "swift backend service returns a status before reading # from", "patch_policies instead of setting the object_ring on the policy definitions.", "global wasn't patched yet) \"\"\" def __init__(self, policies, fake_ring_args=None): if", "True def readuntil2crlfs(fd): rv = '' lc = '' crlfs", "kwargs['give_content_type'](args[6]['Content-Type']) else: kwargs['give_content_type']('') i, status = next(conn_id_and_code_iter) if 'give_connect' in", "self def getexpect(self): expect_status = self._status.get_expect_status() headers = dict(self.expect_headers) if", "tearDown return cls def _patch_method(self, f): @functools.wraps(f) def mywrapper(*args, **kwargs):", "connect.code_iter = code_iter return connect @contextmanager def mocked_http_conn(*args, **kwargs): requests", "PatchPolicies(thing_or_policies, fake_ring_args=fake_ring_args) if legacy_only: default_policies = [ StoragePolicy(0, name='legacy', is_default=True),", "can always \"tweak\" these fresh rings in setUp - or", "if isinstance(policies, storage_policy.StoragePolicyCollection): self.policies = policies else: self.policies = storage_policy.StoragePolicyCollection(policies)", "self._patch_method(thing) def _patch_class(self, cls): \"\"\" Creating a new class that", "v): inode = _get_inode(fd) data = xattr_data.get(inode, {}) data[k] =", "= record.getMessage() except TypeError: print('WARNING: unable to format log message", "elif with_ec_default: default_policies = [ ECStoragePolicy(0, name='ec', is_default=True, ec_type=DEFAULT_TEST_EC_TYPE, ec_ndata=10,", "(StoragePolicy, ECStoragePolicy, VALID_EC_TYPES) import functools import six.moves.cPickle as pickle from", "is False: headers['x-container-timestamp'] = '1' except StopIteration: pass am_slow, value", "a another module who imports time directly by monkey patching", "defaultdict, Iterable import itertools from numbers import Number from tempfile", "expect_status class SlowBody(object): \"\"\" This will work with our fake_http_connect,", "pass class UnmockTimeModule(object): \"\"\" Even if a test mocks time.time", "**kwargs) finally: storage_policy._POLICIES = self._orig_POLICIES return mywrapper def __enter__(self): self._orig_POLICIES", "patch_policies wrapper outside of the TestCase instance which can lead", "or [None] * len(code_iter)) if isinstance(kwargs.get('headers'), (list, tuple)): headers_iter =", "'replication_ip': '10.0.0.%s' % x, 'port': self._base_port + x, 'replication_port': self._base_port", ">>> thing.attribute True >>> thing.method() True >>> thing.attribute.method() True >>>", "self.store[key] except Exception: pass return True def readuntil2crlfs(fd): rv =", "not mock.patch? In my case, when used as a decorator", "from inside methods in the decorated class. \"\"\" orig_setUp =", "matter if # this is set higher, or R^2 for", "x} def write_fake_ring(path, *devs): \"\"\" Pretty much just a two", "needs. \"\"\" def __init__(self, replicas=6, devices=8, nodes=4, port=6000, part_power=4): self.devices" ]
[ "weights. if hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict() for k, v", "def forward( self, src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ):", "under the MIT license found in the # LICENSE file", "def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) # We", "{} (prev: {})'.format( name, num_classes, prev_num_classes, inner_dim, prev_inner_dim ) )", "head_name not in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else: if head_name", "self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, ): super().__init__() self.dense =", "x['models'][0]) def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a classification", "prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes != prev_num_classes or inner_dim !=", "'WARNING: re-registering head \"{}\" with num_classes {} (prev: {}) '", "Handle new classification heads present in the state dict. keys_to_delete", "'classification_heads'): cur_state = self.classification_heads.state_dict() for k, v in cur_state.items(): if", "x, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, ) if", "num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a classification head.\"\"\" print(\"Registering classification head:", "{})'.format( name, num_classes, prev_num_classes, inner_dim, prev_inner_dim ) ) self.classification_heads[name] =", "getattr(args, 'no_scale_embedding', True) args.layernorm_embedding = getattr(args, 'layernorm_embedding', True) args.activation_fn =", "continue head_name = k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix +", "Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension", "LICENSE file in the root directory of this source tree.", "the source sequence' ) parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N', help='max", "+ k] = v class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification", "name): super().upgrade_state_dict_named(state_dict, name) prefix = name + '.' if name", "'--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to use for pooler layer' )", "args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.)", "prefix + 'classification_heads.' + k not in state_dict: print('Overwriting', prefix", "not in state_dict: print('Overwriting', prefix + 'classification_heads.' + k) state_dict[prefix", "(prev: {}) ' 'and inner_dim {} (prev: {})'.format( name, num_classes,", "'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder)", "bpe='gpt2', **kwargs, ): from fairseq import hub_utils x = hub_utils.from_pretrained(", "We follow BERT's random weight initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict()", "checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'], x['task'],", "not in current_head_names: print( 'WARNING: deleting classification head ({}) from", "help='activation function to use for pooler layer' ) @property def", ":] x = self.classification_heads[classification_head_name]( sentence_representation ) return x, extra @classmethod", "getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers =", "args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads',", "= nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024,", "current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else: if head_name not in current_head_names:", "BARTModel(TransformerModel): @classmethod def hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz',", "\"{}\" with num_classes {} (prev: {}) ' 'and inner_dim {}", "the MIT license found in the # LICENSE file in", "'--max-source-positions', default=1024, type=int, metavar='N', help='max number of tokens in the", "prefix = name + '.' if name != '' else", "self.register_classification_head(head_name, num_classes, inner_dim) else: if head_name not in current_head_names: print(", "extra @classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs,", "state dict. keys_to_delete = [] for k in state_dict.keys(): if", "+ '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False): if head_name not in", "inner_dim, num_classes, activation_fn, pooler_dropout, ): super().__init__() self.dense = nn.Linear(input_dim, inner_dim)", "+ '.' if name != '' else '' current_head_names =", "license found in the # LICENSE file in the root", "= self.dropout(x) x = self.dense(x) x = self.activation_fn(x) x =", "Comprehension \"\"\" import torch.nn as nn from fairseq import utils", "help='max number of tokens in the source sequence' ) parser.add_argument(", "= getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos", "prefix + 'classification_heads.' + k) state_dict[prefix + 'classification_heads.' + k]", "parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout probability in the masked_lm pooler", "if getattr(self.args, 'load_checkpoint_heads', False): if head_name not in current_head_names: self.register_classification_head(head_name,", "state dict # with their current weights. if hasattr(self, 'classification_heads'):", "Natural Language Generation, Translation, and Comprehension \"\"\" import torch.nn as", "elif ( num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features ):", "inner_dim != self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting classification head ({})", "self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes) def forward(self, features,", "tokens in the source sequence' ) parser.add_argument( '--max-target-positions', default=1024, type=int,", "+ 'classification_heads.' + k not in state_dict: print('Overwriting', prefix +", "= getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before", "hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict() for k, v in cur_state.items():", ") from fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params from", "0.) args.dropout = getattr(args, 'dropout', 0.1) args.max_target_positions = getattr(args, 'max_target_positions',", "state_dict: print('Overwriting', prefix + 'classification_heads.' + k) state_dict[prefix + 'classification_heads.'", "classification heads present in the state dict. keys_to_delete = []", "classification head ({}) from checkpoint ' 'with different dimensions than", "checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ): from fairseq import hub_utils x", "= getattr(args, 'decoder_learned_pos', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout", "for k in keys_to_delete: del state_dict[k] # Copy any newly-added", "model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'],", "getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before =", "if name in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features", "**kwargs, ) if classification_head_name is not None: sentence_representation = x[", "k not in state_dict: print('Overwriting', prefix + 'classification_heads.' + k)", "+ k) state_dict[prefix + 'classification_heads.' + k] = v class", "args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers',", "layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to use for", "x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs,", "decoder) # We follow BERT's random weight initialization self.apply(init_bert_params) self.classification_heads", "the state dict # with their current weights. if hasattr(self,", "the target sequence' ) parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout probability", "'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args,", "0.1) args.max_target_positions = getattr(args, 'max_target_positions', 1024) args.max_source_positions = getattr(args, 'max_source_positions',", "num_classes = state_dict[prefix + 'classification_heads.' + head_name + '.out_proj.weight'].size(0) inner_dim", "self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, ) if classification_head_name is not", "classification tasks.\"\"\" def __init__( self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout,", "'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh') args.pooler_dropout = getattr(args,", "not None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:,", "'decoder_layers', 12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args,", "False): if head_name not in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else:", "= getattr(args, 'dropout', 0.1) args.max_target_positions = getattr(args, 'max_target_positions', 1024) args.max_source_positions", "not None: features_only = True encoder_out = self.encoder( src_tokens, src_lengths=src_lengths,", "= x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:, -1, :] x", "if not k.startswith(prefix + 'classification_heads.'): continue head_name = k[len(prefix +", "= getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers", "'--pooler-dropout', type=float, metavar='D', help='dropout probability in the masked_lm pooler layers'", "self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes !=", "= self.activation_fn(x) x = self.dropout(x) x = self.out_proj(x) return x", "head: {0}\".format(name)) if name in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim", "prev_inner_dim: print( 'WARNING: re-registering head \"{}\" with num_classes {} (prev:", "inner_dim, prev_inner_dim ) ) self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or", "deleting classification head ({}) from checkpoint ' 'with different dimensions", "self.dense(x) x = self.activation_fn(x) x = self.dropout(x) x = self.out_proj(x)", "'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_attention_heads = getattr(args,", "Translation, and Comprehension \"\"\" import torch.nn as nn from fairseq", "if not hasattr(self, 'classification_heads') else \\ self.classification_heads.keys() # Handle new", "1024) args.max_source_positions = getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff',", "use for pooler layer' ) @property def supported_targets(self): return {'self'}", "args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh') args.pooler_dropout = getattr(args, 'pooler_dropout', 0.0)", "getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim =", ") if classification_head_name is not None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()),", "heads into the state dict # with their current weights.", "x = self.classification_heads[classification_head_name]( sentence_representation ) return x, extra @classmethod def", "present in the state dict. keys_to_delete = [] for k", "BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def", "'with different dimensions than current model: {}'.format(head_name, k) ) keys_to_delete.append(k)", "'classification_heads.' + head_name + '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False): if", "{0}\".format(name)) if name in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim =", "print('Overwriting', prefix + 'classification_heads.' + k) state_dict[prefix + 'classification_heads.' +", "encoder_out=encoder_out, features_only=features_only, **kwargs, ) if classification_head_name is not None: sentence_representation", "# We follow BERT's random weight initialization self.apply(init_bert_params) self.classification_heads =", "args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True)", "self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting classification", "+ 'classification_heads.' + head_name + '.out_proj.weight'].size(0) inner_dim = state_dict[prefix +", "name) prefix = name + '.' if name != ''", "getattr(args, 'layernorm_embedding', True) args.activation_fn = getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn =", "{}'.format(head_name, k) ) keys_to_delete.append(k) elif ( num_classes != self.classification_heads[head_name].out_proj.out_features or", "from fairseq import utils from fairseq.models import ( register_model, register_model_architecture,", "getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos =", "print( 'WARNING: deleting classification head ({}) from checkpoint ' 'with", "model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ): from fairseq import hub_utils", "'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args,", "self.classification_heads[name].dense.out_features if num_classes != prev_num_classes or inner_dim != prev_inner_dim: print(", "BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod def hub_models(cls): return { 'bart.large':", "def supported_targets(self): return {'self'} def forward( self, src_tokens, src_lengths, prev_output_tokens,", "print( 'WARNING: re-registering head \"{}\" with num_classes {} (prev: {})", "else '' current_head_names = [] if not hasattr(self, 'classification_heads') else", "keys_to_delete = [] for k in state_dict.keys(): if not k.startswith(prefix", "forward(self, features, **kwargs): x = features x = self.dropout(x) x", "True) args.layernorm_embedding = getattr(args, 'layernorm_embedding', True) args.activation_fn = getattr(args, 'activation_fn',", "getattr(args, 'decoder_layers', 12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before =", "getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout =", "inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim,", "in the root directory of this source tree. \"\"\" BART:", "args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)", "({}) from checkpoint ' 'not present in current model: {}'.format(head_name,", "@staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N',", "affiliates. # # This source code is licensed under the", "'share_all_embeddings', True) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args,", "parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to use for pooler layer'", "def hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def", "dict. keys_to_delete = [] for k in state_dict.keys(): if not", "dimensions than current model: {}'.format(head_name, k) ) keys_to_delete.append(k) for k", "encoder, decoder): super().__init__(args, encoder, decoder) # We follow BERT's random", "if num_classes != prev_num_classes or inner_dim != prev_inner_dim: print( 'WARNING:", "= getattr(args, 'max_target_positions', 1024) args.max_source_positions = getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff", "register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a classification head.\"\"\" print(\"Registering", "pooler layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to use", "hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return", "+ 'classification_heads.' + k] = v class BARTClassificationHead(nn.Module): \"\"\"Head for", ") parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to use for pooler", "'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path = getattr(args,", "or inner_dim != prev_inner_dim: print( 'WARNING: re-registering head \"{}\" with", ") x, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, )", "different dimensions than current model: {}'.format(head_name, k) ) keys_to_delete.append(k) for", "0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args, 'share_all_embeddings',", "classification head.\"\"\" print(\"Registering classification head: {0}\".format(name)) if name in self.classification_heads:", "return {'self'} def forward( self, src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None,", "{}) ' 'and inner_dim {} (prev: {})'.format( name, num_classes, prev_num_classes,", ") keys_to_delete.append(k) elif ( num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim !=", "k, v in cur_state.items(): if prefix + 'classification_heads.' + k", ": ].view(x.size(0), -1, x.size(-1))[:, -1, :] x = self.classification_heads[classification_head_name]( sentence_representation", "= getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_attention_heads", "): from fairseq import hub_utils x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file,", "args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)", "name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a classification head.\"\"\" print(\"Registering classification", "inner_dim {} (prev: {})'.format( name, num_classes, prev_num_classes, inner_dim, prev_inner_dim )", "= getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout", "None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed',", "activation_fn, pooler_dropout, ): super().__init__() self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn =", "Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension \"\"\"", "import torch.nn as nn from fairseq import utils from fairseq.models", "the state dict. keys_to_delete = [] for k in state_dict.keys():", "target sequence' ) parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout probability in", "= k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix + 'classification_heads.' +", "if head_name not in current_head_names: print( 'WARNING: deleting classification head", "if hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict() for k, v in", "and its affiliates. # # This source code is licensed", "init_bert_params from .hub_interface import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod def", "BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and", "the masked_lm pooler layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function", "'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args, encoder, decoder):", "def forward(self, features, **kwargs): x = features x = self.dropout(x)", "getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed =", "tokens in the target sequence' ) parser.add_argument( '--pooler-dropout', type=float, metavar='D',", "state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix = name + '.' if", "'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args,", "classification_head_name is not None: features_only = True encoder_out = self.encoder(", "directory of this source tree. \"\"\" BART: Denoising Sequence-to-Sequence Pre-training", "args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args, 'encoder_layers', 12)", "Copyright (c) Facebook, Inc. and its affiliates. # # This", "+ head_name + '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False): if head_name", "getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim =", "args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0)", "from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ): from fairseq", ") self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn,", "+ k not in state_dict: print('Overwriting', prefix + 'classification_heads.' +", "as nn from fairseq import utils from fairseq.models import (", "keys_to_delete.append(k) elif ( num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features", "self.dropout(x) x = self.dense(x) x = self.activation_fn(x) x = self.dropout(x)", "= getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim", "args.max_source_positions = getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None)", "new classification heads present in the state dict. keys_to_delete =", "in cur_state.items(): if prefix + 'classification_heads.' + k not in", "= v class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification tasks.\"\"\" def", "TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface import BARTHubInterface @register_model('bart')", "+ '.out_proj.weight'].size(0) inner_dim = state_dict[prefix + 'classification_heads.' + head_name +", "def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix = name +", "inner_dim=None, **kwargs): \"\"\"Register a classification head.\"\"\" print(\"Registering classification head: {0}\".format(name))", "# LICENSE file in the root directory of this source", "!= self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting", "if head_name not in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else: if", "'.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False): if head_name not in current_head_names:", "classification heads into the state dict # with their current", "**kwargs ): if classification_head_name is not None: features_only = True", "16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos',", "'classification_heads') else \\ self.classification_heads.keys() # Handle new classification heads present", "nn from fairseq import utils from fairseq.models import ( register_model,", "x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:, -1, :] x =", "found in the # LICENSE file in the root directory", "state_dict[prefix + 'classification_heads.' + head_name + '.out_proj.weight'].size(0) inner_dim = state_dict[prefix", "= self.dense(x) x = self.activation_fn(x) x = self.dropout(x) x =", "'.' if name != '' else '' current_head_names = []", "pooler layer' ) @property def supported_targets(self): return {'self'} def forward(", "weight initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel,", "def bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args,", "prev_inner_dim ) ) self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim,", "-1, x.size(-1))[:, -1, :] x = self.classification_heads[classification_head_name]( sentence_representation ) return", "'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args,", ") return x, extra @classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt',", "inner_dim) else: if head_name not in current_head_names: print( 'WARNING: deleting", "model: {}'.format(head_name, k) ) keys_to_delete.append(k) elif ( num_classes != self.classification_heads[head_name].out_proj.out_features", "k) ) keys_to_delete.append(k) elif ( num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim", "their current weights. if hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict() for", "return x, extra @classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.',", "self.activation_fn(x) x = self.dropout(x) x = self.out_proj(x) return x @register_model_architecture('bart',", "args.max_target_positions = getattr(args, 'max_target_positions', 1024) args.max_source_positions = getattr(args, 'max_source_positions', 1024)", "'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix + 'classification_heads.' + head_name + '.out_proj.weight'].size(0)", "pooler_dropout, ): super().__init__() self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn)", "source sequence' ) parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N', help='max number", "features_only=False, classification_head_name=None, **kwargs ): if classification_head_name is not None: features_only", "{} (prev: {}) ' 'and inner_dim {} (prev: {})'.format( name,", "num_classes, prev_num_classes, inner_dim, prev_inner_dim ) ) self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim,", "args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim)", "state_dict[k] # Copy any newly-added classification heads into the state", "if classification_head_name is not None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), :", "follow BERT's random weight initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod", "for k, v in cur_state.items(): if prefix + 'classification_heads.' +", "): print( 'WARNING: deleting classification head ({}) from checkpoint '", "state_dict[prefix + 'classification_heads.' + head_name + '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads',", "= getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path", "super().__init__(args, encoder, decoder) # We follow BERT's random weight initialization", "4*1024) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads',", "x = self.out_proj(x) return x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path", "def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a classification head.\"\"\"", "in the state dict. keys_to_delete = [] for k in", "getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads =", "'layernorm_embedding', True) args.activation_fn = getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args,", "def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N', help='max", "class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification tasks.\"\"\" def __init__( self,", "register_model, register_model_architecture, ) from fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder import", "(c) Facebook, Inc. and its affiliates. # # This source", "self.out_proj = nn.Linear(inner_dim, num_classes) def forward(self, features, **kwargs): x =", "classification head: {0}\".format(name)) if name in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features", "type=int, metavar='N', help='max number of tokens in the target sequence'", "12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before',", "getattr(args, 'decoder_learned_pos', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout =", "'' else '' current_head_names = [] if not hasattr(self, 'classification_heads')", "<reponame>samsontmr/fairseq<gh_stars>100-1000 # Copyright (c) Facebook, Inc. and its affiliates. #", "num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name)", "getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_attention_heads =", "'WARNING: deleting classification head ({}) from checkpoint ' 'with different", "any newly-added classification heads into the state dict # with", "+ 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix + 'classification_heads.' + head_name +", "num_classes {} (prev: {}) ' 'and inner_dim {} (prev: {})'.format(", ".hub_interface import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod def hub_models(cls): return", "= getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.decoder_output_dim", "type=float, metavar='D', help='dropout probability in the masked_lm pooler layers' )", ") def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix = name", "a classification head.\"\"\" print(\"Registering classification head: {0}\".format(name)) if name in", "].view(x.size(0), -1, x.size(-1))[:, -1, :] x = self.classification_heads[classification_head_name]( sentence_representation )", ") @property def supported_targets(self): return {'self'} def forward( self, src_tokens,", "from fairseq import hub_utils x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path,", "head_name + '.out_proj.weight'].size(0) inner_dim = state_dict[prefix + 'classification_heads.' + head_name", "args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim)", "fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel):", "'classification_heads.'): continue head_name = k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix", "'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads = getattr(args,", "'and inner_dim {} (prev: {})'.format( name, num_classes, prev_num_classes, inner_dim, prev_inner_dim", "= self.classification_heads[name].dense.out_features if num_classes != prev_num_classes or inner_dim != prev_inner_dim:", "( register_model, register_model_architecture, ) from fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder", "args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding', True)", "import TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface import BARTHubInterface", "model: {}'.format(head_name, k) ) keys_to_delete.append(k) for k in keys_to_delete: del", "This source code is licensed under the MIT license found", "x = self.dense(x) x = self.activation_fn(x) x = self.dropout(x) x", "is not None: features_only = True encoder_out = self.encoder( src_tokens,", "from checkpoint ' 'not present in current model: {}'.format(head_name, k)", "super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N', help='max number of", "v in cur_state.items(): if prefix + 'classification_heads.' + k not", "getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.decoder_output_dim =", "del state_dict[k] # Copy any newly-added classification heads into the", "prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes != prev_num_classes", ") parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N', help='max number of tokens", "None: features_only = True encoder_out = self.encoder( src_tokens, src_lengths=src_lengths, **kwargs,", "= state_dict[prefix + 'classification_heads.' + head_name + '.dense.weight'].size(0) if getattr(self.args,", "args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)", "into the state dict # with their current weights. if", "self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout)", "self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict,", "cur_state.items(): if prefix + 'classification_heads.' + k not in state_dict:", "k) ) keys_to_delete.append(k) for k in keys_to_delete: del state_dict[k] #", "k in state_dict.keys(): if not k.startswith(prefix + 'classification_heads.'): continue head_name", "' 'not present in current model: {}'.format(head_name, k) ) keys_to_delete.append(k)", "state_dict[prefix + 'classification_heads.' + k] = v class BARTClassificationHead(nn.Module): \"\"\"Head", "licensed under the MIT license found in the # LICENSE", "class BARTModel(TransformerModel): @classmethod def hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli':", "features_only=features_only, **kwargs, ) if classification_head_name is not None: sentence_representation =", "12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before',", "with their current weights. if hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict()", "= getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding", "in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes", "# with their current weights. if hasattr(self, 'classification_heads'): cur_state =", "in current model: {}'.format(head_name, k) ) keys_to_delete.append(k) elif ( num_classes", "'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args,", "0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout',", "MIT license found in the # LICENSE file in the", "v class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification tasks.\"\"\" def __init__(", "encoder_out = self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, ) x, extra =", "BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register", "= getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim", "'' current_head_names = [] if not hasattr(self, 'classification_heads') else \\", "'classification_heads.' + k not in state_dict: print('Overwriting', prefix + 'classification_heads.'", "= utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes) def", "args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True)", "True) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout',", "'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args, encoder, decoder): super().__init__(args, encoder,", "sequence' ) parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout probability in the", "prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ): if classification_head_name is not None:", "self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix =", "keys_to_delete.append(k) for k in keys_to_delete: del state_dict[k] # Copy any", "this source tree. \"\"\" BART: Denoising Sequence-to-Sequence Pre-training for Natural", "} def __init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) #", "fairseq import hub_utils x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(),", "getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim =", "'dropout', 0.1) args.max_target_positions = getattr(args, 'max_target_positions', 1024) args.max_source_positions = getattr(args,", "import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod def hub_models(cls): return {", "# Handle new classification heads present in the state dict.", "= self.dropout(x) x = self.out_proj(x) return x @register_model_architecture('bart', 'bart_large') def", "[] for k in state_dict.keys(): if not k.startswith(prefix + 'classification_heads.'):", "num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features ): print( 'WARNING:", "import init_bert_params from .hub_interface import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod", "masked_lm pooler layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation function to", "for pooler layer' ) @property def supported_targets(self): return {'self'} def", "prev_num_classes or inner_dim != prev_inner_dim: print( 'WARNING: re-registering head \"{}\"", "self.classification_heads.keys() # Handle new classification heads present in the state", "'WARNING: deleting classification head ({}) from checkpoint ' 'not present", "= getattr(args, 'layernorm_embedding', True) args.activation_fn = getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn", "'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True) args.attention_dropout = getattr(args,", "'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args,", "classification_head_name=None, **kwargs ): if classification_head_name is not None: features_only =", "in the # LICENSE file in the root directory of", "@property def supported_targets(self): return {'self'} def forward( self, src_tokens, src_lengths,", "from fairseq.models import ( register_model, register_model_architecture, ) from fairseq.models.transformer import", "data_name_or_path='.', bpe='gpt2', **kwargs, ): from fairseq import hub_utils x =", "name in self.classification_heads: prev_num_classes = self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if", "features x = self.dropout(x) x = self.dense(x) x = self.activation_fn(x)", "sequence' ) parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N', help='max number of", "None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim',", "or inner_dim != self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting classification head", "args, encoder, decoder): super().__init__(args, encoder, decoder) # We follow BERT's", "add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N', help='max number", "classification_head_name is not None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0),", "head_name = k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix + 'classification_heads.'", "**kwargs): \"\"\"Register a classification head.\"\"\" print(\"Registering classification head: {0}\".format(name)) if", "forward( self, src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ): if", "args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding',", "x = self.activation_fn(x) x = self.dropout(x) x = self.out_proj(x) return", "{'self'} def forward( self, src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs", "return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args,", "'decoder_learned_pos', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args,", "@classmethod def hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', }", "getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.max_target_positions =", "x = features x = self.dropout(x) x = self.dense(x) x", "number of tokens in the target sequence' ) parser.add_argument( '--pooler-dropout',", "1024) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout',", "bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self,", "torch.nn as nn from fairseq import utils from fairseq.models import", "is not None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1,", "None: sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:, -1,", "' 'and inner_dim {} (prev: {})'.format( name, num_classes, prev_num_classes, inner_dim,", "return x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path',", "utils from fairseq.models import ( register_model, register_model_architecture, ) from fairseq.models.transformer", "in the masked_lm pooler layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(), help='activation", "x.size(-1))[:, -1, :] x = self.classification_heads[classification_head_name]( sentence_representation ) return x,", "name != '' else '' current_head_names = [] if not", "Generation, Translation, and Comprehension \"\"\" import torch.nn as nn from", "= [] for k in state_dict.keys(): if not k.startswith(prefix +", "decoder): super().__init__(args, encoder, decoder) # We follow BERT's random weight", "self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument(", "getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout =", "@classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ):", "num_classes, inner_dim) else: if head_name not in current_head_names: print( 'WARNING:", "hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self,", "= self.out_proj(x) return x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path =", "bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim',", "from .hub_interface import BARTHubInterface @register_model('bart') class BARTModel(TransformerModel): @classmethod def hub_models(cls):", "!= '' else '' current_head_names = [] if not hasattr(self,", "= self.classification_heads.state_dict() for k, v in cur_state.items(): if prefix +", "Pre-training for Natural Language Generation, Translation, and Comprehension \"\"\" import", "head \"{}\" with num_classes {} (prev: {}) ' 'and inner_dim", "'classification_heads.' + head_name + '.out_proj.weight'].size(0) inner_dim = state_dict[prefix + 'classification_heads.'", "hasattr(self, 'classification_heads') else \\ self.classification_heads.keys() # Handle new classification heads", "(prev: {})'.format( name, num_classes, prev_num_classes, inner_dim, prev_inner_dim ) ) self.classification_heads[name]", "= getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos", "args.layernorm_embedding = getattr(args, 'layernorm_embedding', True) args.activation_fn = getattr(args, 'activation_fn', 'gelu')", "nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int,", "k.startswith(prefix + 'classification_heads.'): continue head_name = k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes", "__init__(self, args, encoder, decoder): super().__init__(args, encoder, decoder) # We follow", "if classification_head_name is not None: features_only = True encoder_out =", "[] if not hasattr(self, 'classification_heads') else \\ self.classification_heads.keys() # Handle", "encoder, decoder) # We follow BERT's random weight initialization self.apply(init_bert_params)", "newly-added classification heads into the state dict # with their", "register_model_architecture, ) from fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params", "**kwargs, ) x, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs,", "of tokens in the source sequence' ) parser.add_argument( '--max-target-positions', default=1024,", "'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args,", "cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ): from fairseq import", "self.out_proj(x) return x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path = getattr(args,", "keys_to_delete: del state_dict[k] # Copy any newly-added classification heads into", "head ({}) from checkpoint ' 'not present in current model:", "\"\"\" import torch.nn as nn from fairseq import utils from", "if prefix + 'classification_heads.' + k not in state_dict: print('Overwriting',", "getattr(args, 'dropout', 0.1) args.max_target_positions = getattr(args, 'max_target_positions', 1024) args.max_source_positions =", "default=1024, type=int, metavar='N', help='max number of tokens in the source", "or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict, name):", "x, extra @classmethod def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2',", "args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.)", "getattr(self.args, 'load_checkpoint_heads', False): if head_name not in current_head_names: self.register_classification_head(head_name, num_classes,", ") parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout probability in the masked_lm", "with num_classes {} (prev: {}) ' 'and inner_dim {} (prev:", "the # LICENSE file in the root directory of this", "**kwargs, ): from fairseq import hub_utils x = hub_utils.from_pretrained( model_name_or_path,", "re-registering head \"{}\" with num_classes {} (prev: {}) ' 'and", "hub_utils x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True,", "x['task'], x['models'][0]) def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs): \"\"\"Register a", "in keys_to_delete: del state_dict[k] # Copy any newly-added classification heads", "= features x = self.dropout(x) x = self.dense(x) x =", "prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, ) if classification_head_name is not None:", "'encoder_layers', 12) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args,", "= getattr(args, 'share_all_embeddings', True) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim", "default=1024, type=int, metavar='N', help='max number of tokens in the target", "head ({}) from checkpoint ' 'with different dimensions than current", "True) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim',", "print( 'WARNING: deleting classification head ({}) from checkpoint ' 'not", "load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self, name,", "k in keys_to_delete: del state_dict[k] # Copy any newly-added classification", "src_lengths=src_lengths, **kwargs, ) x, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only,", "= BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, )", "not hasattr(self, 'classification_heads') else \\ self.classification_heads.keys() # Handle new classification", "self.classification_heads.state_dict() for k, v in cur_state.items(): if prefix + 'classification_heads.'", "else: if head_name not in current_head_names: print( 'WARNING: deleting classification", "current_head_names: print( 'WARNING: deleting classification head ({}) from checkpoint '", "k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes = state_dict[prefix + 'classification_heads.' + head_name", "'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding', True) args.layernorm_embedding = getattr(args,", "print(\"Registering classification head: {0}\".format(name)) if name in self.classification_heads: prev_num_classes =", "and Comprehension \"\"\" import torch.nn as nn from fairseq import", "True) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim',", "checkpoint ' 'with different dimensions than current model: {}'.format(head_name, k)", "= name + '.' if name != '' else ''", "!= prev_num_classes or inner_dim != prev_inner_dim: print( 'WARNING: re-registering head", "True) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.decoder_output_dim = getattr(args, 'decoder_output_dim',", "num_classes, activation_fn, pooler_dropout, ): super().__init__() self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn", "\\ self.classification_heads.keys() # Handle new classification heads present in the", "code is licensed under the MIT license found in the", "dict # with their current weights. if hasattr(self, 'classification_heads'): cur_state", "import hub_utils x = hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe,", "args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False)", "( num_classes != self.classification_heads[head_name].out_proj.out_features or inner_dim != self.classification_heads[head_name].dense.out_features ): print(", "= getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers", "= getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True) args.attention_dropout", "1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args, 'encoder_layers',", "source code is licensed under the MIT license found in", "Facebook, Inc. and its affiliates. # # This source code", "super().__init__() self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout =", "BARTModel).add_args(parser) parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N', help='max number of tokens", "number of tokens in the source sequence' ) parser.add_argument( '--max-target-positions',", "): if classification_head_name is not None: features_only = True encoder_out", "for Natural Language Generation, Translation, and Comprehension \"\"\" import torch.nn", "False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path = getattr(args, 'decoder_embed_path',", "# # This source code is licensed under the MIT", "archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'], x['task'], x['models'][0]) def", "prev_num_classes, inner_dim, prev_inner_dim ) ) self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim", "for sentence-level classification tasks.\"\"\" def __init__( self, input_dim, inner_dim, num_classes,", "inner_dim = state_dict[prefix + 'classification_heads.' + head_name + '.dense.weight'].size(0) if", "self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout,", "= getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed", "cur_state = self.classification_heads.state_dict() for k, v in cur_state.items(): if prefix", "args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024)", "'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args,", "current_head_names = [] if not hasattr(self, 'classification_heads') else \\ self.classification_heads.keys()", "in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else: if head_name not in", "+ 'classification_heads.' + head_name + '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False):", "\"\"\"Register a classification head.\"\"\" print(\"Registering classification head: {0}\".format(name)) if name", "BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification tasks.\"\"\" def __init__( self, input_dim,", "# This source code is licensed under the MIT license", "probability in the masked_lm pooler layers' ) parser.add_argument( '--pooler-activation-fn', choices=utils.get_available_activation_fns(),", "\"\"\"Head for sentence-level classification tasks.\"\"\" def __init__( self, input_dim, inner_dim,", "in current_head_names: print( 'WARNING: deleting classification head ({}) from checkpoint", ") return BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self, name, num_classes=None, inner_dim=None,", "fairseq.models import ( register_model, register_model_architecture, ) from fairseq.models.transformer import TransformerModel", "args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 12)", "def __init__( self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, ): super().__init__()", "help='dropout probability in the masked_lm pooler layers' ) parser.add_argument( '--pooler-activation-fn',", "inner_dim != prev_inner_dim: print( 'WARNING: re-registering head \"{}\" with num_classes", "16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos',", "args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim)", "'no_scale_embedding', True) args.layernorm_embedding = getattr(args, 'layernorm_embedding', True) args.activation_fn = getattr(args,", "not in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim) else: if head_name not", "upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix = name + '.'", "= getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings", "= self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes != prev_num_classes or", "fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface import", "'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh') args.pooler_dropout = getattr(args, 'pooler_dropout',", "self.classification_heads = nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser) parser.add_argument( '--max-source-positions',", "initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod def add_args(parser): super(BARTModel, BARTModel).add_args(parser)", "@register_model('bart') class BARTModel(TransformerModel): @classmethod def hub_models(cls): return { 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz',", "+ 'classification_heads.'): continue head_name = k[len(prefix + 'classification_heads.'):].split('.')[0] num_classes =", "tree. \"\"\" BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation,", "tasks.\"\"\" def __init__( self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, ):", "choices=utils.get_available_activation_fns(), help='activation function to use for pooler layer' ) @property", "getattr(args, 'max_target_positions', 1024) args.max_source_positions = getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff =", "'max_target_positions', 1024) args.max_source_positions = getattr(args, 'max_source_positions', 1024) args.adaptive_softmax_cutoff = getattr(args,", "self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes)", "x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)", "not k.startswith(prefix + 'classification_heads.'): continue head_name = k[len(prefix + 'classification_heads.'):].split('.')[0]", "checkpoint ' 'not present in current model: {}'.format(head_name, k) )", "= getattr(args, 'decoder_layers', 12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before", "args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)", "'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.max_target_positions = getattr(args,", "args.no_scale_embedding = getattr(args, 'no_scale_embedding', True) args.layernorm_embedding = getattr(args, 'layernorm_embedding', True)", "k) state_dict[prefix + 'classification_heads.' + k] = v class BARTClassificationHead(nn.Module):", "= [] if not hasattr(self, 'classification_heads') else \\ self.classification_heads.keys() #", "from fairseq.models.transformer import TransformerModel from fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface", "its affiliates. # # This source code is licensed under", "utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes) def forward(self,", "'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args, encoder, decoder): super().__init__(args,", "root directory of this source tree. \"\"\" BART: Denoising Sequence-to-Sequence", "getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding', True) args.layernorm_embedding =", "\"\"\" BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation,", "parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N', help='max number of tokens in", "'bart_large') def bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim =", "random weight initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod def add_args(parser):", "'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args,", "= getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout", "'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args,", "getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path =", "parser.add_argument( '--max-source-positions', default=1024, type=int, metavar='N', help='max number of tokens in", "function to use for pooler layer' ) @property def supported_targets(self):", "def from_pretrained( cls, model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', bpe='gpt2', **kwargs, ): from", "args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True)", "self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, ) x, extra = self.decoder( prev_output_tokens,", "'classification_heads.' + k) state_dict[prefix + 'classification_heads.' + k] = v", "x = self.dropout(x) x = self.out_proj(x) return x @register_model_architecture('bart', 'bart_large')", "= getattr(args, 'no_scale_embedding', True) args.layernorm_embedding = getattr(args, 'layernorm_embedding', True) args.activation_fn", "current model: {}'.format(head_name, k) ) keys_to_delete.append(k) for k in keys_to_delete:", "for k in state_dict.keys(): if not k.startswith(prefix + 'classification_heads.'): continue", "__init__( self, input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, ): super().__init__() self.dense", "head_name + '.dense.weight'].size(0) if getattr(self.args, 'load_checkpoint_heads', False): if head_name not", "getattr(args, 'decoder_attention_heads', 16) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos =", "= nn.Linear(inner_dim, num_classes) def forward(self, features, **kwargs): x = features", "= True encoder_out = self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, ) x,", "name, num_classes, prev_num_classes, inner_dim, prev_inner_dim ) ) self.classification_heads[name] = BARTClassificationHead(", "of this source tree. \"\"\" BART: Denoising Sequence-to-Sequence Pre-training for", "Language Generation, Translation, and Comprehension \"\"\" import torch.nn as nn", "from fairseq.modules.transformer_sentence_encoder import init_bert_params from .hub_interface import BARTHubInterface @register_model('bart') class", "if name != '' else '' current_head_names = [] if", "src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:, -1, :] x = self.classification_heads[classification_head_name](", "= getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding', True) args.layernorm_embedding", "# Copy any newly-added classification heads into the state dict", "file in the root directory of this source tree. \"\"\"", "self.classification_heads[classification_head_name]( sentence_representation ) return x, extra @classmethod def from_pretrained( cls,", "in state_dict: print('Overwriting', prefix + 'classification_heads.' + k) state_dict[prefix +", "present in current model: {}'.format(head_name, k) ) keys_to_delete.append(k) elif (", "'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args,", "input_dim, inner_dim, num_classes, activation_fn, pooler_dropout, ): super().__init__() self.dense = nn.Linear(input_dim,", "sentence_representation = x[ src_tokens.eq(self.encoder.dictionary.eos()), : ].view(x.size(0), -1, x.size(-1))[:, -1, :]", "src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ): if classification_head_name is", "= self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, ) if classification_head_name is", "!= prev_inner_dim: print( 'WARNING: re-registering head \"{}\" with num_classes {}", "deleting classification head ({}) from checkpoint ' 'not present in", "' 'with different dimensions than current model: {}'.format(head_name, k) )", "= hub_utils.from_pretrained( model_name_or_path, checkpoint_file, data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, )", "getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh') args.pooler_dropout =", "+ 'classification_heads.' + k) state_dict[prefix + 'classification_heads.' + k] =", "is licensed under the MIT license found in the #", "= getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh') args.pooler_dropout", "!= self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting classification head ({}) from", "src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ): if classification_head_name is not", "self.classification_heads[name].out_proj.out_features prev_inner_dim = self.classification_heads[name].dense.out_features if num_classes != prev_num_classes or inner_dim", "nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj =", "fairseq import utils from fairseq.models import ( register_model, register_model_architecture, )", "= getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers = getattr(args, 'encoder_layers', 12) args.encoder_attention_heads", "getattr(args, 'share_all_embeddings', True) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim =", "True) args.activation_fn = getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn',", "= getattr(args, 'encoder_learned_pos', True) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim", "in state_dict.keys(): if not k.startswith(prefix + 'classification_heads.'): continue head_name =", "getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) args.no_scale_embedding =", "Copy any newly-added classification heads into the state dict #", "metavar='D', help='dropout probability in the masked_lm pooler layers' ) parser.add_argument(", "metavar='N', help='max number of tokens in the source sequence' )", "of tokens in the target sequence' ) parser.add_argument( '--pooler-dropout', type=float,", "False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True) args.attention_dropout = getattr(args, 'attention_dropout',", "-1, :] x = self.classification_heads[classification_head_name]( sentence_representation ) return x, extra", "num_classes != prev_num_classes or inner_dim != prev_inner_dim: print( 'WARNING: re-registering", "sentence_representation ) return x, extra @classmethod def from_pretrained( cls, model_name_or_path,", "# Copyright (c) Facebook, Inc. and its affiliates. # #", "args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim)", "self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self,", "super().upgrade_state_dict_named(state_dict, name) prefix = name + '.' if name !=", "+ head_name + '.out_proj.weight'].size(0) inner_dim = state_dict[prefix + 'classification_heads.' +", "'classification_heads.' + k] = v class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level", "'load_checkpoint_heads', False): if head_name not in current_head_names: self.register_classification_head(head_name, num_classes, inner_dim)", "sentence-level classification tasks.\"\"\" def __init__( self, input_dim, inner_dim, num_classes, activation_fn,", "= nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout = nn.Dropout(p=pooler_dropout) self.out_proj", "heads present in the state dict. keys_to_delete = [] for", "in the target sequence' ) parser.add_argument( '--pooler-dropout', type=float, metavar='D', help='dropout", "metavar='N', help='max number of tokens in the target sequence' )", "head.\"\"\" print(\"Registering classification head: {0}\".format(name)) if name in self.classification_heads: prev_num_classes", "'.out_proj.weight'].size(0) inner_dim = state_dict[prefix + 'classification_heads.' + head_name + '.dense.weight'].size(0)", "current weights. if hasattr(self, 'classification_heads'): cur_state = self.classification_heads.state_dict() for k,", ") keys_to_delete.append(k) for k in keys_to_delete: del state_dict[k] # Copy", "getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', True) args.share_all_embeddings =", "from checkpoint ' 'with different dimensions than current model: {}'.format(head_name,", "help='max number of tokens in the target sequence' ) parser.add_argument(", "= self.classification_heads[classification_head_name]( sentence_representation ) return x, extra @classmethod def from_pretrained(", "features, **kwargs): x = features x = self.dropout(x) x =", "**kwargs): x = features x = self.dropout(x) x = self.dense(x)", "self.dropout(x) x = self.out_proj(x) return x @register_model_architecture('bart', 'bart_large') def bart_large_architecture(args):", "getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4*1024) args.encoder_layers =", "{}'.format(head_name, k) ) keys_to_delete.append(k) for k in keys_to_delete: del state_dict[k]", "args.activation_fn = getattr(args, 'activation_fn', 'gelu') args.pooler_activation_fn = getattr(args, 'pooler_activation_fn', 'tanh')", "BERT's random weight initialization self.apply(init_bert_params) self.classification_heads = nn.ModuleDict() @staticmethod def", "features_only = True encoder_out = self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, )", "nn.Linear(inner_dim, num_classes) def forward(self, features, **kwargs): x = features x", "args.dropout = getattr(args, 'dropout', 0.1) args.max_target_positions = getattr(args, 'max_target_positions', 1024)", "getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', True) args.attention_dropout =", "@register_model_architecture('bart', 'bart_large') def bart_large_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim", "inner_dim or self.args.encoder_embed_dim, num_classes, self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict,", "({}) from checkpoint ' 'with different dimensions than current model:", "else \\ self.classification_heads.keys() # Handle new classification heads present in", "data_name_or_path, archive_map=cls.hub_models(), bpe=bpe, load_checkpoint_heads=True, **kwargs, ) return BARTHubInterface(x['args'], x['task'], x['models'][0])", "import utils from fairseq.models import ( register_model, register_model_architecture, ) from", "src_tokens, src_lengths=src_lengths, **kwargs, ) x, extra = self.decoder( prev_output_tokens, encoder_out=encoder_out,", "None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim',", "**kwargs, ) return BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self, name, num_classes=None,", "self.args.pooler_activation_fn, self.args.pooler_dropout, ) def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) prefix", "source tree. \"\"\" BART: Denoising Sequence-to-Sequence Pre-training for Natural Language", "head_name not in current_head_names: print( 'WARNING: deleting classification head ({})", "in the source sequence' ) parser.add_argument( '--max-target-positions', default=1024, type=int, metavar='N',", "'not present in current model: {}'.format(head_name, k) ) keys_to_delete.append(k) elif", "Inc. and its affiliates. # # This source code is", "True encoder_out = self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, ) x, extra", "args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', True)", "args.decoder_embed_dim) args.no_scale_embedding = getattr(args, 'no_scale_embedding', True) args.layernorm_embedding = getattr(args, 'layernorm_embedding',", "args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1)", ") ) self.classification_heads[name] = BARTClassificationHead( self.args.encoder_embed_dim, inner_dim or self.args.encoder_embed_dim, num_classes,", "k] = v class BARTClassificationHead(nn.Module): \"\"\"Head for sentence-level classification tasks.\"\"\"", "the root directory of this source tree. \"\"\" BART: Denoising", "supported_targets(self): return {'self'} def forward( self, src_tokens, src_lengths, prev_output_tokens, features_only=False,", "than current model: {}'.format(head_name, k) ) keys_to_delete.append(k) for k in", "'--max-target-positions', default=1024, type=int, metavar='N', help='max number of tokens in the", "args.decoder_layers = getattr(args, 'decoder_layers', 12) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16)", "current model: {}'.format(head_name, k) ) keys_to_delete.append(k) elif ( num_classes !=", "'share_decoder_input_output_embed', True) args.share_all_embeddings = getattr(args, 'share_all_embeddings', True) args.decoder_output_dim = getattr(args,", "num_classes) def forward(self, features, **kwargs): x = features x =", "return BARTHubInterface(x['args'], x['task'], x['models'][0]) def register_classification_head(self, name, num_classes=None, inner_dim=None, **kwargs):", "x = self.dropout(x) x = self.dense(x) x = self.activation_fn(x) x", "= self.encoder( src_tokens, src_lengths=src_lengths, **kwargs, ) x, extra = self.decoder(", "extra = self.decoder( prev_output_tokens, encoder_out=encoder_out, features_only=features_only, **kwargs, ) if classification_head_name", "name + '.' if name != '' else '' current_head_names", "layer' ) @property def supported_targets(self): return {'self'} def forward( self,", "= state_dict[prefix + 'classification_heads.' + head_name + '.out_proj.weight'].size(0) inner_dim =", "{ 'bart.large': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.tar.gz', 'bart.large.mnli': 'http://dl.fbaipublicfiles.com/fairseq/models/bart.large.mnli.tar.gz', } def __init__(self, args, encoder,", "to use for pooler layer' ) @property def supported_targets(self): return", "): super().__init__() self.dense = nn.Linear(input_dim, inner_dim) self.activation_fn = utils.get_activation_fn(activation_fn) self.dropout", "'encoder_learned_pos', True) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args,", "self.classification_heads[head_name].dense.out_features ): print( 'WARNING: deleting classification head ({}) from checkpoint", "= getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.max_target_positions", "nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes) def forward(self, features, **kwargs): x", "type=int, metavar='N', help='max number of tokens in the source sequence'", "state_dict.keys(): if not k.startswith(prefix + 'classification_heads.'): continue head_name = k[len(prefix", "classification head ({}) from checkpoint ' 'not present in current", "self, src_tokens, src_lengths, prev_output_tokens, features_only=False, classification_head_name=None, **kwargs ): if classification_head_name", "import ( register_model, register_model_architecture, ) from fairseq.models.transformer import TransformerModel from", "= nn.Dropout(p=pooler_dropout) self.out_proj = nn.Linear(inner_dim, num_classes) def forward(self, features, **kwargs):" ]
[ "import wraps from logging import error from os import urandom", "json=False): return handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if", "from functools import wraps from logging import error from os", "from werkzeug.exceptions import Forbidden from werkzeug.exceptions import Gone from werkzeug.exceptions", "forbidden(e='403: Forbidden', json=False): return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405:", "return handle_error(e if 'check your spelling' not in '{}'.format(e) else", "handle_error(e if 'check your spelling' not in '{}'.format(e) else '404:", "@wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped return", "smileys_sad error_handlers = [] def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func,", "from werkzeug.exceptions import BadRequest from werkzeug.exceptions import Forbidden from werkzeug.exceptions", "wraps from logging import error from os import urandom from", "{'message': e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e,", "import NotFound from config import get_debug_flag from tracker import tracker", "from tracker.symbol import smileys_sad error_handlers = [] def errorhandler(code_or_exception): def", "import get_debug_flag from tracker import tracker from tracker.symbol import smileys_sad", "method_not_allowed(e='405: Method Not Allowed', json=False): return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code)", "return handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag():", "<gh_stars>0 from binascii import hexlify from functools import wraps from", "import urandom from random import randint from flask import make_response", "def forbidden(e='403: Forbidden', json=False): return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def", "Allowed', json=False): return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410: Gone',", "@errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag(): raise e code = hexlify(urandom(4)).decode()", "from config import get_debug_flag from tracker import tracker from tracker.symbol", "code, json=False): if json: return {'message': e}, code return make_response(render_template('error.html',", "gone(e='410: Gone', json=False): return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400:", "NotFound from config import get_debug_flag from tracker import tracker from", "- 1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404: Not Found',", "from random import randint from flask import make_response from flask", "= [] def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception})", "decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args, **kwargs): return", "Gone from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import MethodNotAllowed from", "not_found(e='404: Not Found', json=False): return handle_error(e if 'check your spelling'", "if 'check your spelling' not in '{}'.format(e) else '404: Not", "import Gone from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import MethodNotAllowed", "import InternalServerError from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound", "BadRequest from werkzeug.exceptions import Forbidden from werkzeug.exceptions import Gone from", "tracker.symbol import smileys_sad error_handlers = [] def errorhandler(code_or_exception): def decorator(func):", "smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404:", "raise e code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True) text", "import smileys_sad error_handlers = [] def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func':", "**kwargs): return func(*args, **kwargs) return wrapped return decorator def handle_error(e,", "json=False): return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not", "json=False): return handle_error(e if 'check your spelling' not in '{}'.format(e)", "error(Exception(\"Code: {}\".format(code), e), exc_info=True) text = '500: Deep Shit\\n{}'.format(code) return", "not in '{}'.format(e) else '404: Not Found', NotFound.code, json) @errorhandler(Forbidden.code)", "werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound from config import", "{}\".format(code), e), exc_info=True) text = '500: Deep Shit\\n{}'.format(code) return handle_error(text,", "tracker from tracker.symbol import smileys_sad error_handlers = [] def errorhandler(code_or_exception):", "code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e, title='{}'.format(code)), code)", "werkzeug.exceptions import InternalServerError from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import", "Request', json=False): return handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e):", "Method Not Allowed', json=False): return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def", "= hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True) text = '500: Deep", "werkzeug.exceptions import Gone from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import", "Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not Allowed', json=False): return", "json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False): return handle_error(e, Forbidden.code, json)", "len(smileys_sad) - 1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404: Not", "decorator def handle_error(e, code, json=False): if json: return {'message': e},", "hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True) text = '500: Deep Shit\\n{}'.format(code)", "binascii import hexlify from functools import wraps from logging import", "return {'message': e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)],", "def internal_error(e): if get_debug_flag(): raise e code = hexlify(urandom(4)).decode() error(Exception(\"Code:", "import tracker from tracker.symbol import smileys_sad error_handlers = [] def", "'{}'.format(e) else '404: Not Found', NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403:", "MethodNotAllowed from werkzeug.exceptions import NotFound from config import get_debug_flag from", "json=False): return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad Request',", "Forbidden', json=False): return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method", "@errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not Allowed', json=False): return handle_error(e, MethodNotAllowed.code,", "error_handlers = [] def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func, 'code_or_exception':", "spelling' not in '{}'.format(e) else '404: Not Found', NotFound.code, json)", "from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound from config", "if json: return {'message': e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad)", "@errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag(): raise e code =", "get_debug_flag(): raise e code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True)", "from logging import error from os import urandom from random", "def not_found(e='404: Not Found', json=False): return handle_error(e if 'check your", "from tracker import tracker from tracker.symbol import smileys_sad error_handlers =", "return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad Request', json=False):", "wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped return decorator def", "title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404: Not Found', json=False): return handle_error(e", "bad_request(e='400: Bad Request', json=False): return handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code)", "import randint from flask import make_response from flask import render_template", "Gone', json=False): return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad", "json=False): if json: return {'message': e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0,", "'404: Not Found', NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False):", "'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs) return", "wrapped return decorator def handle_error(e, code, json=False): if json: return", "from flask import make_response from flask import render_template from werkzeug.exceptions", "'check your spelling' not in '{}'.format(e) else '404: Not Found',", "@errorhandler(BadRequest.code) def bad_request(e='400: Bad Request', json=False): return handle_error(e, BadRequest.code, json)", "werkzeug.exceptions import NotFound from config import get_debug_flag from tracker import", "import make_response from flask import render_template from werkzeug.exceptions import BadRequest", "def wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped return decorator", "import render_template from werkzeug.exceptions import BadRequest from werkzeug.exceptions import Forbidden", "Found', NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False): return handle_error(e,", "return decorator def handle_error(e, code, json=False): if json: return {'message':", "json=False): return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410: Gone', json=False):", "handle_error(e, code, json=False): if json: return {'message': e}, code return", "json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not Allowed', json=False): return handle_error(e,", "InternalServerError from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound from", "e), exc_info=True) text = '500: Deep Shit\\n{}'.format(code) return handle_error(text, InternalServerError.code)", "e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e, title='{}'.format(code)),", "werkzeug.exceptions import BadRequest from werkzeug.exceptions import Forbidden from werkzeug.exceptions import", "return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410: Gone', json=False): return", "hexlify from functools import wraps from logging import error from", "handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410: Gone', json=False): return handle_error(e,", "make_response from flask import render_template from werkzeug.exceptions import BadRequest from", "make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def", "def method_not_allowed(e='405: Method Not Allowed', json=False): return handle_error(e, MethodNotAllowed.code, json)", "[] def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func)", "from flask import render_template from werkzeug.exceptions import BadRequest from werkzeug.exceptions", "code_or_exception}) @wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs) return wrapped", "def errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func) def", "NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False): return handle_error(e, Forbidden.code,", "flask import make_response from flask import render_template from werkzeug.exceptions import", "func, 'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args, **kwargs): return func(*args, **kwargs)", "urandom from random import randint from flask import make_response from", "json) @errorhandler(Gone.code) def gone(e='410: Gone', json=False): return handle_error(e, Gone.code, json)", "Not Found', json=False): return handle_error(e if 'check your spelling' not", "Found', json=False): return handle_error(e if 'check your spelling' not in", "Not Found', NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False): return", "handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not Allowed', json=False):", "werkzeug.exceptions import Forbidden from werkzeug.exceptions import Gone from werkzeug.exceptions import", "if get_debug_flag(): raise e code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e),", "import hexlify from functools import wraps from logging import error", "from werkzeug.exceptions import NotFound from config import get_debug_flag from tracker", "def gone(e='410: Gone', json=False): return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def", "def decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args, **kwargs):", "return func(*args, **kwargs) return wrapped return decorator def handle_error(e, code,", "json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad Request', json=False): return handle_error(e, BadRequest.code,", "import Forbidden from werkzeug.exceptions import Gone from werkzeug.exceptions import InternalServerError", "def handle_error(e, code, json=False): if json: return {'message': e}, code", "code) @errorhandler(NotFound.code) def not_found(e='404: Not Found', json=False): return handle_error(e if", "import MethodNotAllowed from werkzeug.exceptions import NotFound from config import get_debug_flag", "Not Allowed', json=False): return handle_error(e, MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410:", "**kwargs) return wrapped return decorator def handle_error(e, code, json=False): if", "Forbidden from werkzeug.exceptions import Gone from werkzeug.exceptions import InternalServerError from", "functools import wraps from logging import error from os import", "handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag(): raise", "import BadRequest from werkzeug.exceptions import Forbidden from werkzeug.exceptions import Gone", "func(*args, **kwargs) return wrapped return decorator def handle_error(e, code, json=False):", "Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad Request', json=False): return handle_error(e,", "else '404: Not Found', NotFound.code, json) @errorhandler(Forbidden.code) def forbidden(e='403: Forbidden',", "randint from flask import make_response from flask import render_template from", "e code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True) text =", "MethodNotAllowed.code, json) @errorhandler(Gone.code) def gone(e='410: Gone', json=False): return handle_error(e, Gone.code,", "json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag(): raise e code", "tracker import tracker from tracker.symbol import smileys_sad error_handlers = []", "return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) - 1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code)", "json: return {'message': e}, code return make_response(render_template('error.html', smiley=smileys_sad[randint(0, len(smileys_sad) -", "from werkzeug.exceptions import InternalServerError from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions", "get_debug_flag from tracker import tracker from tracker.symbol import smileys_sad error_handlers", "errorhandler(code_or_exception): def decorator(func): error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args,", "from os import urandom from random import randint from flask", "return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code) def method_not_allowed(e='405: Method Not Allowed',", "config import get_debug_flag from tracker import tracker from tracker.symbol import", "os import urandom from random import randint from flask import", "@errorhandler(Forbidden.code) def forbidden(e='403: Forbidden', json=False): return handle_error(e, Forbidden.code, json) @errorhandler(MethodNotAllowed.code)", "your spelling' not in '{}'.format(e) else '404: Not Found', NotFound.code,", "from binascii import hexlify from functools import wraps from logging", "1)], text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404: Not Found', json=False):", "BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def internal_error(e): if get_debug_flag(): raise e", "in '{}'.format(e) else '404: Not Found', NotFound.code, json) @errorhandler(Forbidden.code) def", "error_handlers.append({'func': func, 'code_or_exception': code_or_exception}) @wraps(func) def wrapped(*args, **kwargs): return func(*args,", "@errorhandler(Gone.code) def gone(e='410: Gone', json=False): return handle_error(e, Gone.code, json) @errorhandler(BadRequest.code)", "return wrapped return decorator def handle_error(e, code, json=False): if json:", "random import randint from flask import make_response from flask import", "def bad_request(e='400: Bad Request', json=False): return handle_error(e, BadRequest.code, json) @errorhandler(Exception)", "handle_error(e, Gone.code, json) @errorhandler(BadRequest.code) def bad_request(e='400: Bad Request', json=False): return", "flask import render_template from werkzeug.exceptions import BadRequest from werkzeug.exceptions import", "render_template from werkzeug.exceptions import BadRequest from werkzeug.exceptions import Forbidden from", "logging import error from os import urandom from random import", "code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code), e), exc_info=True) text = '500:", "error from os import urandom from random import randint from", "internal_error(e): if get_debug_flag(): raise e code = hexlify(urandom(4)).decode() error(Exception(\"Code: {}\".format(code),", "Bad Request', json=False): return handle_error(e, BadRequest.code, json) @errorhandler(Exception) @errorhandler(InternalServerError.code) def", "text=e, title='{}'.format(code)), code) @errorhandler(NotFound.code) def not_found(e='404: Not Found', json=False): return", "import error from os import urandom from random import randint", "from werkzeug.exceptions import Gone from werkzeug.exceptions import InternalServerError from werkzeug.exceptions", "@errorhandler(NotFound.code) def not_found(e='404: Not Found', json=False): return handle_error(e if 'check" ]
[ "BaseEvent(object): def __init__(self, type, data): self.type = type self.name =", "super().__init__(type, data) self.category = data.get(\"cat\", \"\") self.duration = data.get(\"dur\") @property", "id\") if extern_id is None: extern_id = self.args.get(\"External id\") return", "return extern_id @property def callstack(self): return self.args.get(\"Call stack\", \"\") @property", "if category == \"Operator\": name = event.get(\"name\") if name and", "self.args.get(\"External id\") return extern_id @property def callstack(self): return self.args.get(\"Call stack\",", "= \"Runtime\" KERNEL = \"Kernel\" MEMCPY = \"Memcpy\" MEMSET =", "extern_id @property def callstack(self): return self.args.get(\"Call stack\", \"\") @property def", "= self.args.get(\"Input dims\") return shape @property def input_type(self): return self.args.get(\"Input", "\"Memset\" PYTHON = \"Python\" MEMORY = \"Memory\" Supported_EventTypes = [v", "type self.name = data.get(\"name\") self.ts = data.get(\"ts\") self.pid = data.get(\"pid\")", "shape is None: shape = self.args.get(\"Input dims\") return shape @property", "if dtype is None: return None try: return DeviceType(dtype) except", "k.startswith(\"_\") and v != EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self, type,", "exc_info=True) raise def create_trace_event(event): category = event.get(\"cat\") if category ==", "Exception=%s. Event=%s\", ex, event, exc_info=True) raise def create_trace_event(event): category =", "\"\") self.duration = data.get(\"dur\") @property def external_id(self): extern_id = self.args.get(\"external", "return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data)", "data.get(\"args\", {}) class TraceEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data)", "\"create_event\"] logger = utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'], start=0)", "== \"i\" and event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY, event) else:", "data.get(\"pid\") self.tid = data.get(\"tid\") self.args = data.get(\"args\", {}) class TraceEvent(BaseEvent):", "\"Runtime\" KERNEL = \"Kernel\" MEMCPY = \"Memcpy\" MEMSET = \"Memset\"", "shape @property def input_type(self): return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def", "self.args.get(\"Input Dims\") if shape is None: shape = self.args.get(\"Input dims\")", "def bytes(self): return self.args.get(\"Bytes\", 0) def create_event(event): try: type =", "= event.get(\"cat\") if category == \"Operator\": name = event.get(\"name\") if", "parse profile event. Exception=%s. Event=%s\", ex, event, exc_info=True) raise def", "\"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL = \"Kernel\"", "= \"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL = \"Kernel\" MEMCPY =", "= data.get(\"name\") self.ts = data.get(\"ts\") self.pid = data.get(\"pid\") self.tid =", "= data.get(\"tid\") self.args = data.get(\"args\", {}) class TraceEvent(BaseEvent): def __init__(self,", "None @property def device_id(self): return self.args.get(\"Device Id\") @property def bytes(self):", "None except Exception as ex: logger.warning(\"Failed to parse profile event.", "MEMORY = \"Memory\" Supported_EventTypes = [v for k, v in", "def callstack(self): return self.args.get(\"Call stack\", \"\") @property def input_shape(self): shape", "Corporation. All rights reserved. # -------------------------------------------------------------------------- from enum import IntEnum", "\"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self, type, data):", "PROFILER_STEP = \"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL = \"Kernel\" MEMCPY", "\"\") @property def device_type(self): dtype = self.args.get(\"Device Type\") if dtype", "None: return None try: return DeviceType(dtype) except ValueError: return None", "name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category in Supported_EventTypes: return", "device_type(self): dtype = self.args.get(\"Device Type\") if dtype is None: return", "ValueError: return None @property def device_id(self): return self.args.get(\"Device Id\") @property", "data.get(\"s\", \"\") @property def device_type(self): dtype = self.args.get(\"Device Type\") if", "self.args.get(\"Call stack\", \"\") @property def input_shape(self): shape = self.args.get(\"Input Dims\")", "extern_id = self.args.get(\"external id\") if extern_id is None: extern_id =", "like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self, type,", "create_trace_event(event) elif type == \"i\" and event.get('s') == 't': return", "return None @property def device_id(self): return self.args.get(\"Device Id\") @property def", "bytes(self): return self.args.get(\"Bytes\", 0) def create_event(event): try: type = event.get(\"ph\")", "dims\") return shape @property def input_type(self): return self.args.get(\"Input type\") class", "== \"Operator\": name = event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"): return", "\"Memcpy\" MEMSET = \"Memset\" PYTHON = \"Python\" MEMORY = \"Memory\"", "v in vars(EventTypes).items() if not k.startswith(\"_\") and v != EventTypes.PROFILER_STEP]", "in vars(EventTypes).items() if not k.startswith(\"_\") and v != EventTypes.PROFILER_STEP] class", "with name like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def", "= event.get(\"ph\") if type == \"X\": return create_trace_event(event) elif type", "and v != EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self, type, data):", "self.scope = data.get(\"s\", \"\") @property def device_type(self): dtype = self.args.get(\"Device", "PYTHON = \"Python\" MEMORY = \"Memory\" Supported_EventTypes = [v for", "and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category in Supported_EventTypes: return TraceEvent(category,", "@property def bytes(self): return self.args.get(\"Bytes\", 0) def create_event(event): try: type", "@property def callstack(self): return self.args.get(\"Call stack\", \"\") @property def input_shape(self):", "int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.scope", "= data.get(\"cat\", \"\") self.duration = data.get(\"dur\") @property def external_id(self): extern_id", "'CUDA'], start=0) class EventTypes(object): TRACE = \"Trace\" OPERATOR = \"Operator\"", "DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class EventTypes(object): TRACE =", "try: return DeviceType(dtype) except ValueError: return None @property def device_id(self):", "class EventTypes(object): TRACE = \"Trace\" OPERATOR = \"Operator\" PROFILER_STEP =", "invoke record_function with name like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class", "Id\") @property def bytes(self): return self.args.get(\"Bytes\", 0) def create_event(event): try:", "[v for k, v in vars(EventTypes).items() if not k.startswith(\"_\") and", "\"i\" and event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY, event) else: return", "return None except Exception as ex: logger.warning(\"Failed to parse profile", "(c) Microsoft Corporation. All rights reserved. # -------------------------------------------------------------------------- from enum", "\"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL = \"Kernel\" MEMCPY = \"Memcpy\"", "as ex: logger.warning(\"Failed to parse profile event. Exception=%s. Event=%s\", ex,", "self.category = data.get(\"cat\", \"\") self.duration = data.get(\"dur\") @property def external_id(self):", "def create_trace_event(event): category = event.get(\"cat\") if category == \"Operator\": name", "= data.get(\"dur\") @property def external_id(self): extern_id = self.args.get(\"external id\") if", "enum import IntEnum from .. import utils __all__ = [\"EventTypes\",", "return self.args.get(\"Call stack\", \"\") @property def input_shape(self): shape = self.args.get(\"Input", "MemoryEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.scope = data.get(\"s\",", "@property def device_id(self): return self.args.get(\"Device Id\") @property def bytes(self): return", "self.args = data.get(\"args\", {}) class TraceEvent(BaseEvent): def __init__(self, type, data):", "self.args.get(\"external id\") if extern_id is None: extern_id = self.args.get(\"External id\")", "= \"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL =", "OPERATOR = \"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME = \"Runtime\" KERNEL", "Microsoft Corporation. All rights reserved. # -------------------------------------------------------------------------- from enum import", "0) def create_event(event): try: type = event.get(\"ph\") if type ==", "torch.profiler.profile.step will invoke record_function with name like \"ProfilerStep#5\" self.step =", "ex, event, exc_info=True) raise def create_trace_event(event): category = event.get(\"cat\") if", "name like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self,", "= utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class EventTypes(object):", "# -------------------------------------------------------------------------- from enum import IntEnum from .. import utils", "record_function with name like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent):", "= self.args.get(\"external id\") if extern_id is None: extern_id = self.args.get(\"External", "utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class EventTypes(object): TRACE", "extern_id is None: extern_id = self.args.get(\"External id\") return extern_id @property", "data): super().__init__(type, data) self.scope = data.get(\"s\", \"\") @property def device_type(self):", "type, data): super().__init__(type, data) self.scope = data.get(\"s\", \"\") @property def", "= [\"EventTypes\", \"create_event\"] logger = utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU',", "self.type = type self.name = data.get(\"name\") self.ts = data.get(\"ts\") self.pid", "dtype = self.args.get(\"Device Type\") if dtype is None: return None", "id\") return extern_id @property def callstack(self): return self.args.get(\"Call stack\", \"\")", "except ValueError: return None @property def device_id(self): return self.args.get(\"Device Id\")", "def device_id(self): return self.args.get(\"Device Id\") @property def bytes(self): return self.args.get(\"Bytes\",", "self.args.get(\"Device Id\") @property def bytes(self): return self.args.get(\"Bytes\", 0) def create_event(event):", "to parse profile event. Exception=%s. Event=%s\", ex, event, exc_info=True) raise", "event. Exception=%s. Event=%s\", ex, event, exc_info=True) raise def create_trace_event(event): category", "data.get(\"dur\") @property def external_id(self): extern_id = self.args.get(\"external id\") if extern_id", "__init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will invoke record_function with", "is None: extern_id = self.args.get(\"External id\") return extern_id @property def", "TRACE = \"Trace\" OPERATOR = \"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME", "Event=%s\", ex, event, exc_info=True) raise def create_trace_event(event): category = event.get(\"cat\")", "class BaseEvent(object): def __init__(self, type, data): self.type = type self.name", "self.step = int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self, type, data): super().__init__(type,", "self.args.get(\"Input dims\") return shape @property def input_type(self): return self.args.get(\"Input type\")", "__init__(self, type, data): self.type = type self.name = data.get(\"name\") self.ts", "event.get(\"cat\") if category == \"Operator\": name = event.get(\"name\") if name", "if name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category in Supported_EventTypes:", "-------------------------------------------------------------------------- from enum import IntEnum from .. import utils __all__", "category = event.get(\"cat\") if category == \"Operator\": name = event.get(\"name\")", "event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category in", "name = event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if", "@property def external_id(self): extern_id = self.args.get(\"external id\") if extern_id is", "if shape is None: shape = self.args.get(\"Input dims\") return shape", "= \"Python\" MEMORY = \"Memory\" Supported_EventTypes = [v for k,", "data): self.type = type self.name = data.get(\"name\") self.ts = data.get(\"ts\")", "return DeviceType(dtype) except ValueError: return None @property def device_id(self): return", "EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self, type, data): self.type = type", "TraceEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.category = data.get(\"cat\",", "super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will invoke record_function with name like", "logger.warning(\"Failed to parse profile event. Exception=%s. Event=%s\", ex, event, exc_info=True)", "from .. import utils __all__ = [\"EventTypes\", \"create_event\"] logger =", "MemoryEvent(EventTypes.MEMORY, event) else: return None except Exception as ex: logger.warning(\"Failed", "return create_trace_event(event) elif type == \"i\" and event.get('s') == 't':", "MEMCPY = \"Memcpy\" MEMSET = \"Memset\" PYTHON = \"Python\" MEMORY", "type = event.get(\"ph\") if type == \"X\": return create_trace_event(event) elif", "<gh_stars>0 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights", "input_shape(self): shape = self.args.get(\"Input Dims\") if shape is None: shape", "device_id(self): return self.args.get(\"Device Id\") @property def bytes(self): return self.args.get(\"Bytes\", 0)", "\"Memory\" Supported_EventTypes = [v for k, v in vars(EventTypes).items() if", "super().__init__(type, data) self.scope = data.get(\"s\", \"\") @property def device_type(self): dtype", "not k.startswith(\"_\") and v != EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self,", "try: type = event.get(\"ph\") if type == \"X\": return create_trace_event(event)", "= data.get(\"args\", {}) class TraceEvent(BaseEvent): def __init__(self, type, data): super().__init__(type,", "ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will invoke", "else: return None except Exception as ex: logger.warning(\"Failed to parse", "= type self.name = data.get(\"name\") self.ts = data.get(\"ts\") self.pid =", "data.get(\"ts\") self.pid = data.get(\"pid\") self.tid = data.get(\"tid\") self.args = data.get(\"args\",", "__init__(self, type, data): super().__init__(type, data) self.scope = data.get(\"s\", \"\") @property", "self.pid = data.get(\"pid\") self.tid = data.get(\"tid\") self.args = data.get(\"args\", {})", "data) # torch.profiler.profile.step will invoke record_function with name like \"ProfilerStep#5\"", "Dims\") if shape is None: shape = self.args.get(\"Input dims\") return", "data) self.category = data.get(\"cat\", \"\") self.duration = data.get(\"dur\") @property def", "class ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will", "= self.args.get(\"Device Type\") if dtype is None: return None try:", "name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category in Supported_EventTypes: return TraceEvent(category, event)", "return MemoryEvent(EventTypes.MEMORY, event) else: return None except Exception as ex:", "\"Python\" MEMORY = \"Memory\" Supported_EventTypes = [v for k, v", "import IntEnum from .. import utils __all__ = [\"EventTypes\", \"create_event\"]", "= self.args.get(\"Input Dims\") if shape is None: shape = self.args.get(\"Input", "'t': return MemoryEvent(EventTypes.MEMORY, event) else: return None except Exception as", "ProfilerStepEvent(event) if category in Supported_EventTypes: return TraceEvent(category, event) else: return", "start=0) class EventTypes(object): TRACE = \"Trace\" OPERATOR = \"Operator\" PROFILER_STEP", "def __init__(self, type, data): super().__init__(type, data) self.category = data.get(\"cat\", \"\")", "def input_type(self): return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def __init__(self, data):", "shape = self.args.get(\"Input Dims\") if shape is None: shape =", "type, data): self.type = type self.name = data.get(\"name\") self.ts =", "utils __all__ = [\"EventTypes\", \"create_event\"] logger = utils.get_logger() DeviceType =", "self.duration = data.get(\"dur\") @property def external_id(self): extern_id = self.args.get(\"external id\")", "= \"Memcpy\" MEMSET = \"Memset\" PYTHON = \"Python\" MEMORY =", "def input_shape(self): shape = self.args.get(\"Input Dims\") if shape is None:", "create_event(event): try: type = event.get(\"ph\") if type == \"X\": return", "is None: shape = self.args.get(\"Input dims\") return shape @property def", "All rights reserved. # -------------------------------------------------------------------------- from enum import IntEnum from", "profile event. Exception=%s. Event=%s\", ex, event, exc_info=True) raise def create_trace_event(event):", "== \"X\": return create_trace_event(event) elif type == \"i\" and event.get('s')", "@property def input_shape(self): shape = self.args.get(\"Input Dims\") if shape is", "dtype is None: return None try: return DeviceType(dtype) except ValueError:", "event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY, event) else: return None except", "Copyright (c) Microsoft Corporation. All rights reserved. # -------------------------------------------------------------------------- from", "self.tid = data.get(\"tid\") self.args = data.get(\"args\", {}) class TraceEvent(BaseEvent): def", "= data.get(\"pid\") self.tid = data.get(\"tid\") self.args = data.get(\"args\", {}) class", "class MemoryEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.scope =", "raise def create_trace_event(event): category = event.get(\"cat\") if category == \"Operator\":", "for k, v in vars(EventTypes).items() if not k.startswith(\"_\") and v", "------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. #", "Type\") if dtype is None: return None try: return DeviceType(dtype)", "== 't': return MemoryEvent(EventTypes.MEMORY, event) else: return None except Exception", "logger = utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class", "def __init__(self, type, data): super().__init__(type, data) self.scope = data.get(\"s\", \"\")", "self.name = data.get(\"name\") self.ts = data.get(\"ts\") self.pid = data.get(\"pid\") self.tid", "data.get(\"tid\") self.args = data.get(\"args\", {}) class TraceEvent(BaseEvent): def __init__(self, type,", "callstack(self): return self.args.get(\"Call stack\", \"\") @property def input_shape(self): shape =", "except Exception as ex: logger.warning(\"Failed to parse profile event. Exception=%s.", "elif type == \"i\" and event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY,", "type, data): super().__init__(type, data) self.category = data.get(\"cat\", \"\") self.duration =", "def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will invoke record_function", "input_type(self): return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP,", "@property def device_type(self): dtype = self.args.get(\"Device Type\") if dtype is", "event, exc_info=True) raise def create_trace_event(event): category = event.get(\"cat\") if category", "\"\") @property def input_shape(self): shape = self.args.get(\"Input Dims\") if shape", "# torch.profiler.profile.step will invoke record_function with name like \"ProfilerStep#5\" self.step", "\"X\": return create_trace_event(event) elif type == \"i\" and event.get('s') ==", "vars(EventTypes).items() if not k.startswith(\"_\") and v != EventTypes.PROFILER_STEP] class BaseEvent(object):", "type\") class ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step", "import utils __all__ = [\"EventTypes\", \"create_event\"] logger = utils.get_logger() DeviceType", "data.get(\"cat\", \"\") self.duration = data.get(\"dur\") @property def external_id(self): extern_id =", "= int(self.name.split(\"#\")[1]) class MemoryEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data)", "\"Operator\": name = event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event)", "['CPU', 'CUDA'], start=0) class EventTypes(object): TRACE = \"Trace\" OPERATOR =", "event.get(\"ph\") if type == \"X\": return create_trace_event(event) elif type ==", "RUNTIME = \"Runtime\" KERNEL = \"Kernel\" MEMCPY = \"Memcpy\" MEMSET", "None: shape = self.args.get(\"Input dims\") return shape @property def input_type(self):", "category == \"Operator\": name = event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"):", "KERNEL = \"Kernel\" MEMCPY = \"Memcpy\" MEMSET = \"Memset\" PYTHON", "return shape @property def input_type(self): return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent):", "= \"Memory\" Supported_EventTypes = [v for k, v in vars(EventTypes).items()", "IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class EventTypes(object): TRACE = \"Trace\" OPERATOR", "data) self.scope = data.get(\"s\", \"\") @property def device_type(self): dtype =", "def device_type(self): dtype = self.args.get(\"Device Type\") if dtype is None:", "\"Kernel\" MEMCPY = \"Memcpy\" MEMSET = \"Memset\" PYTHON = \"Python\"", "Exception as ex: logger.warning(\"Failed to parse profile event. Exception=%s. Event=%s\",", "extern_id = self.args.get(\"External id\") return extern_id @property def callstack(self): return", "reserved. # -------------------------------------------------------------------------- from enum import IntEnum from .. import", "return None try: return DeviceType(dtype) except ValueError: return None @property", "DeviceType(dtype) except ValueError: return None @property def device_id(self): return self.args.get(\"Device", "data.get(\"name\") self.ts = data.get(\"ts\") self.pid = data.get(\"pid\") self.tid = data.get(\"tid\")", "type == \"i\" and event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY, event)", "self.args.get(\"Device Type\") if dtype is None: return None try: return", "= IntEnum('DeviceType', ['CPU', 'CUDA'], start=0) class EventTypes(object): TRACE = \"Trace\"", "!= EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self, type, data): self.type =", "and event.get('s') == 't': return MemoryEvent(EventTypes.MEMORY, event) else: return None", "= data.get(\"s\", \"\") @property def device_type(self): dtype = self.args.get(\"Device Type\")", "self.args.get(\"Bytes\", 0) def create_event(event): try: type = event.get(\"ph\") if type", "k, v in vars(EventTypes).items() if not k.startswith(\"_\") and v !=", "__init__(self, type, data): super().__init__(type, data) self.category = data.get(\"cat\", \"\") self.duration", "class TraceEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.category =", "\"Trace\" OPERATOR = \"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME = \"Runtime\"", "# Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------------------------", "external_id(self): extern_id = self.args.get(\"external id\") if extern_id is None: extern_id", "from enum import IntEnum from .. import utils __all__ =", "IntEnum from .. import utils __all__ = [\"EventTypes\", \"create_event\"] logger", "if type == \"X\": return create_trace_event(event) elif type == \"i\"", ".. import utils __all__ = [\"EventTypes\", \"create_event\"] logger = utils.get_logger()", "= \"Trace\" OPERATOR = \"Operator\" PROFILER_STEP = \"ProfilerStep\" RUNTIME =", "will invoke record_function with name like \"ProfilerStep#5\" self.step = int(self.name.split(\"#\")[1])", "= event.get(\"name\") if name and name.startswith(\"ProfilerStep#\"): return ProfilerStepEvent(event) if category", "= \"Memset\" PYTHON = \"Python\" MEMORY = \"Memory\" Supported_EventTypes =", "v != EventTypes.PROFILER_STEP] class BaseEvent(object): def __init__(self, type, data): self.type", "Supported_EventTypes = [v for k, v in vars(EventTypes).items() if not", "= self.args.get(\"External id\") return extern_id @property def callstack(self): return self.args.get(\"Call", "shape = self.args.get(\"Input dims\") return shape @property def input_type(self): return", "def create_event(event): try: type = event.get(\"ph\") if type == \"X\":", "return ProfilerStepEvent(event) if category in Supported_EventTypes: return TraceEvent(category, event) else:", "[\"EventTypes\", \"create_event\"] logger = utils.get_logger() DeviceType = IntEnum('DeviceType', ['CPU', 'CUDA'],", "= data.get(\"ts\") self.pid = data.get(\"pid\") self.tid = data.get(\"tid\") self.args =", "# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved.", "ex: logger.warning(\"Failed to parse profile event. Exception=%s. Event=%s\", ex, event,", "data): super().__init__(type, data) self.category = data.get(\"cat\", \"\") self.duration = data.get(\"dur\")", "EventTypes(object): TRACE = \"Trace\" OPERATOR = \"Operator\" PROFILER_STEP = \"ProfilerStep\"", "if not k.startswith(\"_\") and v != EventTypes.PROFILER_STEP] class BaseEvent(object): def", "create_trace_event(event): category = event.get(\"cat\") if category == \"Operator\": name =", "self.ts = data.get(\"ts\") self.pid = data.get(\"pid\") self.tid = data.get(\"tid\") self.args", "data): super().__init__(EventTypes.PROFILER_STEP, data) # torch.profiler.profile.step will invoke record_function with name", "return self.args.get(\"Device Id\") @property def bytes(self): return self.args.get(\"Bytes\", 0) def", "if extern_id is None: extern_id = self.args.get(\"External id\") return extern_id", "return self.args.get(\"Bytes\", 0) def create_event(event): try: type = event.get(\"ph\") if", "MEMSET = \"Memset\" PYTHON = \"Python\" MEMORY = \"Memory\" Supported_EventTypes", "None try: return DeviceType(dtype) except ValueError: return None @property def", "type == \"X\": return create_trace_event(event) elif type == \"i\" and", "= [v for k, v in vars(EventTypes).items() if not k.startswith(\"_\")", "{}) class TraceEvent(BaseEvent): def __init__(self, type, data): super().__init__(type, data) self.category", "self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def __init__(self, data): super().__init__(EventTypes.PROFILER_STEP, data) #", "if category in Supported_EventTypes: return TraceEvent(category, event) else: return None", "def __init__(self, type, data): self.type = type self.name = data.get(\"name\")", "stack\", \"\") @property def input_shape(self): shape = self.args.get(\"Input Dims\") if", "= \"Kernel\" MEMCPY = \"Memcpy\" MEMSET = \"Memset\" PYTHON =", "is None: return None try: return DeviceType(dtype) except ValueError: return", "None: extern_id = self.args.get(\"External id\") return extern_id @property def callstack(self):", "__all__ = [\"EventTypes\", \"create_event\"] logger = utils.get_logger() DeviceType = IntEnum('DeviceType',", "rights reserved. # -------------------------------------------------------------------------- from enum import IntEnum from ..", "def external_id(self): extern_id = self.args.get(\"external id\") if extern_id is None:", "event) else: return None except Exception as ex: logger.warning(\"Failed to", "@property def input_type(self): return self.args.get(\"Input type\") class ProfilerStepEvent(TraceEvent): def __init__(self," ]
[ "or chromeos == 1', { 'conditions': [ ['chromeos==1', { 'sources/':", "'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc',", "] }], ['use_ozone == 1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ]", "[ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain',", "on host. 'type': 'static_library', # Base for host support is", "'variables': { # TODO(ajwong): Is there a way to autodetect", "[ 'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc', ], }, { 'target_name':", "# and runs a base::TestSuite. { 'target_name': 'run_all_unittests', 'type': 'static_library',", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_i18n', 'type':", "'type': 'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc',", "'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc',", "'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'defines': [ '<@(nacl_win64_defines)',", "'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h',", "{ 'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest',", "'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package':", "'type': 'shared_library', 'dependencies': [ 'base', ], 'sources': [ 'test/malloc_wrapper.cc', ],", "'../build/java.gypi' ], }, { # TODO(jbudorick): Remove this once we", "that it can be unloaded during testing. 'type': 'shared_library', 'include_dirs':", "}, }, # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [", "\"ios\" or _toolset == \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"',", "'base' }, 'conditions': [ ['OS == \"android\"', { 'dependencies': [", "However, we use our own fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker',", "# base depends on base_static. 'target_name': 'base_static', 'type': 'static_library', 'variables':", "{ # GN: //base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library', 'dependencies': [", "[ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options':", "we should do this more generally for all # targets", "'../third_party/icu/icu.gyp:icudata', ], }], ], }, { # OS != \"win\"", "{ 'Common_Base': { 'msvs_target_platform': 'x64', }, }, }, { #", "'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc',", "'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [ # base64.cc depends on modp_b64.", "[ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base', ], }, { 'type':", "'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h',", "'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc',", "'includes': [ '../build/android/java_cpp_template.gypi' ], }, { # GN: //base:base_multidex_gen 'target_name':", "'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, },", "'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc',", "'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ], }, }, }, ], }],", "'base_win64', 'type': '<(component)', 'variables': { 'base_target': 1, }, 'dependencies': [", "'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc',", "], # Specify delayload for base_win64.dll. 'msvs_settings': { 'VCLinkerTool': {", "use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ { 'action_name': 'copy_test_data',", "'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..',", "{ 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib',", "'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], }], ['desktop_linux == 1", "getting the gyp magic # per-toolset for the \"component\" variable", "'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h',", "'conditions': [ ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name':", "and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc',", "'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS == \"ios\" and", "'max', }, 'dependencies': [ 'base', ], 'export_dependent_settings': [ 'base', ],", "'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc',", "], 'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC', ], }, }], ],", "Specify delayload for components that link with base_win64.lib. 'all_dependent_settings': {", "'includes': [ '../build/apk_test.gypi' ], }, { # GN: //base:base_unittests_apk 'target_name':", "'../build/java.gypi' ], }, { # GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type':", "should not be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }], ],", "# '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use our own fork. See", "'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings should be shared with", "'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [", "], 'targets': [ { 'target_name': 'base', 'type': '<(component)', 'toolsets': ['host',", "TODO(gregoryd): direct_dependent_settings should be shared with the # 64-bit target,", "], 'sources!': [ 'file_version_info_unittest.cc', ], 'conditions': [ [ 'desktop_linux==1', {", "== \"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library',", "}, { # GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies':", "'../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'target_name': 'base', 'type': '<(component)',", "'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc',", "'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc',", "more direct string conversions on platforms with native utf8 #", "'includes': [ '../build/java.gypi' ], }, { # GN: //base/android/linker:chromium_android_linker 'target_name':", "'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base', ], },", "<(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't used on", "'..', ], 'sources': [ 'profiler/test_support_library.cc', ], }, ] }], ['os_posix==1", "'../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base', ], 'conditions': [ ['os_posix==0',", "['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS", "'target'], 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [", "# 32-bit target, but it doesn't work due to a", "crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ],", "components that link with base_win64.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool':", "is needed to trigger the dll copy step on windows.", "the \"component\" variable is hard, and we really only #", "'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..', ], 'includes': [", "fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }],", "'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc',", "'sources!': [ 'test/test_file_util_linux.cc', ], }], ['OS == \"android\"', { 'dependencies':", "it can be unloaded during testing. 'type': 'shared_library', 'include_dirs': [", "target toolset using components since that's what developers are #", "'variables': { 'chromium_code': 0, }, 'cflags!': [ '-Wextra', ], 'sources':", "'defines': [ 'USE_SYMBOLIZE', ], }, { # desktop_linux == 0", "'template_deps': [], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { #", "# (the normal build is 32 bits). { 'target_name': 'base_win64',", "'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h',", "== \"host\")', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',", "be shared with the # 64-bit target, but it doesn't", "'<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest',", "# GN: //base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'base',", "//base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none', 'variables': { 'source_file': 'android/application_status_listener.h', },", "}, 'includes': [ '../build/jni_generator.gypi' ], }, { # GN: //base:base_native_libraries_gen", "'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java',", "'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc',", "'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc',", "# Base for host support is the minimum required to", "are dependent # on tcmalloc. # TODO(wfh): crbug.com/246278 Move tcmalloc", "], # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244,", "'../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type':", "'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc',", "'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }], ], # conditions 'target_conditions': [", "'base_prefs', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', },", "'type': 'none', 'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ],", "'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc',", "}, ], }], ['OS == \"win\" and target_arch==\"ia32\"', { 'targets':", "'target'], 'variables': { 'chromium_code': 0, }, 'conditions': [ ['OS ==", "'none', }], ], }, ], 'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"',", "], }, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..',", "'includes': ['../build/android/java_cpp_template.gypi'], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type':", "//base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h',", "'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc',", "'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [", "# GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables': { 'source_file':", "], }, ], }], ['OS == \"linux\"', { 'targets': [", "{ 'include_dirs': [ '/usr/local/include', ], 'link_settings': { 'libraries': [ '-L/usr/local/lib", "'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h',", "but getting the gyp magic # per-toolset for the \"component\"", "chromeos == 0 'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ],", "], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }], ['OS == \"android\" and", "(and tests). # Note: when building for host, gyp has", "'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc',", "'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc',", "[ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude',", "'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc',", "GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h',", "}, { # GN: //base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies':", "in the multidex shadow library. crbug.com/522043 # GN: //base:base_junit_test_support 'target_name':", "'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS == \"ios\"', {", "'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ],", "'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc',", "'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc',", "crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use our own", "'base_static', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', },", "'dependencies': [ 'symbolize', 'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE', ], },", "'../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths': [ '../base/test/android/junit/', ], }, 'includes':", "'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc',", "'msvs_disabled_warnings': [ 4244, ], }, ], }], ['OS == \"win\"", "# This is the subset of files from base that", "[ '../build/java.gypi' ], }, { # GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support',", "'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc',", "4267, ], 'conditions': [ # This is needed so base_unittests", "the allocator shim, as # SecurityTest.MemoryAllocationRestriction* tests are dependent #", "int truncations. 'msvs_disabled_warnings': [ 4267, ], }], ['icu_use_data_file_flag==1', { 'defines':", "{ 'dependencies': [ 'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"', { 'dependencies':", "'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc',", "}], ], # target_conditions }, { 'target_name': 'test_support_perf', 'type': 'static_library',", "if # we're doing a component build. Specifically, we only", "per-toolset for the \"component\" variable is hard, and we really", "'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries': [ '-llog', ],", "'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ],", "'test_data_prefix': 'base', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], }],", "GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java',", "'^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable more direct string conversions on", "OS_ANDROID / ANDROID defined. 'conditions': [ ['host_os == \"mac\"', {", "}, 'dependencies': [ 'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi' ], },", "'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc',", "{ 'msvs_target_platform': 'x64', }, }, 'defines': [ '<@(nacl_win64_defines)', ], #", "'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"', { 'sources!':", "'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The crazy linker is never", "for iOS (which have been filtered out # by file", "[ ['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources':", "# GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none', 'dependencies': [ 'base_java',", "'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc',", "isn't used on iOS ['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc', ],", "'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc',", "'direct_dependent_settings': { 'defines': [ 'PERF_TEST', ], }, }, { 'target_name':", "and _toolset != \"host\"', { 'sources/': [ # Pull in", "{ 'target_name': 'test_launcher', 'toolsets': ['host'], 'type': 'executable', 'dependencies': [ 'test_support_base',", "}, ], 'conditions': [ ['test_isolation_mode != \"noop\"', { 'targets': [", "target_arch == \"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [", "'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The crazy linker is", "['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib', ],", "so that it can be unloaded during testing. 'type': 'shared_library',", "['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_apk_run', 'type':", "'$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS != \"win\"", "'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc',", "'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to", "[ '../build/android/increase_size_for_speed.gypi', ], }, # Include this target for a", "{ 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS == \"ios\"',", "'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [ ['OS == \"android\"', { 'dependencies':", "'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h',", "'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc',", "'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, ],", "[ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings", "== \"linux\"', { 'link_settings': { 'libraries': [ # We need", "'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base',", "[ ['OS == \"ios\" and _toolset != \"host\"', { 'sources/':", "== \"mac\"', { 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude',", "'base', ], 'export_dependent_settings': [ 'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ],", "and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'],", "== \"win\" and target_arch==\"ia32\"', { 'targets': [ # The base_win64", "TODO(ajwong): Is there a way to autodetect this? 'module_dir': 'base'", "'message_loop/message_loop_test.h', ], }, { 'target_name': 'base_prefs', 'type': '<(component)', 'variables': {", "# TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, ],", "'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java',", "# Pull in specific Mac files for iOS (which have", "have been filtered out # by file name rules). ['include',", "'../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java 'target_name': 'base_java', 'type':", "base_win64 target here allows us to use base for Win64", "iOS does not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test", "['OS==\"ios\"', { 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ] }], ], 'sources':", "['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], }], ['OS==\"ios\"',", "'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h',", "], 'dependencies': [ 'test_support_base', ], }, { 'type': 'none', }],", "}, { # GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables':", "'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { # GN:", "], }, { 'target_name': 'base_i18n', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors':", "'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], },", "'defines': [ '<@(nacl_win64_defines)', ], # TODO(rvargas): Bug 78117. Remove this.", "'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc', ], }], ], }], ['use_glib", "Base for host support is the minimum required to run", "}, 'includes': [ '../build/java.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar", "OS!=\"ios\"', { 'targets': [ { 'target_name': 'symbolize', 'type': 'static_library', 'toolsets':", "'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, {", "'VCLinkerTool': { 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll',", "'type': 'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!':", "'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc', ], }, { 'target_name': 'base_unittests',", "'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock',", "'variables': { 'test_data_files': [ 'test/data', ], 'test_data_prefix': 'base', }, 'includes':", "[ 'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator',", "'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc',", "//base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', },", "}], ['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc', ], }], ['OS ==", "here allows us to use base for Win64 targets #", "'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], },", "!= \"host\"', { 'sources/': [ # Pull in specific Mac", "{ # GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none', 'sources': [", "[ '../base/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ], }, {", "'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h',", "files from base that should not be used with a", "], }], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else", "modp_b64. 'base64.cc', ], 'include_dirs': [ '..', ], 'configurations': { 'Common_Base':", "hence the *_android.cc files are included but the actual code", "GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h'", "'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc',", "'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', },", "# Note: when building for host, gyp has OS ==", "to use base for Win64 targets # (the normal build", "}], ], }], ['OS == \"ios\"', { 'toolsets': ['host', 'target'],", "}], ['OS == \"linux\"', { 'targets': [ { 'target_name': 'malloc_wrapper',", "], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, },", "], 'test_data_prefix': 'base', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ],", "}, }, 'defines': [ '<@(nacl_win64_defines)', ], # TODO(rvargas): Bug 78117.", "] }], ['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"', { 'targets': [", "'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h',", "== \"linux\"', { 'dependencies': [ 'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"',", "'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java',", "'PERF_TEST', ], }, }, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0", "'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc',", "'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [ ['OS == \"android\"',", "NDK contains the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we", "]}, ], [ 'OS == \"win\" and target_arch == \"x64\"',", "'sources/': [ # Pull in specific Mac files for iOS", "'base_java', ], 'variables': { 'java_in_dir': '../base/test/android/java', }, 'includes': [ '../build/java.gypi'", "'targets': [ # The base_win64 target here allows us to", "[ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187 fix", "base_win64.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll',", "'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc',", "'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings should", "[ '../build/apk_test.gypi' ], }, ], 'conditions': [ ['test_isolation_mode != \"noop\"',", "}], ['icu_use_data_file_flag==0', { # This is needed to trigger the", "start blacklist tool. It requires further changes # to generically", "be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }], ], }, {", "[ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'test/data', ],", "'base_java_unittest_support', 'type': 'none', 'dependencies': [ 'base_java', ], 'variables': { 'java_in_dir':", "], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none',", "}, { # GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies':", "['OS == \"win\" and target_arch==\"x64\"', { 'targets': [ { 'target_name':", "'jni_gen_package': 'base', }, 'includes': [ '../build/jni_generator.gypi' ], }, { #", "{ 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',", "[ { 'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ],", "'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc',", "[ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1', { 'dependencies':", "'target_name': 'base_javatests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', ], 'variables':", "'none', 'dependencies': [ 'base_java', 'base_unittests', ], 'variables': { 'test_suite_name': 'base_unittests',", "and _toolset != \"host\"', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework',", "], 'conditions': [ [ 'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc', ],", "'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package': 'base', },", "'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc',", "doing a component build. Specifically, we only care about the", "# desktop_linux == 0 and chromeos == 0 'sources/': [", "'prefs/testing_pref_store.h', ], }, { # This is the subset of", "\"linux\"', { 'dependencies': [ 'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"', {", "'../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], }, {", "bug 36232. 'target_name': 'base_static_win64', 'type': 'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h',", "'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc',", "# SecurityTest.MemoryAllocationRestriction* tests are dependent # on tcmalloc. # TODO(wfh):", "'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc',", "== 0 'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }],", "due to a bug in gyp 'direct_dependent_settings': { 'include_dirs': [", "['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ], }], ['OS == \"android\" and", "windows. # TODO(mark): This should not be necessary. 'dependencies': [", "the iOS-meaningful portion of memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude',", "[ ['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ]}, ],", "'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h',", "['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1', { 'dependencies': [", "}, { 'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies': [ 'base', 'test_support_base',", "[ ['include', '_chromeos\\\\.cc$'] ] }], ], 'dependencies': [ 'symbolize', 'xdg_mime',", "with base_win64.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [", "'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name': 'org/chromium/base/library_loader',", "'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc',", "for clock_gettime(). '-lrt', # For 'native_library_linux.cc' '-ldl', ], }, 'conditions':", "[ '../build/jni_generator.gypi' ], }, { # GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers',", "'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc',", "'../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi' ], }, { #", "[ '/usr/local/include', ], 'link_settings': { 'libraries': [ '-L/usr/local/lib -lexecinfo', ],", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_i18n', 'type': '<(component)',", "'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'defines': [ 'BASE_WIN64',", "], }, { # GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none',", "'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi' ], }, ],", "}], ['OS == \"win\"', { 'targets': [ { # Target", "[ '../build/java.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state',", "target_conditions }, { # GN: //base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)',", "[ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [ ['OS ==", "[ ['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1',", "'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc',", "this source code is governed by a BSD-style license that", "'dependencies': [ 'base_java', 'base_java_test_support', ], 'variables': { 'java_in_dir': '../base/android/javatests', },", "1, 'optimize': 'max', }, 'dependencies': [ 'base', ], 'export_dependent_settings': [", "}, { # OS != \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ],", "_toolset == \"host\")', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',", "4244, ], }, ], }], ['OS == \"win\" and target_arch==\"x64\"',", "# GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h',", "1', { 'conditions': [ ['chromeos==1', { 'sources/': [ ['include', '_chromeos\\\\.cc$']", "# GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': { 'source_file':", "'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps': [], }, 'includes':", "'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ],", "{ 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"', {", "], }, }], ], }], ['OS == \"win\"', { #", "\"ios\"', { 'toolsets': ['host', 'target'], }], ], 'sources': [ 'test/gtest_util.cc',", "host builds (and tests). # Note: when building for host,", "== \"android\"', { 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], #", "GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'base',", "//base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support',", "size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], 'conditions': [", "'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs':", "}, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none', 'variables':", "'../build/android/java_cpp_template.gypi' ], }, { # GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type':", "[ ['component == \"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }],", "of files from base that should not be used with", "['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'],", "and OS!=\"mac\" and OS!=\"ios\"', { 'targets': [ { 'target_name': 'symbolize',", "# found in the LICENSE file. { 'variables': { 'chromium_code':", "{ 'conditions': [ ['chromeos==1', { 'sources/': [ ['include', '_chromeos\\\\.cc$'] ]", "'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc',", "'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_i18n',", "'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc',", "for components that link with base.lib. 'all_dependent_settings': { 'msvs_settings': {", "# OS != \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }], ],", "'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd):", "'symbolize', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0,", "[ '..', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', },", "'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll',", "GN: //base:base_java 'target_name': 'base_java', 'type': 'none', 'variables': { 'java_in_dir': 'android/java',", "'target_name': 'base_prefs', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max',", "'dependencies': [ 'test_support_base', ], }, { 'type': 'none', }], ],", "'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "\"host\"', { 'sources/': [ # iOS does not support FilePathWatcher.", "'../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base', ], 'conditions':", "'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc',", "'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], },", "'../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS", "desktop_linux == 0 and chromeos == 0 'sources/': [ ['exclude',", "'^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files':", "[ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc',", "{ 'toolsets': ['host', 'target'], }], ], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h',", "'nix/xdg_util_unittest.cc', ], }], ], }], ['use_glib == 1', { 'dependencies':", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'xdg_mime', 'type':", "should do this more generally for all # targets when", "== \"solaris\"', { 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ],", "# Copyright (c) 2012 The Chromium Authors. All rights reserved.", "'USE_SYMBOLIZE', ], }, { # desktop_linux == 0 and chromeos", "{ # GN: //base:base_java 'target_name': 'base_java', 'type': 'none', 'variables': {", "], }, }], ['OS != \"win\" and (OS != \"ios\"", "], 'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [", "is needed so base_unittests uses the allocator shim, as #", "of this source code is governed by a BSD-style license", "'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }],", "by file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'],", "'variables': { 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi'", "{ 'VCLinkerTool': { 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [", "], }, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen',", "'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc',", "reserved. # Use of this source code is governed by", "'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC', ], }, }], ], }],", "'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies': [ 'base', ], 'sources': [", "'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h',", "host, but getting the gyp magic # per-toolset for the", "'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc',", "'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java',", "found in the LICENSE file. { 'variables': { 'chromium_code': 1,", "'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ],", "'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc',", "runs a base::TestSuite. { 'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies': [", "# iOS does not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only", "and chromeos == 0 'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'],", "'conditions': [ ['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }],", "'^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS == \"android\"',", "'test/run_all_unittests.cc', ], }, { 'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources': [", "[ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], },", "\"win\"', { # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations.", "[ '../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate', ], }, ], }],", "}, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { # GN: //base:base_multidex_gen", "[ 'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate',", "== \"host\"', { # Always build base as a static_library", "host, gyp has OS == \"android\", # hence the *_android.cc", "GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies': [ 'base_java', ],", "[ 'cfgmgr32.lib', 'shell32.lib', ], }, }, }, ], }], ['test_isolation_mode", "'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'toolsets': ['host', 'target'],", "'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc',", "'sources': [ 'test/launcher/test_launcher_ios.cc', ], }, ], }], ['OS!=\"ios\"', { 'targets':", "{ # TODO(ajwong): Is there a way to autodetect this?", "'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN:", "'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc',", "'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ], },", "], }], ['OS == \"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc',", "{ 'targets': [ # The base_win64 target here allows us", "], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h',", "using components since that's what developers are # focusing on.", "'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'defines': [", "{ # else icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"', { 'defines':", "'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package': 'base', }, 'dependencies': [ 'android_runtime_jni_headers',", "], }, { # GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library',", "'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm',", "'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc',", "further changes # to generically support host builds (and tests).", "'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t to int", "'../base/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { # GN:", "}, 'includes': [ '../build/apk_test.gypi' ], }, ], 'conditions': [ ['test_isolation_mode", "}], ['OS == \"linux\"', { 'link_settings': { 'libraries': [ #", "{ 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1', { 'sources!':", "'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, { # This is the subset", "'../third_party/libevent/libevent.gyp:libevent' ], }], ], # conditions 'target_conditions': [ ['OS ==", "'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type':", "[ { 'target_name': 'base_unittests_run', 'type': 'none', 'dependencies': [ 'base_unittests', ],", "tcmalloc. # TODO(wfh): crbug.com/246278 Move tcmalloc specific tests into #", "OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }], #", "'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc',", "'defines': [ 'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc', ], 'conditions': [", "'i18n/streaming_utf8_validator_perftest.cc', ], }, { # GN: //base/test:test_support 'target_name': 'test_support_base', 'type':", "}, { # TODO(rvargas): Remove this when gyp finally supports", "}, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base': {", "'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'test/data', ], 'test_data_prefix': 'base',", "'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ],", "[ 'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps': [], },", "'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries':", "target_arch==\"x64\"', { 'targets': [ { 'target_name': 'base_profiler_test_support_library', # Must be", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, # Include this target", "'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [", "'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h',", "'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { #", "'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm',", "or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't used", "[ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS == \"mac\" or (OS ==", "'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h',", "'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h',", "], 'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps': [], }, 'includes': [", "[ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'], }, { #", "'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The crazy linker", "{ # GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies': [", "'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ], # target_conditions }, {", "'../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_i18n', 'type': '<(component)', 'variables': {", "\"win\" and (OS != \"ios\" or _toolset == \"host\")', {", "'optimize': 'max', }, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc',", "'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'conditions': [", "}, }, }, 'copies': [ { 'destination': '<(PRODUCT_DIR)/', 'files': [", "'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [ 'base', 'base_i18n',", "['OS == \"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }], ],", "}, 'conditions': [ ['desktop_linux == 1 or chromeos == 1',", "{ 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], }], ['OS==\"ios\"', {", "'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc',", "'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h',", "the subset of files from base that should not be", "'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc',", "[ # The base_win64 target here allows us to use", "'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name':", "'sources/': [ ['include', '_chromeos\\\\.cc$'] ] }], ], 'dependencies': [ 'symbolize',", "'base_unittests_apk.isolate', ], }, ] } ], ], }], ['OS ==", "'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc',", "[ 'test/malloc_wrapper.cc', ], } ], }], ['OS == \"android\"', {", "'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h',", "in gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'defines':", "}, { # GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies':", "}], # SyncSocket isn't used on iOS ['OS==\"ios\"', { 'sources!':", "should be shared with the # 64-bit target, but it", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, # Include this target for", "{ 'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target': 1, }, 'dependencies': [", "'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h',", "# This is needed to trigger the dll copy step", "'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc',", "'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc',", "# GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template',", "['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'],", "//base:base_java 'target_name': 'base_java', 'type': 'none', 'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes':", "['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [ { 'target_name': 'test_launcher', 'toolsets':", "'actions': [ { 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'test/data',", "'conditions': [ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'],", "'includes': [ '../build/host_jar.gypi' ] }, { # GN: //base:base_junit_tests 'target_name':", "'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [ '..',", "\"host\"', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework',", "}], ], }], ['OS == \"win\"', { # Specify delayload", "'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc',", "'base_java_library_process_type', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [", "'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h',", "'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], },", "'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h',", "unloaded during testing. 'type': 'shared_library', 'include_dirs': [ '..', ], 'sources':", "'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables':", "Note: when building for host, gyp has OS == \"android\",", "'targets': [ { # Target to manually rebuild pe_image_test.dll which", "'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc',", "'test/test_support_ios.mm', ], }], ], # target_conditions }, { 'target_name': 'test_support_perf',", "'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths': [", "'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc',", "'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm',", "'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc',", "[ 'base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], },", "[ '../build/jar_file_jni_generator.gypi' ], }, { # GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers',", "'Common_Base': { 'msvs_target_platform': 'x64', }, }, }, { # TODO(rvargas):", "!=1 'conditions': [ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines':", "and _toolset != \"host\"', { 'sources/': [ # iOS does", "{ 'target_name': 'base_profiler_test_support_library', # Must be a shared library so", "], }, 'includes': [ '../build/host_jar.gypi' ], }, { # GN:", "allocator shim, as # SecurityTest.MemoryAllocationRestriction* tests are dependent # on", "64-bit target, but it doesn't work due to a bug", "library cannot depend on base because # base depends on", "['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'],", "'../base/test/android/java', }, 'includes': [ '../build/java.gypi' ], }, { # GN:", "on tcmalloc. # TODO(wfh): crbug.com/246278 Move tcmalloc specific tests into", "'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc',", "'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class':", "{ 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, {", "int truncations. 'msvs_disabled_warnings': [ 4267, ], 'conditions': [ # This", "], 'includes': ['../build/nocompile.gypi'], 'variables': { # TODO(ajwong): Is there a", "else icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], },", "'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc',", "}], ['OS == \"win\" and target_arch==\"x64\"', { 'targets': [ {", "GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java',", "targets when building for host, but getting the gyp magic", "}, ], }], ['OS!=\"ios\"', { 'targets': [ { # GN:", "and target_arch==\"ia32\"', { 'targets': [ # The base_win64 target here", "# This is needed so base_unittests uses the allocator shim,", "'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc',", "Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib',", "run the # ssl false start blacklist tool. It requires", "== \"ios\" and _toolset != \"host\"', { 'sources/': [ #", "[ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library', ], }], ['OS ==", "{ 'type': 'none', }], ], }, ], 'conditions': [ ['OS==\"ios\"", "\"android\", # hence the *_android.cc files are included but the", "'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'],", "'none', 'dependencies': [ 'base_perftests', ], 'variables': { 'test_suite_name': 'base_perftests', },", "], 'dependencies': [ 'base_profiler_test_support_library', ], }], ['OS == \"win\"', {", "filtered out # by file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include',", "32-bit target, but it doesn't work due to a bug", "icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, {", "'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc',", "'/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib',", "or (OS == \"ios\" and _toolset == \"host\")', { 'link_settings':", "SecurityTest.MemoryAllocationRestriction* tests are dependent # on tcmalloc. # TODO(wfh): crbug.com/246278", "'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines':", "[ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "], }], ['OS == \"win\"', { # Specify delayload for", "'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm',", "}, }, }, # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings':", "# The base_win64 target here allows us to use base", "files are included but the actual code # doesn't have", "[ 'test/data', ], 'test_data_prefix': 'base', }, 'includes': [ '../build/copy_test_data_ios.gypi' ],", "], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base': { 'msvs_target_platform':", "# Only test the iOS-meaningful portion of memory and process_utils.", "{ # GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none', 'dependencies': [", "'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc',", "}], ['OS == \"android\"', { 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ],", "'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [ ['OS == \"ios\"', {", "'type': 'executable', 'sources': [ 'check_example.cc', ], 'dependencies': [ 'base', ],", "a bug in gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ],", "[ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings", "], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, #", "'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc',", "'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc',", "'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc',", "}, { # TODO(jbudorick): Remove this once we roll to", "# For 'native_library_linux.cc' '-ldl', ], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"', {", "'../build/linux/system.gyp:glib', ], }], ['OS == \"android\" and _toolset == \"host\"',", "'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc',", "'../base/test/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ] }, { #", "'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library', ], }], ['OS", "'include_dirs': [ '..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': {", "'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h',", "and target_arch == \"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies':", "'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ],", "], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate', ], },", "}], ['OS == \"ios\"', { 'toolsets': ['host', 'target'], }], ],", "'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h',", "'targets': [ { # GN: //base:check_example 'target_name': 'check_example', 'type': 'executable',", "], }, ], }], ['OS == \"win\" and target_arch==\"ia32\"', {", "It requires further changes # to generically support host builds", "shared with the # 64-bit target, but it doesn't work", "normal build is 32 bits). { 'target_name': 'base_win64', 'type': '<(component)',", "<(chromeos)==1 or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't", "'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm',", "and _toolset == \"host\"', { # Always build base as", "fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { # GN:", "'../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_message_loop_tests',", "{ # GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none', 'sources': [", "], }, }, }, ], }], ['test_isolation_mode != \"noop\"', {", "{ 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ], #", "'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc',", "is the minimum required to run the # ssl false", "{ 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS == \"ios\"', {", "'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc',", "'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables':", "'-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h',", "], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS == \"mac\" or", "'type': 'shared_library', 'include_dirs': [ '..', ], 'sources': [ 'profiler/test_support_library.cc', ],", "'jni_gen_package': 'base', }, 'dependencies': [ 'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi'", "], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib',", "bits). { 'target_name': 'base_win64', 'type': '<(component)', 'variables': { 'base_target': 1,", "], }], ['OS == \"android\"', { 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support',", "'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables': {", "'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables': {", "'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], # Specify delayload for", "'$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS == \"ios\" and _toolset", "'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc',", "shared library so that it can be unloaded during testing.", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_message_loop_tests', 'type': 'static_library',", "'../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ],", "}], ['OS == \"mac\" or (OS == \"ios\" and _toolset", "'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name':", "toolset, even if # we're doing a component build. Specifically,", "], }, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base':", "}, ], }], ['test_isolation_mode != \"noop\"', { 'targets': [ {", "'^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS == \"android\"', { 'sources/': [ ['include',", "}], ['OS == \"ios\" and _toolset != \"host\"', { 'link_settings':", "and pull # in the multidex shadow library. crbug.com/522043 #", "'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc',", "'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ] }], ], 'sources': [ 'auto_reset.h',", "'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'defines': [", "GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java',", "{ 'defines': [ 'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc', ], 'conditions':", "gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'conditions': [", "'debug/debug_on_start_win.cc', ], }], ], # Specify delayload for base_win64.dll. 'msvs_settings':", "'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc',", "'sources!': [ # base64.cc depends on modp_b64. 'base64.cc', ], 'include_dirs':", "'../build/jni_generator.gypi' ], }, { # GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type':", "\"win\" and target_arch==\"ia32\"', { 'targets': [ # The base_win64 target", "'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps': [],", "shim, as # SecurityTest.MemoryAllocationRestriction* tests are dependent # on tcmalloc.", "'base_perftests', ], 'variables': { 'test_suite_name': 'base_perftests', }, 'includes': [ '../build/apk_test.gypi'", "{ 'java_in_dir': '../base/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, {", "as a static_library for host toolset, even if # we're", "'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ],", "], 'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests',", "this once we roll to robolectric 3.0 and pull #", "[ 'sync_socket_unittest.cc', ], }], ], # target_conditions }, { #", "'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h',", "], # TODO(gregoryd): direct_dependent_settings should be shared with the #", "== \"target\"', { 'sources!': [ # iOS uses its own", "'test_support_base', 'type': 'static_library', 'dependencies': [ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest',", "native utf8 # strings ['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1 or", "shadow library. crbug.com/522043 # GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none',", "linker is never instrumented. 'cflags!': [ '-finstrument-functions', ], 'dependencies': [", "], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ], }, }, }, ],", "'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc',", "//base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies': [ 'base_java', 'base_unittests', ],", "'msvs_target_platform': 'x64', }, }, 'conditions': [ ['component == \"shared_library\"', {", "[ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines': [ 'PERF_TEST', ], },", "'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies':", "['desktop_linux == 1 or chromeos == 1', { 'defines': [", "need rt for clock_gettime(). '-lrt', # For 'native_library_linux.cc' '-ldl', ],", "to int truncations. 'msvs_disabled_warnings': [ 4267, ], }], ['icu_use_data_file_flag==1', {", "[ 'NO_TCMALLOC', ], }, }], ], }], ['OS == \"win\"',", "'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc',", "'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target': 1,", "['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'],", "'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes':", "Remove this. 'msvs_disabled_warnings': [ 4244, ], }, ], }], ['OS", "care about the # target toolset using components since that's", "[ 'base_profiler_test_support_library', ], }], ['OS == \"win\"', { 'sources!': [", "'toolsets': ['host'], 'type': 'executable', 'dependencies': [ 'test_support_base', ], 'sources': [", "'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [ # base64.cc depends on", "'x64', }, }, 'defines': [ '<@(nacl_win64_defines)', ], # TODO(rvargas): Bug", "], 'conditions': [ # This is needed so base_unittests uses", "'sources!': [ 'file_version_info_unittest.cc', ], 'conditions': [ [ 'desktop_linux==1', { 'sources':", "{ 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable more", "filtered out # by file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ],", "'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', { 'include_dirs': [ '/usr/local/include', ], 'link_settings':", "{ 'msvs_target_platform': 'x64', }, }, 'conditions': [ ['component == \"shared_library\"',", "], # target_conditions }, { # GN: //base:base_perftests 'target_name': 'base_perftests',", "['host', 'target'], 'variables': { 'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize': 'max',", "'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h',", "}, { # GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources':", "or <(chromeos)==1 or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket", "'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc',", "# Specify delayload for base.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs':", "{ 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'conditions': [ ['component", "}, }, 'conditions': [ ['component == \"shared_library\"', { 'sources!': [", "['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', { #", "['../build/android/java_cpp_template.gypi'], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none',", "'base', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], }], ['desktop_linux", "'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc',", "'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc',", "], }], ['OS == \"android\"', { 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'],", "been filtered out # by file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'],", "[ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, # TODO(rvargas):", "GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support',", "\"host\")', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework',", "[ '-llog', ], }, 'sources!': [ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1',", "[], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'], },", "[ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies':", "or _toolset == \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', {", "'base_java_application_state', 'type': 'none', 'variables': { 'source_file': 'android/application_status_listener.h', }, 'includes': [", "[ 'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2', #", "[ { # GN: //base:check_example 'target_name': 'check_example', 'type': 'executable', 'sources':", "# target toolset using components since that's what developers are", "'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc',", "0, }, 'cflags!': [ '-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h',", "'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources':", "and OS!=\"ios\"', { 'targets': [ { 'target_name': 'symbolize', 'type': 'static_library',", "{ 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }],", "'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64',", "'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths': [ '../base/test/android/junit/',", "toolset using components since that's what developers are # focusing", "is governed by a BSD-style license that can be #", "'target_name': 'pe_image_test', 'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings': {", "], 'direct_dependent_settings': { 'defines': [ 'PERF_TEST', ], }, }, {", "{ 'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [", "'..', ], }, 'conditions': [ ['desktop_linux == 1 or chromeos", "'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package': 'base',", "['OS == \"win\"', { # TODO(jschuh): crbug.com/167187 fix size_t to", "'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines': [ 'PERF_TEST', ],", "}, ], }], ['OS == \"linux\"', { 'targets': [ {", "{ 'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ],", "_toolset != \"host\"', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework',", "'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc',", "truncations. 'msvs_disabled_warnings': [ 4267, ], }], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'],", "{ 'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock',", "# SyncSocket isn't used on iOS ['OS==\"ios\"', { 'sources!': [", "], 'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], },", "}, 'copies': [ { 'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ],", "'variables': { 'src_paths': [ '../base/test/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi'", "that link with base.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': {", "'target_name': 'base_junit_tests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support',", "this. 'msvs_disabled_warnings': [ 4244, ], }, ], }], ['OS ==", "'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm',", "its own unit test launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS ==", "'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ],", "\"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }], ], }, {", "'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'toolsets':", "[ 'base_unittests_apk.isolate', ], }, ] } ], ], }], ['OS", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_message_loop_tests', 'type':", "on. In theory we should do this more generally for", "[ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, # Specify delayload", "[ ['OS == \"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }],", "{ 'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies': [ 'base', ], 'sources':", "'<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target': 1, },", "# 64-bit target, but it doesn't work due to a", "'../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name':", "], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h',", "}, }, ], }], ['test_isolation_mode != \"noop\"', { 'targets': [", "['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"', { 'sources!': [", "//base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h', },", "blacklist tool. It requires further changes # to generically support", "'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi' ], },", "for all # targets when building for host, but getting", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, ], }], ['OS ==", "Use of this source code is governed by a BSD-style", "'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies': [ 'base_java', ], 'variables': {", "Include this target for a main() function that simply instantiates", "'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], },", "0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone == 1', {", "iOS ['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc', ], }], ], #", "'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc',", "'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h',", "'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't used on iOS ['OS==\"ios\"',", "'input_java_class': 'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { #", "'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [", "static_library for host toolset, even if # we're doing a", "'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc',", "'target_conditions': [ ['OS == \"ios\"', { 'sources/': [ # Pull", "[ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc',", "'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc',", "'type': '<(component)', # TODO(gregoryd): direct_dependent_settings should be shared with the", "'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, {", "'base.gypi', ], 'targets': [ { 'target_name': 'base', 'type': '<(component)', 'toolsets':", "the # 64-bit target, but it doesn't work due to", "# ssl false start blacklist tool. It requires further changes", "'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc',", "{ # GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources': [", "'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc',", "[ '../build/apk_test.gypi' ], }, { # GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk',", "a # dynamic library. Note that this library cannot depend", "'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h',", "'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "'dependencies': [ 'base', ], }, { 'target_name': 'build_utf8_validator_tables', 'type': 'executable',", "'../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS == \"ios\" and _toolset != \"host\"',", "\"mac\"', { 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'],", "'include_dirs': [ '..', ], }, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ],", "'optimize': 'max', }, 'toolsets': ['host', 'target'], 'sources': [ 'base_switches.cc', 'base_switches.h',", "{ # GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables': {", "'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1', {", "direct_dependent_settings should be shared with the # 32-bit target, but", "has OS == \"android\", # hence the *_android.cc files are", "['OS == \"ios\"', { 'sources/': [ # Pull in specific", "# Include this target for a main() function that simply", "['use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], }, {", "tcmalloc specific tests into # their own test suite. ['win_use_allocator_shim==1',", "'type': 'none', 'dependencies': [ 'base_java', 'base_unittests', ], 'variables': { 'test_suite_name':", "'msvs_target_platform': 'x64', }, }, 'defines': [ '<@(nacl_win64_defines)', ], # TODO(rvargas):", "}, { # use_glib == 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ]", "['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'],", "'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS == \"ios\"', { 'toolsets': ['host',", "own test suite. ['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }],", "'test/launcher/test_launcher_ios.cc', ], }, ], }], ['OS!=\"ios\"', { 'targets': [ {", "'^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does", "{ # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none', 'variables': {", "], }, { 'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'], 'dependencies':", "}, { 'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables':", "'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h',", "'../build/java.gypi' ], }, { # GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type':", "}, { 'target_name': 'base_prefs', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1,", "because # base depends on base_static. 'target_name': 'base_static', 'type': 'static_library',", "'dependencies': [ 'base_java', ], 'variables': { 'java_in_dir': '../base/test/android/java', }, 'includes':", "rights reserved. # Use of this source code is governed", "support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test the iOS-meaningful portion", "\"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }], ], # conditions 'target_conditions':", "'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], },", "# GN: //base:base_javatests 'target_name': 'base_javatests', 'type': 'none', 'dependencies': [ 'base_java',", "{ # This is needed to trigger the dll copy", "# GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none', 'dependencies': [ 'base_java',", "},], ['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc',", "'sources': [ 'test/run_all_unittests.cc', ], }, { 'target_name': 'base_unittests', 'type': '<(gtest_target_type)',", "'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm',", "Specifically, we only care about the # target toolset using", "], 'conditions': [ ['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ],", "'msvs_target_platform': 'x64', }, }, }, { # TODO(rvargas): Remove this", "'base_unittests_jni_headers', 'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': {", "'msvs_disabled_warnings': [ 4244, 4996, 4267, ], 'sources': [ 'auto_reset.h', 'linux_util.cc',", "# GN: //base:check_example 'target_name': 'check_example', 'type': 'executable', 'sources': [ 'check_example.cc',", "['host', 'target'], 'variables': { 'chromium_code': 0, }, 'cflags!': [ '-Wextra',", "'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes':", "'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc',", "'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [ '..', ], 'includes':", "'setupapi.lib', ], }, }, }, 'copies': [ { 'destination': '<(PRODUCT_DIR)/',", "], }], ], # target_conditions }, { # GN: //base:base_perftests", "'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps':", "'../build/java.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type':", "'dependencies': [ # The NDK contains the crazy_linker here: #", "'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ],", "'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc',", "], # The crazy linker is never instrumented. 'cflags!': [", "], }, { 'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets': ['host', 'target'],", "'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths':", "'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS == \"mac\" or (OS", "is hard, and we really only # need base on", "== 0 and chromeos == 0 'sources/': [ ['exclude', '/xdg_user_dirs/'],", "], }, }, }, # TODO(rvargas): Bug 78117. Remove this.", "}, }], ['OS != \"win\" and (OS != \"ios\" or", "use our own fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], },", "'-finstrument-functions', ], 'dependencies': [ # The NDK contains the crazy_linker", "'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc',", "[ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS == \"ios\"', { 'toolsets':", "'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc',", "}, { # GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources':", "[ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, { 'target_name': 'base_prefs', 'type': '<(component)',", "'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc',", "[ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [ # base64.cc", "== \"android\", # hence the *_android.cc files are included but", "'jar_excluded_classes': [ '*/NativeLibraries.class' ], }, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type',", "included but the actual code # doesn't have OS_ANDROID /", "builds (and tests). # Note: when building for host, gyp", "'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib',", "# GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java',", "'../build/linux/system.gyp:glib', ], }, { # use_glib == 0 'sources!': [", "], 'variables': { 'java_in_dir': '../base/test/android/java', }, 'includes': [ '../build/java.gypi' ],", "], }], ], # Specify delayload for base_win64.dll. 'msvs_settings': {", "\"ios\" and _toolset != \"host\"', { 'sources/': [ # iOS", "'^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include',", "'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ],", "'libraries': [ '-llog', ], }, 'sources!': [ 'debug/stack_trace_posix.cc', ], }],", "'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0, }, 'conditions':", "[ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies':", "'sources': [ 'nix/xdg_util_unittest.cc', ], }], ], }], ['use_glib == 1',", "'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc',", "{ 'package_name': 'org/chromium/base/library_loader', 'template_deps': [], }, 'includes': [ '../build/android/java_cpp_template.gypi' ],", "# Specify delayload for components that link with base_win64.lib. 'all_dependent_settings':", "'2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies':", "'target_name': 'check_example', 'type': 'executable', 'sources': [ 'check_example.cc', ], 'dependencies': [", "'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h',", "'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, { # This is", "['os_bsd==1', { 'include_dirs': [ '/usr/local/include', ], 'link_settings': { 'libraries': [", "'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc',", "'link_settings': { 'libraries': [ '-L/usr/local/lib -lexecinfo', ], }, }], ['OS", "{ # GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies': [", "license that can be # found in the LICENSE file.", "}, }, # Specify delayload for components that link with", "'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, {", "'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ],", "'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [", "variable is hard, and we really only # need base", "'copy_test_data', 'variables': { 'test_data_files': [ 'test/data', ], 'test_data_prefix': 'base', },", "}, }, 'copies': [ { 'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll',", "1, 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks',", "'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc',", "'../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base', ],", "}], ['OS == \"win\"', { # Specify delayload for base.dll.", "], 'variables': { 'java_in_dir': '../base/test/android/javatests', }, 'includes': [ '../build/java.gypi' ],", "'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc',", "# per-toolset for the \"component\" variable is hard, and we", "}], ['OS == \"ios\" and _toolset != \"host\"', { 'sources/':", "'type': '<(component)', 'variables': { 'base_target': 1, }, 'dependencies': [ 'base_static_win64',", "'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc',", "link with base.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs':", "# Use of this source code is governed by a", "], }], ], }, { # OS != \"win\" 'dependencies':", "# need base on host. 'type': 'static_library', # Base for", "[ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }], ['OS ==", "'defines': [ 'PERF_TEST', ], }, }, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions':", "}, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java_test_support", "specific tests into # their own test suite. ['win_use_allocator_shim==1', {", "[ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', { 'include_dirs': [ '/usr/local/include', ],", "'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h',", "# GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package':", "\"android\" and _toolset == \"target\"', { 'dependencies': [ 'base_java', 'base_jni_headers',", "'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies': [", "['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ],", "'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc',", "out # by file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',],", "'target_name': 'test_support_base', 'type': 'static_library', 'dependencies': [ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock',", "'base', ], 'conditions': [ ['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h',", "'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc',", "'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes':", "[ '*/NativeLibraries.class' ], }, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level',", "(c) 2012 The Chromium Authors. All rights reserved. # Use", "}, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'target_name':", "Specify delayload for components that link with base.lib. 'all_dependent_settings': {", "'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ], # target_conditions }, { 'target_name':", "# base64.cc depends on modp_b64. 'base64.cc', ], 'include_dirs': [ '..',", "'$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS != \"win\" and (OS !=", "[ 'base_perftests', ], 'variables': { 'test_suite_name': 'base_perftests', }, 'includes': [", "'shared_library', 'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem':", "'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', { # This is needed to", "'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc',", "'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h',", "}, 'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings':", "'targets': [ { 'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies': [ 'base',", "'includes': [ '../build/jni_generator.gypi' ], }, { # GN: //base:android_runtime_jni_headers 'target_name':", "rebuild pe_image_test.dll which is checked into # base/test/data/pe_image. 'target_name': 'pe_image_test',", "test the iOS-meaningful portion of memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'],", "'none', 'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ], },", "'powrprof.lib', 'setupapi.lib', ], }, }, # Specify delayload for components", "'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables':", "a BSD-style license that can be # found in the", "ANDROID defined. 'conditions': [ ['host_os == \"mac\"', { 'sources/': [", "== \"mac\" or (OS == \"ios\" and _toolset == \"host\")',", "!= \"win\" and (OS != \"ios\" or _toolset == \"host\")',", "'^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ],", "[ # The NDK contains the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker'", "}, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS == \"mac\"", "'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "[ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }],", "'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc',", "[ 'check_example.cc', ], 'dependencies': [ 'base', ], }, { 'target_name':", "disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ],", "'../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets': ['host',", "'^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS == \"android\"', { 'sources/':", "'-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc',", "], }, { 'target_name': 'base_prefs', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors':", "{ 'defines': [ 'PERF_TEST', ], }, }, { 'target_name': 'test_launcher_nacl_nonsfi',", "Mac files for iOS (which have been filtered out #", "['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1', {", "}], ], # Specify delayload for base_win64.dll. 'msvs_settings': { 'VCLinkerTool':", "'isolate_file': 'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi' ], }, ], 'conditions':", "we roll to robolectric 3.0 and pull # in the", "'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h',", "'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc',", "'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc',", "'variables': { 'test_suite_name': 'base_perftests', }, 'includes': [ '../build/apk_test.gypi' ], },", "'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)',", "'includes': [ '../build/java.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name':", "{ 'action_name': 'copy_test_data', 'variables': { 'test_data_files': [ 'test/data', ], 'test_data_prefix':", "], }, { 'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies': [ 'base',", "only care about the # target toolset using components since", "], 'sources!': [ # base64.cc depends on modp_b64. 'base64.cc', ],", "the minimum required to run the # ssl false start", "'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package': 'base', }, 'dependencies': [", "{ 'base_target': 1, }, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64',", "{ 'include_dirs': [ '..', ], }, 'conditions': [ ['desktop_linux ==", "], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate', ], },", "'sources/': [ # iOS does not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'],", "'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc',", "we're doing a component build. Specifically, we only care about", "'sources': [ 'check_example.cc', ], 'dependencies': [ 'base', ], }, {", "(the normal build is 32 bits). { 'target_name': 'base_win64', 'type':", "], }, }, # Specify delayload for components that link", "{ 'include_dirs': [ '..', ], }, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION',", "'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps': [], }, 'includes': [ '../build/android/java_cpp_template.gypi'", "'allocator/allocator.gyp:allocator', ], }], ]}, ], [ 'OS == \"win\" and", "}, 'includes': [ '../build/java.gypi' ], }, { # GN: //base/android/linker:chromium_android_linker", "'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc',", "to run the # ssl false start blacklist tool. It", "# TODO(wfh): crbug.com/246278 Move tcmalloc specific tests into # their", "requires further changes # to generically support host builds (and", "on modp_b64. 'base64.cc', ], 'include_dirs': [ '..', ], 'configurations': {", "'../testing/perf/perf_test.cc' ], 'conditions': [ ['OS == \"android\"', { 'dependencies': [", "'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc',", "'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h',", "'../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }], ['OS == \"android\"", "'msvs_disabled_warnings': [ 4267, ], 'conditions': [ # This is needed", "'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c',", "'symbolize', 'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE', ], }, { #", "'dependencies': [ 'base_perftests', ], 'variables': { 'test_suite_name': 'base_perftests', }, 'includes':", "], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [", "'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java',", "and runs a base::TestSuite. { 'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies':", "], }, 'sources!': [ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', { 'include_dirs':", "'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h',", "base depends on base_static. 'target_name': 'base_static', 'type': 'static_library', 'variables': {", "['OS == \"ios\" and _toolset == \"target\"', { 'sources!': [", "'base', ], }, { 'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'],", "base as a static_library for host toolset, even if #", "shared with the # 32-bit target, but it doesn't work", "'toolsets': ['host', 'target'], }], ], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc',", "\"ios\" and _toolset == \"target\"', { 'sources!': [ # iOS", "tests into # their own test suite. ['win_use_allocator_shim==1', { 'dependencies':", "this library cannot depend on base because # base depends", "'../build/apk_test.gypi' ], }, { # GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type':", "\"component\" variable is hard, and we really only # need", "{ 'dependencies': [ '../build/linux/system.gyp:glib', ], }, { # use_glib ==", "uses the allocator shim, as # SecurityTest.MemoryAllocationRestriction* tests are dependent", "['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS ==", "{ 'src_paths': [ '../base/test/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ]", "file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS == \"ios\"", "files for iOS (which have been filtered out # by", "'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc',", "build base as a static_library for host toolset, even if", "'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc',", "'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [", "], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ], }, ], }], ['OS ==", "'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc',", "'../build/jar_file_jni_generator.gypi' ], }, { # GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type':", "1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ {", "'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ],", "'type': 'none', 'variables': { 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes':", "'copies': [ { 'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], },", "about the # target toolset using components since that's what", "{ 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library', ], }],", "'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc',", "targets # (the normal build is 32 bits). { 'target_name':", "1', { 'defines': [ 'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc', ],", "[ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java_test_support 'target_name': 'base_java_test_support',", "['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test the iOS-meaningful portion of memory", "}, }, }, ], }], ['test_isolation_mode != \"noop\"', { 'targets':", "'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc',", "'../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, { 'target_name':", "'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, # TODO(rvargas): Bug", "'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc',", "'type': 'executable', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc', ],", "], 'sources': [ 'test/malloc_wrapper.cc', ], } ], }], ['OS ==", "], 'dependencies': [ 'symbolize', 'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE', ],", "}, 'toolsets': ['host', 'target'], 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h',", "multidex shadow library. crbug.com/522043 # GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type':", "theory we should do this more generally for all #", "'-lrt', # For 'native_library_linux.cc' '-ldl', ], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"',", "or OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1', { 'defines': ['SYSTEM_NATIVE_UTF8'], }],", "'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc',", "{ 'target_name': 'symbolize', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': {", "'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc',", "'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package': 'base', }, 'includes': [ '../build/jni_generator.gypi'", "[ 'debug/debug_on_start_win.cc', ], }], ], }], ['OS==\"ios\"', { 'sources!': [", "0 and chromeos == 0 'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude',", "source code is governed by a BSD-style license that can", "], }, { # GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none',", "'target_name': 'base', 'type': '<(component)', 'toolsets': ['host', 'target'], 'variables': { 'base_target':", "'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h',", "'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc', ],", "platforms with native utf8 # strings ['OS==\"mac\" or OS==\"ios\" or", "that simply instantiates # and runs a base::TestSuite. { 'target_name':", "{ 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ]}, ], [ 'OS", "'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2', # Set", "'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }], ], }, { # OS", "\"ios\" and _toolset != \"host\"', { 'sources/': [ # Pull", "(which have been filtered out # by file name rules).", "'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ],", "build is 32 bits). { 'target_name': 'base_win64', 'type': '<(component)', 'variables':", "], 'export_dependent_settings': [ 'base', ], 'conditions': [ ['os_posix==0', { 'sources!':", "], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none',", "], }], ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name':", "[ '../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate', ], }, ] }", "], 'link_settings': { 'libraries': [ '-L/usr/local/lib -lexecinfo', ], }, }],", "\"win\" and target_arch == \"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ],", "'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc',", "[ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'sources': [", "this? 'module_dir': 'base' }, 'conditions': [ ['OS == \"android\"', {", "'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', {", "'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h',", "need base on host. 'type': 'static_library', # Base for host", "'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc',", "{ 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], # Specify delayload", "'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc',", "'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc',", "'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc',", "'../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate', ], }, ], }], ],", "'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi'", "'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc',", "'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests',", "'include_dirs': [ '..', ], 'sources': [ 'profiler/test_support_library.cc', ], }, ]", "[ { 'target_name': 'symbolize', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables':", "'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc',", "'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc',", "[ '-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c',", "[ 'allocator/allocator.gyp:allocator', ], }], ]}, ], [ 'OS == \"win\"", "'conditions': [ # This is needed so base_unittests uses the", "'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "[ '../build/linux/system.gyp:glib', ], }, { # use_glib == 0 'sources!':", "crbug.com/246278 Move tcmalloc specific tests into # their own test", "base that should not be used with a # dynamic", "copy step on windows. # TODO(mark): This should not be", "}, { # GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none', 'dependencies':", "], }], ], }], ['OS == \"android\" and _toolset ==", "'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [", "], }, ], }], ['OS == \"win\" and target_arch==\"x64\"', {", "'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm',", "[ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ], },", "}, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables':", "//base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables':", "'source_file': 'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { #", "into # base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc',", "This is needed so base_unittests uses the allocator shim, as", "], }, }, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and", "'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi' ], }, {", "}], ], }], ['OS==\"ios\"', { 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ]", "'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [", "}, }], ['OS == \"ios\" and _toolset != \"host\"', {", "['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_run', 'type':", "in the LICENSE file. { 'variables': { 'chromium_code': 1, },", "'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc',", "'link_settings': { 'libraries': [ '-llog', ], }, 'sources!': [ 'debug/stack_trace_posix.cc',", "'conditions': [ ['component == \"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ],", "'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies': [ 'base_unittests_apk', ], 'includes': [", "'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi'", "'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', #", "Specify delayload for base_win64.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [", "'conditions': [ ['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ]},", "not be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }], ], },", "'optimize': 'max', 'base_i18n_target': 1, }, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n',", "//base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest',", "own unit test launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS == \"ios\"", "'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi'", "}, { # GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources':", "] }], ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h',", "# TODO(rvargas): Remove this when gyp finally supports a clean", "[ 'base', ], 'conditions': [ ['os_posix==0', { 'sources!': [ 'test/scoped_locale.cc',", "{ # This is the subset of files from base", "], 'cflags!': [ '-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources':", "], }, }], ['OS == \"ios\" and _toolset != \"host\"',", "}, { # GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none', 'sources':", "'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc', ], }, ], }], ['OS!=\"ios\"',", "//base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' },", "'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [ # base64.cc depends", "'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ],", "that should not be used with a # dynamic library.", "}, # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244,", "'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c',", "], }, { 'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc',", "], 'conditions': [ ['test_isolation_mode != \"noop\"', { 'targets': [ {", "'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h',", "== 1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], }, { #", "], }, ], 'conditions': [ ['test_isolation_mode != \"noop\"', { 'targets':", "unit test launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS == \"ios\" and", "'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h',", "'target'], 'variables': { 'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize': 'max', },", "], 'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [ {", "1, 'optimize': 'max', 'base_i18n_target': 1, }, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "[ '../testing/android/native_test.gyp:native_test_native_code', ], }], ], }, { # GN: //base:base_i18n_perftests", "], 'sources': [ 'test/run_all_unittests.cc', ], }, { 'target_name': 'base_unittests', 'type':", "and _toolset == \"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm',", "}, 'includes': [ '../build/host_jar.gypi' ], }, { # GN: //base:base_javatests", "{ 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'toolsets': ['host', 'target'], 'sources':", "'-L/usr/local/lib -lexecinfo', ], }, }], ['OS == \"linux\"', { 'link_settings':", "'toolsets': ['host', 'target'], 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ],", "'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'sources':", "['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else icu_use_data_file_flag !=1", "'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm',", "'OS == \"win\" and target_arch == \"x64\"', { 'sources': [", "'src_paths': [ '../base/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ], },", "'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs':", "fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], 'conditions':", "[ 'test/launcher/test_launcher_ios.cc', ], }, ], }], ['OS!=\"ios\"', { 'targets': [", "'toolsets': ['host', 'target'], 'variables': { 'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize':", "\"ios\" and _toolset == \"host\")', { 'link_settings': { 'libraries': [", "[ 4244, 4996, 4267, ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h',", "}, { 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd): direct_dependent_settings should", "'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc',", "'target_name': 'base_win64', 'type': '<(component)', 'variables': { 'base_target': 1, }, 'dependencies':", "'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc',", "'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc',", "'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc',", "{ 'targets': [ { 'target_name': 'base_unittests_run', 'type': 'none', 'dependencies': [", "'type': 'static_library', 'dependencies': [ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc',", "[ '../build/android/increase_size_for_speed.gypi', ], }, ], }], ['OS == \"linux\"', {", "'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h',", "'conditions': [ ['OS == \"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ],", "'type': 'none', 'dependencies': [ 'base_perftests', ], 'variables': { 'test_suite_name': 'base_perftests',", "'<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc',", "}, ] } ], ], }], ['OS == \"win\"', {", "'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [ ['OS", "'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc',", "}, { 'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc',", "[ '..', ], 'sources': [ 'profiler/test_support_library.cc', ], }, ] }],", "'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc',", "[ 'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc', ], 'conditions': [ [", "'test/values_test_util.h', ], 'target_conditions': [ ['OS == \"ios\"', { 'sources/': [", "# GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none', 'variables': { 'source_file':", "'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, { 'target_name': 'base_prefs', 'type':", "OS!=\"mac\" and OS!=\"ios\"', { 'targets': [ { 'target_name': 'symbolize', 'type':", "[ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], },", "\"noop\"', { 'targets': [ { 'target_name': 'base_unittests_run', 'type': 'none', 'dependencies':", "'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm',", "], }, { # GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none',", "'dependencies': [ 'base', ], 'export_dependent_settings': [ 'base', ], 'defines': [", "{ 'toolsets': ['host', 'target'], }], ], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc',", "'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h',", "'^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ], }], ['OS == \"android\"", "[ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h',", "'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc',", "['OS == \"win\" and target_arch==\"ia32\"', { 'targets': [ # The", "'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc',", "In theory we should do this more generally for all", "_toolset != \"host\"', { 'sources/': [ # iOS does not", "'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS == \"win\"', {", "}, 'sources!': [ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', { 'include_dirs': [", "'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc',", "minimum required to run the # ssl false start blacklist", "[ ['host_os == \"mac\"', { 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude',", "//base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ],", "'sources!': [ 'sync_socket_unittest.cc', ], }], ], # target_conditions }, {", "even if # we're doing a component build. Specifically, we", "], }], ], }], ['use_glib == 1', { 'dependencies': [", "{ # TODO(rvargas): Remove this when gyp finally supports a", "of memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'],", "['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS == \"ios\"', { 'toolsets': ['host',", "generically support host builds (and tests). # Note: when building", "[ 'test_support_base', ], }, { 'type': 'none', }], ], },", "[ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], #", "direct_dependent_settings should be shared with the # 64-bit target, but", "is checked into # base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library', 'sources':", "'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc',", "], }], ['use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:glib', ],", "[ 'base_java', 'base_unittests', ], 'variables': { 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate',", "'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc',", "'<(component)', # TODO(gregoryd): direct_dependent_settings should be shared with the #", "# Target to manually rebuild pe_image_test.dll which is checked into", "'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h',", "by file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS ==", "}], ['OS != \"win\" and (OS != \"ios\" or _toolset", "36232. 'target_name': 'base_static_win64', 'type': 'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc',", "with base.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [", "== \"ios\"', { 'sources/': [ # Pull in specific Mac", "# GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies': [ 'base_java',", "'variables': { 'jni_gen_package': 'base', }, 'dependencies': [ 'android_runtime_jni_headers', ], 'includes':", "}, 'includes': [ '../build/java.gypi' ], }, { # TODO(jbudorick): Remove", "== \"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ],", "clock_gettime(). '-lrt', # For 'native_library_linux.cc' '-ldl', ], }, 'conditions': [", "[ 'test/test_file_util_linux.cc', ], }], ['OS == \"android\"', { 'dependencies': [", "# we're doing a component build. Specifically, we only care", "our own fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, {", "'dependencies': [ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations',", "}, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables':", "this more generally for all # targets when building for", "TODO(wfh): crbug.com/246278 Move tcmalloc specific tests into # their own", "'x64', }, }, }, { # TODO(rvargas): Remove this when", "}], ['OS == \"android\"', { 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ],", "//base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ],", "'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings should be shared with the", "The Chromium Authors. All rights reserved. # Use of this", "], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h',", "'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h',", "magic # per-toolset for the \"component\" variable is hard, and", "], },], ], 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra',", "[ '..', ], }, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations':", "focusing on. In theory we should do this more generally", "more generally for all # targets when building for host,", "[ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ],", "], 'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines': [ 'PERF_TEST',", "'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)',", "since that's what developers are # focusing on. In theory", "], 'includes': [ '../build/java.gypi' ], }, { # GN: //base:base_java_unittest_support", "}], ['OS == \"ios\" and _toolset == \"target\"', { 'sources!':", "], 'variables': { 'jni_gen_package': 'base', }, 'dependencies': [ 'android_runtime_jni_headers', ],", "}], ], }, { # GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type':", "'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [", "# target_conditions }, { 'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies': [", "during testing. 'type': 'shared_library', 'include_dirs': [ '..', ], 'sources': [", "[ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h',", "'base_multidex_gen', 'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name':", "[ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'target_name': 'base', 'type':", "[ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes',", "and target_arch==\"x64\"', { 'targets': [ { 'target_name': 'base_profiler_test_support_library', # Must", "'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc', ], 'conditions': [ [ 'desktop_linux==1',", "'target_name': 'base_i18n', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max',", "{ 'target_name': 'base_unittests_run', 'type': 'none', 'dependencies': [ 'base_unittests', ], 'includes':", "GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies': [ 'base_perftests', ],", "'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base', ], 'conditions': [ ['os_posix==0', {", "'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE', ], }, { # desktop_linux", "{ # GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources': [", "['component == \"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ],", "'none', 'variables': { 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes': [", "'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc',", "'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc',", "'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc',", "and (OS != \"ios\" or _toolset == \"host\")', { 'dependencies':", "1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS == \"linux\"',", "'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187 fix size_t", "'base_junit_test_support', 'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': {", "'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name': 'org/chromium/base/multidex',", "base.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll',", "'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "'target_name': 'base_java_library_process_type', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes':", "[ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings':", "gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'defines': [", "'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS", "{ # use_glib == 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }],", "\"ios\" and _toolset == \"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h',", "Copyright (c) 2012 The Chromium Authors. All rights reserved. #", "'../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies': [", "'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc',", "'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc',", "'none', 'variables': { 'source_file': 'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ],", "'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h',", "['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc', ], }], ], # target_conditions", "}, 'defines': [ '<@(nacl_win64_defines)', ], # TODO(rvargas): Bug 78117. Remove", "'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "}], ], 'dependencies': [ 'symbolize', 'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE',", "\"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"',", "'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc',", "], }], ['icu_use_data_file_flag==0', { # This is needed to trigger", "['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS == \"ios\" and _toolset ==", "simply instantiates # and runs a base::TestSuite. { 'target_name': 'run_all_unittests',", "'chromium_android_linker', 'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h',", "# strings ['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1', {", "[ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets':", "'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h',", "doesn't have OS_ANDROID / ANDROID defined. 'conditions': [ ['host_os ==", "{ 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll',", "'..', ], }, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [", "'^test/test_file_util_mac\\\\.cc$'], ], }], ['OS == \"ios\" and _toolset == \"target\"',", "['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines': [", "['OS == \"linux\"', { 'dependencies': [ 'malloc_wrapper', ], 'conditions': [", "'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ],", "needed so base_unittests uses the allocator shim, as # SecurityTest.MemoryAllocationRestriction*", "'message_loop/message_pump_glib_unittest.cc', ] }], ['OS == \"linux\"', { 'dependencies': [ 'malloc_wrapper',", "with the # 32-bit target, but it doesn't work due", "'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [", "truncations. 'msvs_disabled_warnings': [ 4267, ], 'conditions': [ # This is", "'base_unittests', ], 'variables': { 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes':", "], }, { # GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none',", "'../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables': { # TODO(ajwong): Is", "# GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base',", "{ # OS != \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }],", "{ 'msvs_target_platform': 'x64', }, }, }, { # TODO(rvargas): Remove", "[ 'USE_SYMBOLIZE', ], }, { # desktop_linux == 0 and", "'includes': ['../build/nocompile.gypi'], 'variables': { # TODO(ajwong): Is there a way", "{ 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework',", "'sources!': [ # iOS uses its own unit test launcher.", "step on windows. # TODO(mark): This should not be necessary.", "# Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [", "process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude',", "//base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies': [ 'base_perftests', ], 'variables':", "(OS == \"ios\" and _toolset == \"host\")', { 'link_settings': {", "'type': 'static_library', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [", "], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h',", "'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc',", "}, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0 and", "'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc',", "and _toolset == \"target\"', { 'sources!': [ # iOS uses", "on platforms with native utf8 # strings ['OS==\"mac\" or OS==\"ios\"", "required to run the # ssl false start blacklist tool.", "'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { # GN: //base:base_unittests_jni_headers 'target_name':", "'^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does not use", "\"android\"', { 'targets': [ { # GN: //base:base_jni_headers 'target_name': 'base_jni_headers',", "'executable', 'toolsets': ['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [", "'..', ], }, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': {", "'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library', ], }], ['OS == \"win\"',", "{ 'chromium_code': 0, }, 'cflags!': [ '-Wextra', ], 'sources': [", "'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [ ['OS == \"ios\"', { 'sources/':", "'target'], }], ], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc',", "to autodetect this? 'module_dir': 'base' }, 'conditions': [ ['OS ==", "manually rebuild pe_image_test.dll which is checked into # base/test/data/pe_image. 'target_name':", "'../build/copy_test_data_ios.gypi' ], }, ], }], ['desktop_linux == 1 or chromeos", "[ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc',", "\"win\"', { # Specify delayload for base.dll. 'msvs_settings': { 'VCLinkerTool':", "'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type': 'static_library',", "'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc',", "}, 'conditions': [ ['OS == \"solaris\"', { 'include_dirs': [ '/usr/gnu/include',", "never instrumented. 'cflags!': [ '-finstrument-functions', ], 'dependencies': [ # The", "'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc',", "0, }, 'conditions': [ ['OS == \"solaris\"', { 'include_dirs': [", "'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ],", "roll to robolectric 3.0 and pull # in the multidex", "# their own test suite. ['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator',", "'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc',", "# doesn't have OS_ANDROID / ANDROID defined. 'conditions': [ ['host_os", "is the subset of files from base that should not", "testing. 'type': 'shared_library', 'include_dirs': [ '..', ], 'sources': [ 'profiler/test_support_library.cc',", "], 'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines',", "['OS == \"linux\"', { 'link_settings': { 'libraries': [ # We", "!= \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_apk_run', 'type': 'none',", "], 'target_conditions': [ ['OS == \"ios\"', { 'sources/': [ #", "'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ],", "], }], ['OS == \"ios\"', { 'toolsets': ['host', 'target'], }],", "'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc',", "'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir': '../base/test/android/javatests', }, 'includes': [", "[ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h',", "}, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib',", "'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h',", "'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [", "\"solaris\"', { 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ], 'cflags':", "}, 'cflags!': [ '-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c',", "'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc',", "file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi',", "'none', 'dependencies': [ 'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources':", "_toolset == \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions':", "[ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], },", "'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc',", "['OS == \"linux\"', { 'targets': [ { 'target_name': 'malloc_wrapper', 'type':", "Move tcmalloc specific tests into # their own test suite.", "'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths':", "], 'link_settings': { 'libraries': [ '-llog', ], }, 'sources!': [", "['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ],", "'base_java_memory_pressure_level', 'type': 'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [", "# TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [", "the gyp magic # per-toolset for the \"component\" variable is", "conditions 'target_conditions': [ ['OS == \"ios\" and _toolset != \"host\"',", "}, { 'target_name': 'base_i18n', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1,", "'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc',", "}, { 'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'], 'dependencies': [", "is 32 bits). { 'target_name': 'base_win64', 'type': '<(component)', 'variables': {", "Always build base as a static_library for host toolset, even", "should not be used with a # dynamic library. Note", "'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java',", "# We need rt for clock_gettime(). '-lrt', # For 'native_library_linux.cc'", "'cflags!': [ '-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [", "'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h',", "main() function that simply instantiates # and runs a base::TestSuite.", "'test_support_base', ], }, { 'type': 'none', }], ], }, ],", "'^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS", "{ 'libraries': [ # We need rt for clock_gettime(). '-lrt',", "\"win\"', { 'targets': [ { # Target to manually rebuild", "'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi'", "], }], ['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [", "], }], ['os_bsd==1', { 'include_dirs': [ '/usr/local/include', ], 'link_settings': {", "'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target': 1, }, 'dependencies':", "== 1', { 'defines': [ 'USE_SYMBOLIZE', ], 'sources!': [ 'file_version_info_unittest.cc',", "name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'],", "[ # iOS uses its own unit test launcher. 'test/launcher/unit_test_launcher.cc',", "# conditions 'target_conditions': [ ['OS == \"ios\" and _toolset !=", "}, }], ], }], ['OS == \"win\"', { # Specify", "bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { # GN: //base:base_perftests_apk 'target_name':", "'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc',", "'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc',", "], }, { 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd): direct_dependent_settings", "strings ['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1', { 'defines':", "}, ], }], ['OS == \"win\" and target_arch==\"x64\"', { 'targets':", "# hence the *_android.cc files are included but the actual", "}, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS == \"ios\"',", "'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base', ],", "}], ['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib',", "'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base': { 'msvs_target_platform':", "portion of memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude',", "support is the minimum required to run the # ssl", "{ 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ], 'cflags': [", "building for host, but getting the gyp magic # per-toolset", "}, { # GN: //base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library', 'dependencies':", "iOS-meaningful portion of memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'],", "'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [", "'base_java', 'type': 'none', 'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class'", "'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc',", "{ 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude',", "'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "governed by a BSD-style license that can be # found", "'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h',", "}], ['OS == \"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc',", "{ 'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ],", "== \"win\" and target_arch == \"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc',", "'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines': [ 'PERF_TEST', ], }, },", "\"android\"', { 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS ==", "'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc',", "\"ios\"', { 'sources/': [ # Pull in specific Mac files", "'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'], }, { # GN: //base:base_android_java_enums_srcjar", "'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc',", "'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm',", "# GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies': [ 'base_java',", "0 'sources/': [ ['exclude', '/xdg_user_dirs/'], ['exclude', '_nss\\\\.cc$'], ], }], ['use_glib==1',", "], }, { # desktop_linux == 0 and chromeos ==", "{ 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ] }], ], 'sources': [", "'../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings should be shared with", "to robolectric 3.0 and pull # in the multidex shadow", "a main() function that simply instantiates # and runs a", "[ # Pull in specific Mac files for iOS (which", "[ 'base', ], }, { 'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets':", "], }, 'includes': [ '../build/host_jar.gypi' ] }, { # GN:", "//base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ],", "[ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc',", "[ 'PERF_TEST', ], }, }, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [", "'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [ 'base',", "['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't used on iOS ['OS==\"ios\"', {", "'../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings should be shared", "'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, 'copies':", "TODO(rvargas): Remove this when gyp finally supports a clean model.", "a shared library so that it can be unloaded during", "'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], },", "], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'defines':", "== \"win\"', { # TODO(jschuh): crbug.com/167187 fix size_t to int", "], }, }], ['OS == \"linux\"', { 'link_settings': { 'libraries':", "'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ],", "'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [ ['OS", "'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc',", "['OS == \"win\"', { 'targets': [ { # Target to", "{ 'targets': [ { 'target_name': 'symbolize', 'type': 'static_library', 'toolsets': ['host',", "and enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies':", "message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ { 'action_name': 'copy_test_data', 'variables':", "# use_glib == 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone", "gyp magic # per-toolset for the \"component\" variable is hard,", "'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc',", "'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc',", "], }, ], }], ['desktop_linux == 1 or chromeos ==", "'sources': [ 'base_unittests_apk.isolate', ], }, ] } ], ], }],", "necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }], ], }, { #", "'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }], ['OS", "{ 'target_name': 'base_win64', 'type': '<(component)', 'variables': { 'base_target': 1, },", "be # found in the LICENSE file. { 'variables': {", "], }], ['OS == \"win\" and target_arch==\"ia32\"', { 'targets': [", "}], ], }], ['OS == \"android\" and _toolset == \"target\"',", "'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC', ], }, }],", "'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc',", "['OS == \"android\"', { 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }],", "'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc',", "[ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable more direct string", "actual code # doesn't have OS_ANDROID / ANDROID defined. 'conditions':", "[ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, # Include", "'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd):", "'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..', ], 'includes':", "# iOS uses its own unit test launcher. 'test/launcher/unit_test_launcher.cc', ],", "but it doesn't work due to a bug in gyp", "with the # 64-bit target, but it doesn't work due", "'module_dir': 'base' }, 'conditions': [ ['OS == \"android\"', { 'dependencies':", "instrumented. 'cflags!': [ '-finstrument-functions', ], 'dependencies': [ # The NDK", "# target_conditions }, { # GN: //base:base_perftests 'target_name': 'base_perftests', 'type':", "'toolsets': ['host', 'target'], }], ], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n',", "['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does not use message_pump_libevent.", "], # target_conditions }, { 'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies':", "'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc',", "'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc',", "Remove this. 'msvs_disabled_warnings': [ 4244, 4996, 4267, ], 'sources': [", "'type': '<(component)', 'toolsets': ['host', 'target'], 'variables': { 'base_target': 1, 'enable_wexit_time_destructors':", "chromeos == 1', { 'defines': [ 'USE_SYMBOLIZE', ], 'sources!': [", "[ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java',", "'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h',", "not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test the iOS-meaningful", "{ 'destination': '<(PRODUCT_DIR)/', 'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies':", "# TODO(gregoryd): direct_dependent_settings should be shared with the # 64-bit", "}], ], }, { # OS != \"win\" 'dependencies': [", "{ 'target_name': 'build_utf8_validator_tables', 'type': 'executable', 'toolsets': ['host'], 'dependencies': [ 'base',", "allows us to use base for Win64 targets # (the", "], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_prefs_test_support', 'type':", "host support is the minimum required to run the #", "], }, { # GN: //base:base_java 'target_name': 'base_java', 'type': 'none',", "{ 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], },", "'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ], }, 'dependencies':", "'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [ '..', ], 'includes': [", "function that simply instantiates # and runs a base::TestSuite. {", "[ 'sync_socket.h', 'sync_socket_posix.cc', ] }], ], 'sources': [ 'auto_reset.h', 'linux_util.cc',", "[ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ],", "that this library cannot depend on base because # base", "'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name':", "'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes':", "[ ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_apk_run',", "'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc',", "'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc',", "== 1 or chromeos == 1', { 'conditions': [ ['chromeos==1',", "'target_name': 'base_java_application_state', 'type': 'none', 'variables': { 'source_file': 'android/application_status_listener.h', }, 'includes':", "[ 'test/run_all_unittests.cc', ], }, { 'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources':", "== 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone == 1',", "'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies': [ 'test_support_base', ], 'sources': [", "'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc',", "'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'conditions': [ ['component ==", "'target_name': 'test_launcher', 'toolsets': ['host'], 'type': 'executable', 'dependencies': [ 'test_support_base', ],", "'android/java/templates/ChromiumMultiDex.template', ], 'variables': { 'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [", "//base:base_javatests 'target_name': 'base_javatests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', ],", "'debug/debug_on_start_win.cc', ], }], ], }], ['OS==\"ios\"', { 'sources!': [ 'sync_socket.h',", "}, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [", "'../testing/android/native_test.gyp:native_test_native_code', ], }], ], }, { # GN: //base:base_i18n_perftests 'target_name':", "'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc',", "'variables': { 'java_in_dir': '../base/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], },", "'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc',", "{ 'libraries': [ '-llog', ], }, 'sources!': [ 'debug/stack_trace_posix.cc', ],", "'sources': [ 'profiler/test_support_library.cc', ], }, ] }], ['os_posix==1 and OS!=\"mac\"", "{ 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }], ], }, { #", "'test/histogram_tester.h', 'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc',", "{ 'targets': [ { # GN: //base:check_example 'target_name': 'check_example', 'type':", "'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc', 'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc',", "robolectric 3.0 and pull # in the multidex shadow library.", "/ ANDROID defined. 'conditions': [ ['host_os == \"mac\"', { 'sources/':", "}], ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc',", "{ 'sources!': [ 'test/test_file_util_linux.cc', ], }], ['OS == \"android\"', {", "'/usr/gnu/include/libelf', ], },], ], 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [", "}, 'conditions': [ ['OS == \"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests',", "{ # GN: //base:base_javatests 'target_name': 'base_javatests', 'type': 'none', 'dependencies': [", "}], ['test_isolation_mode != \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_run',", "['OS == \"android\" and _toolset == \"host\"', { # Always", "}, { # This is the subset of files from", "{ 'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base',", "is never instrumented. 'cflags!': [ '-finstrument-functions', ], 'dependencies': [ #", "changes # to generically support host builds (and tests). #", "See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { # GN: //base:base_perftests_apk", "support host builds (and tests). # Note: when building for", "'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h',", "_toolset == \"host\"', { # Always build base as a", "[ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package': 'base', }, 'includes':", "[ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ],", "delayload for base.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll',", "{ 'targets': [ { 'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies': [", "[ { 'target_name': 'base_profiler_test_support_library', # Must be a shared library", "'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi' ], }, ], 'conditions': [", "'base_unittests_apk_run', 'type': 'none', 'dependencies': [ 'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi',", "'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { #", "], }], ['desktop_linux == 1 or chromeos == 1', {", "to manually rebuild pe_image_test.dll which is checked into # base/test/data/pe_image.", "\"win\" and target_arch==\"x64\"', { 'targets': [ { 'target_name': 'base_profiler_test_support_library', #", "be a shared library so that it can be unloaded", "'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java_test_support 'target_name':", "components that link with base.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool':", "'includes': [ '../build/apk_test.gypi' ], }, ], 'conditions': [ ['test_isolation_mode !=", "\"host\"', { 'sources/': [ # Pull in specific Mac files", "[ 'OS == \"win\" and target_arch == \"x64\"', { 'sources':", "'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc',", "], 'dependencies': [ # The NDK contains the crazy_linker here:", "['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS == \"android\"', { 'sources/': [", "'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name': 'base_i18n_nacl_win64', 'type':", "'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h',", "'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc',", "], }, { # use_glib == 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc',", "'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h',", "'/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ], 'cflags': [ '-Wno-sign-compare', ], 'cflags!':", "'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ],", "== 1', { 'conditions': [ ['chromeos==1', { 'sources/': [ ['include',", "'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, ], }], ['OS", "not be used with a # dynamic library. Note that", "work due to a bug in gyp 'direct_dependent_settings': { 'include_dirs':", "], }, { # GN: //base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library',", "out # by file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }],", "== \"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }],", "{ 'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, {", "\"ios\"', { 'toolsets': ['host', 'target'], }], ], 'export_dependent_settings': [ 'base',", "'..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, # Include this", "'conditions': [ ['chromeos==1', { 'sources/': [ ['include', '_chromeos\\\\.cc$'] ] }],", "the # target toolset using components since that's what developers", "we really only # need base on host. 'type': 'static_library',", "'../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies': [", "'optimize': 'max', }, 'dependencies': [ 'base', ], 'export_dependent_settings': [ 'base',", "'type': 'executable', 'toolsets': ['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources':", "The NDK contains the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However,", "Only test the iOS-meaningful portion of memory and process_utils. ['exclude',", "['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'],", "['chromeos==1', { 'sources/': [ ['include', '_chromeos\\\\.cc$'] ] }], ], 'dependencies':", "'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package': 'base',", "['OS == \"win\"', { # Specify delayload for base.dll. 'msvs_settings':", "'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc',", "== \"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }], ], },", "}], ['OS!=\"ios\"', { 'targets': [ { # GN: //base:check_example 'target_name':", "'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions':", "}], ['OS == \"win\" and target_arch==\"ia32\"', { 'targets': [ #", "'chromium_code': 0, }, 'conditions': [ ['OS == \"solaris\"', { 'include_dirs':", "}], # Enable more direct string conversions on platforms with", "when gyp finally supports a clean model. # See bug", "[ ['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines':", "direct string conversions on platforms with native utf8 # strings", "}, }, { # TODO(rvargas): Remove this when gyp finally", "as # SecurityTest.MemoryAllocationRestriction* tests are dependent # on tcmalloc. #", "'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base', ], }, {", "'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm',", "bug in gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ], },", "'target'], }], ], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes':", "], }], ['OS == \"ios\" and _toolset == \"target\"', {", "{ 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else icu_use_data_file_flag !=1 'conditions':", "Must be a shared library so that it can be", "'base_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java',", "false start blacklist tool. It requires further changes # to", "'<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources':", "'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool': {", "\"linux\"', { 'targets': [ { 'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies':", "'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', { # This is", "'base_java', 'base_unittests', ], 'variables': { 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', },", "# base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc', ],", "'java_in_dir': '../base/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { #", "'variables': { 'java_in_dir': '../base/android/javatests', }, 'includes': [ '../build/java.gypi' ], },", "so base_unittests uses the allocator shim, as # SecurityTest.MemoryAllocationRestriction* tests", "# GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java',", "], }], ['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc', ], }], ['OS", "'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h',", "'variables': { 'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies':", "//base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java',", "{ 'java_in_dir': '../base/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, {", "'i18n/build_utf8_validator_tables.cc' ], }, ], }], ['OS == \"win\" and target_arch==\"ia32\"',", "# Always build base as a static_library for host toolset,", "'includes': [ '../build/jni_generator.gypi' ], }, { # GN: //base:base_native_libraries_gen 'target_name':", "trigger the dll copy step on windows. # TODO(mark): This", "'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc',", "'test_suite_name': 'base_perftests', }, 'includes': [ '../build/apk_test.gypi' ], }, { #", "'base_target': 1, }, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest',", "'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ], }, }, },", "components since that's what developers are # focusing on. In", "], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ], },", "'$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }],", "for base.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll',", "Pull in specific Mac files for iOS (which have been", "'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc',", "}], ['OS == \"android\"', { 'targets': [ { # GN:", "'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources': [", "'dependencies': [ 'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc', ], }, ],", "'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc',", "'test_data_files': [ 'test/data', ], 'test_data_prefix': 'base', }, 'includes': [ '../build/copy_test_data_ios.gypi'", "], }], ], }], ['OS==\"ios\"', { 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc',", "'check_example', 'type': 'executable', 'sources': [ 'check_example.cc', ], 'dependencies': [ 'base',", "we only care about the # target toolset using components", "'defines': [ 'NO_TCMALLOC', ], }, }], ], }], ['OS ==", "'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc',", "], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, },", "'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc',", "or chromeos == 1', { 'defines': [ 'USE_SYMBOLIZE', ], 'sources!':", "'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package': 'base', }, 'includes': [", "], 'sources': [ 'test/launcher/test_launcher_ios.cc', ], }, ], }], ['OS!=\"ios\"', {", "See bug 36232. 'target_name': 'base_static_win64', 'type': 'static_library', 'sources': [ 'base_switches.cc',", "contains the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use", "the # 32-bit target, but it doesn't work due to", "'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, 'copies': [ {", "'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, { #", "'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc',", "'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc',", "here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use our own fork.", "'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h',", "'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { #", "'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h',", "'none', 'dependencies': [ 'base_java', 'base_java_test_support', ], 'variables': { 'java_in_dir': '../base/android/javatests',", "}], ['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"', { 'targets': [ {", "'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc',", "specific Mac files for iOS (which have been filtered out", "'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc',", "'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc',", "], }], ]}, ], [ 'OS == \"win\" and target_arch", "target for a main() function that simply instantiates # and", "# focusing on. In theory we should do this more", "# TODO(mark): This should not be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata',", "a clean model. # See bug 36232. 'target_name': 'base_static_win64', 'type':", "], 'dependencies': [ 'base', ], }, { 'target_name': 'build_utf8_validator_tables', 'type':", "SyncSocket isn't used on iOS ['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc',", "tool. It requires further changes # to generically support host", "cannot depend on base because # base depends on base_static.", "] }, { # GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none',", "\"target\"', { 'sources!': [ # iOS uses its own unit", "'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc',", "'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ], }, 'includes':", "Authors. All rights reserved. # Use of this source code", "['OS == \"ios\" and _toolset != \"host\"', { 'sources/': [", "], }, { # GN: //base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none',", "== \"win\"', { 'targets': [ { # Target to manually", "[ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h',", "# TODO(ajwong): Is there a way to autodetect this? 'module_dir':", "'shared_library', 'include_dirs': [ '..', ], 'sources': [ 'profiler/test_support_library.cc', ], },", "'../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings should be shared", "'base_i18n', 'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], }, { #", "'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ],", "[], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, { # GN:", "'dependencies': [ 'base', ], 'sources': [ 'test/malloc_wrapper.cc', ], } ],", "file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include',", "'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc',", "'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc',", "'executable', 'sources': [ 'check_example.cc', ], 'dependencies': [ 'base', ], },", "{ 'include_dirs': [ '..', ], }, 'defines': [ 'BASE_WIN64', '<@(nacl_win64_defines)',", "78117. Remove this. 'msvs_disabled_warnings': [ 4244, ], }, ], }],", "], 'include_dirs': [ '..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations':", "a static_library for host toolset, even if # we're doing", "!= \"host\"', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework',", "{ # desktop_linux == 0 and chromeos == 0 'sources/':", "'file_version_info_unittest.cc', ], 'conditions': [ [ 'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc',", "'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc',", "'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, {", "'libraries': [ '-L/usr/local/lib -lexecinfo', ], }, }], ['OS == \"linux\"',", "'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh): crbug.com/167187", "delayload for components that link with base_win64.lib. 'all_dependent_settings': { 'msvs_settings':", "['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc', ], }], ['OS == \"android\"',", "This is the subset of files from base that should", "{ 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets':", "['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"',", "'shared_library', 'dependencies': [ 'base', ], 'sources': [ 'test/malloc_wrapper.cc', ], }", "'static_library', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc', ], },", "depends on modp_b64. 'base64.cc', ], 'include_dirs': [ '..', ], 'configurations':", "The crazy linker is never instrumented. 'cflags!': [ '-finstrument-functions', ],", "['OS == \"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }],", "== \"ios\" and _toolset == \"host\")', { 'link_settings': { 'libraries':", "'base_perftests', }, 'includes': [ '../build/apk_test.gypi' ], }, { # GN:", "{ 'conditions': [ ['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }],", "'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }], ['OS == \"android\" and _toolset", "['OS == \"mac\" or (OS == \"ios\" and _toolset ==", "'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings should", "are included but the actual code # doesn't have OS_ANDROID", "from base that should not be used with a #", "}], ], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h',", "GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies': [ 'base_java', 'base_unittests',", "'type': 'none', 'dependencies': [ 'base_unittests', ], 'includes': [ '../build/isolate.gypi', ],", "], 'defines': [ 'USE_SYMBOLIZE', ], }, { # desktop_linux ==", "'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java 'target_name':", "'dependencies': [ 'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [", "{ 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base', ],", "['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ { 'action_name': 'copy_test_data', 'variables': {", "on windows. # TODO(mark): This should not be necessary. 'dependencies':", "gyp has OS == \"android\", # hence the *_android.cc files", "['icu_use_data_file_flag==0', { # This is needed to trigger the dll", "'dependencies': [ 'base_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [", "used with a # dynamic library. Note that this library", "}, ], }], ['desktop_linux == 1 or chromeos == 1',", "}], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else icu_use_data_file_flag", "'dependencies': [ 'malloc_wrapper', ], 'conditions': [ ['use_allocator!=\"none\"', { 'dependencies': [", "the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use our", "], 'sources': [ 'profiler/test_support_library.cc', ], }, ] }], ['os_posix==1 and", "'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h',", "the *_android.cc files are included but the actual code #", "{ 'target_name': 'base', 'type': '<(component)', 'toolsets': ['host', 'target'], 'variables': {", "'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc',", "'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc',", "'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc',", "'^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ],", "== \"ios\"', { 'toolsets': ['host', 'target'], }], ], 'export_dependent_settings': [", "}, { 'target_name': 'base_prefs_test_support', 'type': 'static_library', 'dependencies': [ 'base', 'base_prefs',", "to generically support host builds (and tests). # Note: when", "{ 'chromium_code': 0, }, 'conditions': [ ['OS == \"solaris\"', {", "'base_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate', ],", "'test/launcher/unit_test_launcher.cc', ], }], ['OS == \"ios\" and _toolset == \"host\"',", "], 'export_dependent_settings': [ 'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources':", "size_t to int truncations. 'msvs_disabled_warnings': [ 4267, ], }], ['icu_use_data_file_flag==1',", "{ 'targets': [ { 'target_name': 'base_profiler_test_support_library', # Must be a", "'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0, }, 'cflags!': [", "'check_example.cc', ], 'dependencies': [ 'base', ], }, { 'target_name': 'build_utf8_validator_tables',", "'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, { # This is the", "'target_name': 'base_static', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max',", "{ 'test_data_files': [ 'test/data', ], 'test_data_prefix': 'base', }, 'includes': [", "'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi' ], }, { # GN:", "'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc',", "only # need base on host. 'type': 'static_library', # Base", "'export_dependent_settings': [ 'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [", "] }], ], 'dependencies': [ 'symbolize', 'xdg_mime', ], 'defines': [", "}], ['OS == \"ios\" and _toolset == \"host\"', { 'sources!':", "], }], ['OS == \"win\" and target_arch==\"x64\"', { 'targets': [", "['OS == \"solaris\"', { 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },],", "'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java',", "'type': 'none', 'variables': { 'source_file': 'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi'", "'variables': { 'source_file': 'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], },", "FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test the iOS-meaningful portion of", "[ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries': [", "'link_settings': { 'libraries': [ # We need rt for clock_gettime().", "], }, }, }, 'copies': [ { 'destination': '<(PRODUCT_DIR)/', 'files':", "], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc',", "'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc',", "'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h',", "'../build/android/increase_size_for_speed.gypi', ], }, # Include this target for a main()", "{ 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1',", "'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc',", "}], ['os_bsd==1', { 'include_dirs': [ '/usr/local/include', ], 'link_settings': { 'libraries':", "'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc',", "[ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }],", "{ # Specify delayload for base.dll. 'msvs_settings': { 'VCLinkerTool': {", "'type': 'none', }], ], }, ], 'conditions': [ ['OS==\"ios\" and", "[ { # GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none', 'sources':", "'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ], }, },", "'malloc_wrapper', 'type': 'shared_library', 'dependencies': [ 'base', ], 'sources': [ 'test/malloc_wrapper.cc',", "'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm',", "'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc',", "[ '../build/java.gypi' ], }, { # TODO(jbudorick): Remove this once", "1 or chromeos == 1', { 'conditions': [ ['chromeos==1', {", "Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, 4996, 4267, ],", "'^files/file_path_watcher_unittest\\\\.cc$'], # Only test the iOS-meaningful portion of memory and", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, ], }], ['OS == \"linux\"',", "'<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [", "['disable_nacl==0 and disable_nacl_untrusted==0 and enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources': [", "], 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'defines':", "# GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support',", "'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h',", "'../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc',", "'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc',", "{ 'jni_gen_package': 'base', }, 'includes': [ '../build/jni_generator.gypi' ], }, {", "building for host, gyp has OS == \"android\", # hence", "'targets': [ { 'target_name': 'test_launcher', 'toolsets': ['host'], 'type': 'executable', 'dependencies':", "'variables': { 'jni_gen_package': 'base', }, 'includes': [ '../build/jni_generator.gypi' ], },", "'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN:", "autodetect this? 'module_dir': 'base' }, 'conditions': [ ['OS == \"android\"',", "== \"android\"', { 'dependencies': [ 'base_unittests_jni_headers', 'base_java_unittest_support', ], }], ['OS", "], }], ], # target_conditions }, { 'target_name': 'test_support_perf', 'type':", "['OS == \"ios\" and _toolset == \"host\"', { 'sources!': [", "'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc',", "'type': 'static_library', 'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [", "'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings should be", "developers are # focusing on. In theory we should do", "['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable more direct string conversions", "'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ], 'cflags': [ '-Wno-sign-compare',", "},], ], 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ],", "], }, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS ==", "'../build/jni_generator.gypi' ], }, { # GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type':", "[ ['OS == \"win\"', { # TODO(jschuh): crbug.com/167187 fix size_t", "}, # Specify delayload for components that link with base_win64.lib.", "in specific Mac files for iOS (which have been filtered", "'conditions': [ ['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ],", "1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], }, { # use_glib", "'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java',", "that can be # found in the LICENSE file. {", "[ '<@(nacl_win64_defines)', ], # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings':", "'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target': 1, }, 'dependencies': [ 'base',", "'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc',", "['host_os == \"mac\"', { 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'], ['exclude', '^process_util_linux\\\\.cc$'],", "'type': 'none', 'dependencies': [ 'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ],", "'dependencies': [ 'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc', ], }, {", "}], ], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [", "'sync_socket.h', 'sync_socket_posix.cc', ] }], ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h',", "}, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java", "'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc',", "'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc',", "'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h',", "'base_java_test_support', ], 'variables': { 'java_in_dir': '../base/android/javatests', }, 'includes': [ '../build/java.gypi'", "'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc',", "the # ssl false start blacklist tool. It requires further", "'target_name': 'base_multidex_gen', 'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ], 'variables': {", "\"ios\" and _toolset != \"host\"', { 'link_settings': { 'libraries': [", "'static_library', # Base for host support is the minimum required", "depends on base_static. 'target_name': 'base_static', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors':", "'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [ 'test_support_base', ], }, { 'type': 'none',", "this. 'msvs_disabled_warnings': [ 4244, 4996, 4267, ], 'sources': [ 'auto_reset.h',", "'targets': [ { 'target_name': 'base_profiler_test_support_library', # Must be a shared", "{ 'link_settings': { 'libraries': [ # We need rt for", "'target_name': 'base_unittests_run', 'type': 'none', 'dependencies': [ 'base_unittests', ], 'includes': [", "into # their own test suite. ['win_use_allocator_shim==1', { 'dependencies': [", "'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h',", "a component build. Specifically, we only care about the #", "'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc',", "'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], },", "'targets': [ { 'target_name': 'base', 'type': '<(component)', 'toolsets': ['host', 'target'],", "'metrics/sample_vector_unittest.cc', 'metrics/sparse_histogram_unittest.cc', 'metrics/statistics_recorder_unittest.cc', 'native_library_unittest.cc', 'numerics/safe_numerics_unittest.cc', 'observer_list_unittest.cc', 'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc',", "'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc',", "'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [", "OS == \"android\", # hence the *_android.cc files are included", "'targets': [ { # GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type': 'none',", "'static_library', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'toolsets': ['host',", "'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name': 'base_i18n_nacl_win64',", "'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc',", "it doesn't work due to a bug in gyp 'direct_dependent_settings':", "'dependencies': [ 'base_profiler_test_support_library', ], }], ['OS == \"win\"', { 'sources!':", "{ # GN: //base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [", "'variables': { 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi', ],", "to trigger the dll copy step on windows. # TODO(mark):", "'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h', 'prefs/pref_store.cc', 'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h',", "'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc',", "], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h',", "on base_static. 'target_name': 'base_static', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1,", "[ 'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc', ], }, ], }],", "'win/pe_image.h', ], 'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "'conditions': [ ['OS == \"solaris\"', { 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf',", "'libraries': [ # We need rt for clock_gettime(). '-lrt', #", "base_unittests uses the allocator shim, as # SecurityTest.MemoryAllocationRestriction* tests are", "base.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll',", "# See bug 36232. 'target_name': 'base_static_win64', 'type': 'static_library', 'sources': [", "'base', 'type': '<(component)', 'toolsets': ['host', 'target'], 'variables': { 'base_target': 1,", "['OS == \"android\"', { 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }],", "'../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type':", "\"noop\"', { 'targets': [ { 'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies':", "'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate', ], }, ],", "'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ],", "'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc',", "by a BSD-style license that can be # found in", "'^worker_pool_linux\\\\.cc$'], ], }], ], }], ['OS == \"android\" and _toolset", "base::TestSuite. { 'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies': [ 'test_support_base', ],", "{ 'sources': [ 'nix/xdg_util_unittest.cc', ], }], ], }], ['use_glib ==", "'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], }], ['OS == \"mac\" or (OS == \"ios\"", "'base_target': 1, 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base_static',", "'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable more direct", "utf8 # strings ['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1 or <(chromecast)==1',", "[ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [ { 'target_name': 'test_launcher',", "[ '../base/test/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ] }, {", "], }], ['OS == \"mac\" or (OS == \"ios\" and", "[ '-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h',", "# The crazy linker is never instrumented. 'cflags!': [ '-finstrument-functions',", "'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm',", "}, { # else icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"', {", "'^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ], }], ['OS", "'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc',", "'dependencies': [ 'base_java', 'base_unittests', ], 'variables': { 'test_suite_name': 'base_unittests', 'isolate_file':", "'$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS != \"win\" and (OS", "really only # need base on host. 'type': 'static_library', #", "to int truncations. 'msvs_disabled_warnings': [ 4267, ], 'conditions': [ #", "'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc',", "'dependencies': [ 'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi' ], }, {", "{ 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll',", "that link with base_win64.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': {", "'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'defines': [ '<@(nacl_win64_defines)', ],", "{ 'test_suite_name': 'base_perftests', }, 'includes': [ '../build/apk_test.gypi' ], }, {", "'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS", "], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'conditions':", "'msvs_disabled_warnings': [ 4267, ], }], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], },", "'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc',", "['OS == \"android\" and _toolset == \"target\"', { 'dependencies': [", "'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], }], ['OS==\"ios\"', { 'sources!':", "[ [ 'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc', ], }], ],", "'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ],", "'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc',", "'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi' ],", "], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], }, { # GN: //base/test:test_support", "], } ], }], ['OS == \"android\"', { 'targets': [", "base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings':", "'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The crazy", "GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies': [ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib',", "{ 'libraries': [ '-L/usr/local/lib -lexecinfo', ], }, }], ['OS ==", "'bind_unittest.nc', 'bits_unittest.cc', 'build_time_unittest.cc', 'callback_helpers_unittest.cc', 'callback_list_unittest.cc', 'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc',", "'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc',", "'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h',", "conversions on platforms with native utf8 # strings ['OS==\"mac\" or", "GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template', ],", "'base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, {", "'$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS", "'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc',", "'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc',", "'base_java_test_support', 'type': 'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': {", "}, }], ['OS == \"linux\"', { 'link_settings': { 'libraries': [", "All rights reserved. # Use of this source code is", "TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, 4996, 4267,", "{ 'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC',", "'base_javatests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', ], 'variables': {", "'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc',", "'sync_socket_unittest.cc', ], }], ], # target_conditions }, { # GN:", "not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ { 'action_name':", "], }, # Include this target for a main() function", "'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h',", "{ 'variables': { 'chromium_code': 1, }, 'includes': [ '../build/win_precompile.gypi', 'base.gypi',", "'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h',", "4267, ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc',", "{ 'sources/': [ ['include', '_chromeos\\\\.cc$'] ] }], ], 'dependencies': [", "], }], ], # conditions 'target_conditions': [ ['OS == \"ios\"", "# GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none', 'sources': [ 'android/java/templates/ChromiumMultiDex.template',", "'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd): direct_dependent_settings should be shared", "'base_static_win64', 'type': 'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ],", "'include_dirs': [ '..', ], }, 'conditions': [ ['desktop_linux == 1", "4267, ], }], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { #", "!= \"host\"', { 'sources/': [ # iOS does not support", "component build. Specifically, we only care about the # target", "'test/scoped_locale.h', ], }], ['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc', ], }],", "'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc',", "'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h',", "\"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ],", "[ 4267, ], 'conditions': [ # This is needed so", "'test/data', ], 'test_data_prefix': 'base', }, 'includes': [ '../build/copy_test_data_ios.gypi' ], },", "[ ['desktop_linux == 1 or chromeos == 1', { 'conditions':", "'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc', 'i18n/time_formatting_unittest.cc', 'i18n/timezone_unittest.cc', 'id_map_unittest.cc', 'ios/crb_protocol_observers_unittest.mm', 'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc',", "32 bits). { 'target_name': 'base_win64', 'type': '<(component)', 'variables': { 'base_target':", "//base:android_runtime_jni_headers 'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'base', 'input_java_class':", "{ # GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies': [", "{ # GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none', 'dependencies': [", "'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc',", "[ ['chromeos==1', { 'sources/': [ ['include', '_chromeos\\\\.cc$'] ] }], ],", "use base for Win64 targets # (the normal build is", "'variables': { 'base_target': 1, }, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64',", "], 'sources': [ 'base_unittests.isolate', ], }, ], }], ], }", "'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h',", "}, { # GN: //base:base_java 'target_name': 'base_java', 'type': 'none', 'variables':", "'variables': { 'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], },", "'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h',", "dynamic library. Note that this library cannot depend on base", "], }, ] } ], ], }], ['OS == \"win\"',", "OS != \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }], ], #", "# TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, 4996,", "== \"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS", "GN: //base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library', 'dependencies': [ 'base', 'base_static',", "'includes': [ '../build/java.gypi' ], }, { # GN: //base:base_java_unittest_support 'target_name':", "'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc',", "[ 'file_version_info_unittest.cc', ], 'conditions': [ [ 'desktop_linux==1', { 'sources': [", "'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc',", "target here allows us to use base for Win64 targets", "4996, 4267, ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc', 'md5.h',", "_toolset == \"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ],", "Chromium Authors. All rights reserved. # Use of this source", "'shell32.lib', ], }, }, }, ], }], ['test_isolation_mode != \"noop\"',", "base on host. 'type': 'static_library', # Base for host support", "# by file name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS", "\"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS ==", "'base', ], 'sources': [ 'test/malloc_wrapper.cc', ], } ], }], ['OS", "}, { 'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest',", "'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'conditions': [ ['desktop_linux", "'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc',", "'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc',", "us to use base for Win64 targets # (the normal", "'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'],", "'base', }, 'dependencies': [ 'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi' ],", "once we roll to robolectric 3.0 and pull # in", "'package_name': 'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], },", "This should not be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ], }],", "}], ['desktop_linux == 1 or chromeos == 1', { 'defines':", "], }, { # This is the subset of files", "'base', }, 'includes': [ '../build/jni_generator.gypi' ], }, { # GN:", "tests). # Note: when building for host, gyp has OS", "'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc',", "], 'include_dirs': [ '..', ], 'configurations': { 'Common_Base': { 'msvs_target_platform':", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_prefs_test_support', 'type': 'static_library',", "used on iOS ['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc', ], }],", "1, 'optimize': 'max', }, 'toolsets': ['host', 'target'], 'sources': [ 'base_switches.cc',", "'..', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, },", "], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS", "[ '..', ], }, 'conditions': [ ['desktop_linux == 1 or", "['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ],", "'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_prefs_test_support',", "For 'native_library_linux.cc' '-ldl', ], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines':", "# Specify delayload for base_win64.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs':", "}, }, }, { # TODO(rvargas): Remove this when gyp", "GN: //base:check_example 'target_name': 'check_example', 'type': 'executable', 'sources': [ 'check_example.cc', ],", "dll copy step on windows. # TODO(mark): This should not", "'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': {", "name rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS == \"ios\" and", "], ], }], ['OS == \"win\"', { 'targets': [ {", "'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], },", "'none', 'dependencies': [ 'base_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources':", "{ 'targets': [ { # Target to manually rebuild pe_image_test.dll", "'sync_socket_posix.cc', ] }], ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc',", "'conditions': [ ['OS == \"win\"', { # TODO(jschuh): crbug.com/167187 fix", "'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support',", "[ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ], }, ],", "'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc', 'test/sequenced_worker_pool_owner.h', 'test/simple_test_clock.cc', 'test/simple_test_clock.h', 'test/simple_test_tick_clock.cc', 'test/simple_test_tick_clock.h',", "[ 'base_java', 'base_java_test_support', ], 'variables': { 'java_in_dir': '../base/android/javatests', }, 'includes':", "'base_java', 'base_java_test_support', ], 'variables': { 'java_in_dir': '../base/android/javatests', }, 'includes': [", "'static_library', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc',", "{ 'targets': [ { # GN: //base:base_jni_headers 'target_name': 'base_jni_headers', 'type':", "there a way to autodetect this? 'module_dir': 'base' }, 'conditions':", "'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], }, { # GN:", "'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base',", "can be unloaded during testing. 'type': 'shared_library', 'include_dirs': [ '..',", "*_android.cc files are included but the actual code # doesn't", "{ 'target_name': 'base_unittests', 'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc',", "], 'variables': { 'test_suite_name': 'base_perftests', }, 'includes': [ '../build/apk_test.gypi' ],", "GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none', 'variables': { 'source_file': 'android/application_status_listener.h',", "'base_perftests_apk', 'type': 'none', 'dependencies': [ 'base_perftests', ], 'variables': { 'test_suite_name':", "'../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries': [ '-llog', ], },", "'conditions': [ ['desktop_linux == 1 or chromeos == 1', {", "'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, {", "{ 'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ], }, 'dependencies': [", "'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': { 'jni_gen_package': 'base', }, 'dependencies':", "Remove this once we roll to robolectric 3.0 and pull", "'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [ { 'target_name':", "[ '..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base':", "['exclude', '^process_util_linux\\\\.cc$'], ['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }],", "/SUBSYSTEM:WINDOWS 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib',", "'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc',", "base64.cc depends on modp_b64. 'base64.cc', ], 'include_dirs': [ '..', ],", "[ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS == \"ios\" and _toolset", "{ # Always build base as a static_library for host", "}, { # GN: //base:base_javatests 'target_name': 'base_javatests', 'type': 'none', 'dependencies':", "'conditions': [ ['host_os == \"mac\"', { 'sources/': [ ['exclude', '^native_library_linux\\\\.cc$'],", "'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc',", "'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc',", "}, ] }], ['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"', { 'targets':", "'*/NativeLibraries.class' ], }, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes', 'base_java_library_process_type', 'base_java_memory_pressure_level', 'base_multidex_gen',", "'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone == 1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc',", "'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base', ], 'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ],", "], }], ['OS == \"win\"', { 'targets': [ { #", "{ 'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies': [ 'base_unittests_apk', ], 'includes':", "== \"ios\"', { 'toolsets': ['host', 'target'], }], ], 'sources': [", "}, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar", "'base_unittests_apk', 'type': 'none', 'dependencies': [ 'base_java', 'base_unittests', ], 'variables': {", "does not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], # Only test the", "\"android\"', { 'sources/': [ ['include', '^debug/proc_maps_linux_unittest\\\\.cc$'], ], }], # Enable", "and _toolset == \"host\")', { 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework',", "'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS == \"ios\" and _toolset !=", "'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies':", "'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir': '../base/test/android/javatests',", "host. 'type': 'static_library', # Base for host support is the", "'package_name': 'org/chromium/base/library_loader', 'template_deps': [], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], },", "'base_profiler_test_support_library', # Must be a shared library so that it", "# GN: //base:base_java 'target_name': 'base_java', 'type': 'none', 'variables': { 'java_in_dir':", "'type': 'static_library', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc', ],", "'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h', 'prefs/pref_notifier_impl.cc', 'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h',", "'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS == \"linux\"', { 'dependencies':", "'debug/stack_trace_unittest.cc', 'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc',", "[ '../build/java.gypi' ], }, { # GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker',", "'../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions':", "'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN:", "[ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"',", "[ '..', ], }, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs':", "], }, { 'type': 'none', }], ], }, ], 'conditions':", "'test/icu_test_util.cc', 'test/icu_test_util.h', 'test/ios/wait_util.h', 'test/ios/wait_util.mm', 'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h',", "'base_i18n', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', 'base_i18n_target':", "'../testing/gtest.gyp:gtest', ], 'sources': [ 'test/run_all_perftests.cc', ], 'direct_dependent_settings': { 'defines': [", "code # doesn't have OS_ANDROID / ANDROID defined. 'conditions': [", "to a bug in gyp 'direct_dependent_settings': { 'include_dirs': [ '..',", "'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc', 'at_exit_unittest.cc', 'atomicops_unittest.cc', 'barrier_closure_unittest.cc', 'base64_unittest.cc', 'base64url_unittest.cc', 'big_endian_unittest.cc', 'bind_unittest.cc', 'bind_unittest.nc',", "'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc',", "{ 'sources/': [ # Pull in specific Mac files for", "'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc', 'cpu_unittest.cc', 'debug/crash_logging_unittest.cc', 'debug/debugger_unittest.cc', 'debug/leak_tracker_unittest.cc', 'debug/proc_maps_linux_unittest.cc', 'debug/stack_trace_unittest.cc',", "'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ], }, 'dependencies': [ 'base_java_application_state', 'base_java_library_load_from_apk_status_codes',", "'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc', 'metrics/histogram_unittest.cc', 'metrics/metrics_hashes_unittest.cc', 'metrics/sample_map_unittest.cc',", "[ ['OS == \"ios\"', { 'sources/': [ # Pull in", "code is governed by a BSD-style license that can be", "'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool': { 'SubSystem': '2',", "'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ], }, ], }],", "'NO_TCMALLOC', ], }, }], ], }], ['OS == \"win\"', {", "'xdg_mime', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0,", "'../build/host_jar.gypi' ], }, { # GN: //base:base_javatests 'target_name': 'base_javatests', 'type':", "'target_name': 'base_java_test_support', 'type': 'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables':", "'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc',", "'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0, }, 'cflags!':", "], 'variables': { 'src_paths': [ '../base/test/android/junit/', ], }, 'includes': [", "gyp finally supports a clean model. # See bug 36232.", "{ 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd): direct_dependent_settings should be", "iOS (which have been filtered out # by file name", "'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc', 'containers/stack_container_unittest.cc',", "'win/win_util_unittest.cc', 'win/wrapped_window_proc_unittest.cc', '<@(trace_event_test_sources)', ], 'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs',", "'<(component)', 'variables': { 'base_target': 1, }, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64',", "], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h',", "], }, { # GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen', 'type': 'none',", "{ 'target_name': 'base_i18n', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize':", "'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, #", "'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc',", "[ ['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], }],", "}, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none', 'variables':", "'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir': '../base/test/android/javatests', },", "'type': 'none', 'dependencies': [ 'base_java', ], 'variables': { 'java_in_dir': '../base/test/android/java',", "[ { 'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies': [ 'base_unittests_apk', ],", "}, { # GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type': 'none', 'dependencies':", "['host'], 'type': 'executable', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc',", "} ], ], }], ['OS == \"win\"', { 'targets': [", "'--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'], }, { # GN:", "# targets when building for host, but getting the gyp", "Is there a way to autodetect this? 'module_dir': 'base' },", "'^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], #", "'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc', 'test/test_switches.h', 'test/test_timeouts.cc', 'test/test_timeouts.h', 'test/test_ui_thread_android.cc', 'test/test_ui_thread_android.h', 'test/thread_test_helper.cc', 'test/thread_test_helper.h',", "'base_unittests_run', 'type': 'none', 'dependencies': [ 'base_unittests', ], 'includes': [ '../build/isolate.gypi',", "crbug.com/522043 # GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies': [", "[ 'base', ], 'export_dependent_settings': [ 'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION',", "a base::TestSuite. { 'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies': [ 'test_support_base',", "], }, ], }], ['OS!=\"ios\"', { 'targets': [ { #", "launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS == \"ios\" and _toolset ==", "for host toolset, even if # we're doing a component", "}], ['OS == \"linux\"', { 'dependencies': [ 'malloc_wrapper', ], 'conditions':", "'os_compat_android_unittest.cc', 'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc',", "The base_win64 target here allows us to use base for", "['OS == \"ios\" and _toolset != \"host\"', { 'link_settings': {", "'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ]}, ], [ 'OS ==", "We need rt for clock_gettime(). '-lrt', # For 'native_library_linux.cc' '-ldl',", "'../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries': [ '-llog', ], }, 'sources!':", "'type': '<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [", "'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, { 'target_name': 'base_prefs', 'type': '<(component)', 'variables':", "], 'conditions': [ ['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }],", "== \"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], #", "and _toolset == \"target\"', { 'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features',", "# in the multidex shadow library. crbug.com/522043 # GN: //base:base_junit_test_support", "'includes': [ '../build/win_precompile.gypi', 'base.gypi', ], 'targets': [ { 'target_name': 'base',", "'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc', 'test/test_simple_task_runner.h', 'test/test_suite.cc', 'test/test_suite.h', 'test/test_support_android.cc', 'test/test_support_android.h', 'test/test_support_ios.h', 'test/test_support_ios.mm', 'test/test_switches.cc',", "[ 'i18n/build_utf8_validator_tables.cc' ], }, ], }], ['OS == \"win\" and", "on base because # base depends on base_static. 'target_name': 'base_static',", "'<@(trace_event_test_sources)', ], 'dependencies': [ 'base', 'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static',", "'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h',", "that's what developers are # focusing on. In theory we", "'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h',", "== 1 or chromeos == 1', { 'defines': [ 'USE_SYMBOLIZE',", "}, # Specify delayload for components that link with base.lib.", "'cfgmgr32.lib', 'shell32.lib', ], }, }, }, ], }], ['test_isolation_mode !=", "\"host\"', { # Always build base as a static_library for", "], 'sources': [ 'base_unittests_apk.isolate', ], }, ] } ], ],", "'cflags!': [ '-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h',", "'sources!': [ 'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1', { 'sources!': [", "{ 'java_in_dir': '../base/test/android/java', }, 'includes': [ '../build/java.gypi' ], }, {", "'profiler/test_support_library.cc', ], }, ] }], ['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"',", "'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h',", "['host', 'target'], 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs':", "'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc',", "'$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS != \"win\" and", "'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc',", "'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc',", "], }, 'conditions': [ ['desktop_linux == 1 or chromeos ==", "'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n', 'base',", "'target_name': 'base_unittests_apk', 'type': 'none', 'dependencies': [ 'base_java', 'base_unittests', ], 'variables':", "'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi',", "the actual code # doesn't have OS_ANDROID / ANDROID defined.", "pull # in the multidex shadow library. crbug.com/522043 # GN:", "[ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, 'copies': [", "== \"ios\" and _toolset != \"host\"', { 'link_settings': { 'libraries':", "'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc',", "'include_dirs': [ '/usr/local/include', ], 'link_settings': { 'libraries': [ '-L/usr/local/lib -lexecinfo',", "'../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi' ], }, { # GN:", "'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc',", "['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'], }, { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS ==", "[ '-L/usr/local/lib -lexecinfo', ], }, }], ['OS == \"linux\"', {", "[ '../build/android/java_cpp_template.gypi' ], }, { # GN: //base:base_multidex_gen 'target_name': 'base_multidex_gen',", "384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { # GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk',", "['OS == \"android\"', { 'targets': [ { # GN: //base:base_jni_headers", "target, but it doesn't work due to a bug in", "'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc', 'test/scoped_locale.h', 'test/scoped_path_override.cc', 'test/scoped_path_override.h', 'test/sequenced_task_runner_test_template.cc', 'test/sequenced_task_runner_test_template.h', 'test/sequenced_worker_pool_owner.cc',", "'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, },", "'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, { # GN:", "'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_load_from_apk_status_codes.h' }, 'includes':", "build. Specifically, we only care about the # target toolset", "'prefs/pref_notifier_impl.h', 'prefs/pref_observer.h', 'prefs/pref_registry.cc', 'prefs/pref_registry.h', 'prefs/pref_registry_simple.cc', 'prefs/pref_registry_simple.h', 'prefs/pref_service.cc', 'prefs/pref_service.h', 'prefs/pref_service_factory.cc', 'prefs/pref_service_factory.h',", "# Must be a shared library so that it can", "[ 'base_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests.isolate',", "[ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level',", "[ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone == 1', { 'sources!': [", "# Specify delayload for components that link with base.lib. 'all_dependent_settings':", "'include_dirs': [ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, {", "], 'conditions': [ ['OS == \"win\"', { # TODO(jschuh): crbug.com/167187", "'include_dirs': [ '..', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64',", "# else icu_use_data_file_flag !=1 'conditions': [ ['OS==\"win\"', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_SHARED'],", "}, 'includes': [ '../build/apk_test.gypi' ], }, { # GN: //base:base_unittests_apk", "target_conditions }, { 'target_name': 'test_support_perf', 'type': 'static_library', 'dependencies': [ 'base',", "'test/test_file_util_linux.cc', ], }], ['OS == \"android\"', { 'dependencies': [ 'base_unittests_jni_headers',", "can be # found in the LICENSE file. { 'variables':", "'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [ ['OS == \"ios\"',", "'variables': { 'java_in_dir': '../base/test/android/java', }, 'includes': [ '../build/java.gypi' ], },", "# iOS does not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions':", "\"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ], }], ], # Specify", "'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h',", "rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include',", "78117. Remove this. 'msvs_disabled_warnings': [ 4244, 4996, 4267, ], 'sources':", "[ ['OS == \"solaris\"', { 'include_dirs': [ '/usr/gnu/include', '/usr/gnu/include/libelf', ],", "== \"win\"', { # Specify delayload for base.dll. 'msvs_settings': {", "'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, }, {", "'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc',", "'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes':", "with a # dynamic library. Note that this library cannot", "], }], ['OS == \"ios\" and _toolset != \"host\"', {", "'variables': { 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi'", "{ # Target to manually rebuild pe_image_test.dll which is checked", "{ 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies':", "1 or chromeos == 1', { 'defines': [ 'USE_SYMBOLIZE', ],", "], }, { # OS != \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent'", "{ 'jni_gen_package': 'base', }, 'dependencies': [ 'android_runtime_jni_headers', ], 'includes': [", "'prefs/pref_store.h', 'prefs/pref_value_map.cc', 'prefs/pref_value_map.h', 'prefs/pref_value_store.cc', 'prefs/pref_value_store.h', 'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h',", "'run_all_unittests', 'type': 'static_library', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/run_all_unittests.cc',", "'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ], 'conditions': [ ['OS == \"android\"', {", "[ '../third_party/icu/icu.gyp:icudata', ], }], ], }, { # OS !=", "'setupapi.lib', ], }, }, }, # TODO(rvargas): Bug 78117. Remove", "# GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none', 'variables': { 'source_file':", "GN: //base:base_perftests 'target_name': 'base_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base',", "[ 4267, ], }], ['icu_use_data_file_flag==1', { 'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, {", "with native utf8 # strings ['OS==\"mac\" or OS==\"ios\" or <(chromeos)==1", "], 'includes': [ '../build/jni_generator.gypi' ], }, { # GN: //base:android_runtime_jni_headers", "[ '../build/copy_test_data_ios.gypi' ], }, ], }], ['desktop_linux == 1 or", "{ 'sources!': [ 'sync_socket_unittest.cc', ], }], ], # target_conditions },", "\"linux\"', { 'link_settings': { 'libraries': [ # We need rt", "!= \"ios\" or _toolset == \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },],", "'../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type':", "[ ['OS == \"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ],", "], 'sources': [ 'message_loop/message_loop_test.cc', 'message_loop/message_loop_test.h', ], }, { 'target_name': 'base_prefs',", "'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h',", "'max', 'base_i18n_target': 1, }, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc',", "Target to manually rebuild pe_image_test.dll which is checked into #", "delayload for base_win64.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll',", "'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': { 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/',", "'base64.cc', ], 'include_dirs': [ '..', ], 'configurations': { 'Common_Base': {", "'variables': { 'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base',", "'org/chromium/base/multidex', 'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes':", "link with base_win64.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs':", "[ { 'target_name': 'test_launcher', 'toolsets': ['host'], 'type': 'executable', 'dependencies': [", "], 'variables': { 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes': [", "'$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS == \"ios\" and", "but the actual code # doesn't have OS_ANDROID / ANDROID", "{ 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ],", "'base_unittests', 'type': '<(gtest_target_type)', 'sources': [ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc',", "'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc',", "'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h',", "'pe_image_test', 'type': 'shared_library', 'sources': [ 'win/pe_image_test.cc', ], 'msvs_settings': { 'VCLinkerTool':", "[ '../third_party/libevent/libevent.gyp:libevent' ], }], ], # conditions 'target_conditions': [ ['OS", "'..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'xdg_mime',", "BSD-style license that can be # found in the LICENSE", "], [ 'OS == \"win\" and target_arch == \"x64\"', {", "'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'toolsets': ['host', 'target'], 'sources': [", "'base_java_unittest_support', ], }], ['OS == \"ios\"', { 'toolsets': ['host', 'target'],", "'test/malloc_wrapper.cc', ], } ], }], ['OS == \"android\"', { 'targets':", "'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc', 'containers/small_map_unittest.cc',", "'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0, },", "'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc',", "'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm',", "'template_deps': [], 'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'],", "'java_in_dir': '../base/test/android/java', }, 'includes': [ '../build/java.gypi' ], }, { #", "base_static. 'target_name': 'base_static', 'type': 'static_library', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize':", "[ 'base', ], 'sources': [ 'test/malloc_wrapper.cc', ], } ], }],", "in gyp 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'conditions':", "'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps': [],", "be used with a # dynamic library. Note that this", "//base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest',", "string conversions on platforms with native utf8 # strings ['OS==\"mac\"", "}], ['use_ozone == 1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }],", "[ 4244, ], }, ], }], ['OS == \"win\" and", "'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc',", "This is needed to trigger the dll copy step on", "<reponame>eval1749/elang # Copyright (c) 2012 The Chromium Authors. All rights", "{ 'targets': [ { 'target_name': 'test_launcher', 'toolsets': ['host'], 'type': 'executable',", "'win/pe_image.h', ], 'sources!': [ # base64.cc depends on modp_b64. 'base64.cc',", "{ 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'defines': [ '<@(nacl_win64_defines)',", "}], ['OS == \"android\" and _toolset == \"target\"', { 'dependencies':", "way to autodetect this? 'module_dir': 'base' }, 'conditions': [ ['OS", "delayload for components that link with base.lib. 'all_dependent_settings': { 'msvs_settings':", "['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }],", "], }], ['OS == \"ios\" and _toolset == \"host\"', {", "the dll copy step on windows. # TODO(mark): This should", "'../build/apk_test.gypi' ], }, ], 'conditions': [ ['test_isolation_mode != \"noop\"', {", "'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc' ],", "be unloaded during testing. 'type': 'shared_library', 'include_dirs': [ '..', ],", "], }, { # GN: //base:base_javatests 'target_name': 'base_javatests', 'type': 'none',", "}, 'includes': [ '../build/host_jar.gypi' ] }, { # GN: //base:base_junit_tests", "# to generically support host builds (and tests). # Note:", "pe_image_test.dll which is checked into # base/test/data/pe_image. 'target_name': 'pe_image_test', 'type':", "[ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS", "== 1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS ==", "'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)',", "], }], ['OS == \"android\"', { 'targets': [ { #", "'files/file_unittest.cc', 'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc',", "}], ['OS == \"android\" and _toolset == \"host\"', { #", "GN: //base:base_javatests 'target_name': 'base_javatests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support',", "'base_message_loop_tests', 'type': 'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ], 'sources': [", "for Win64 targets # (the normal build is 32 bits).", "'test/thread_test_helper.h', 'test/trace_event_analyzer.cc', 'test/trace_event_analyzer.h', 'test/trace_to_file.cc', 'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ],", "'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "], 'variables': { 'java_in_dir': '../base/android/javatests', }, 'includes': [ '../build/java.gypi' ],", "[ 'android/application_status_listener_unittest.cc', 'android/content_uri_utils_unittest.cc', 'android/jni_android_unittest.cc', 'android/jni_array_unittest.cc', 'android/jni_string_unittest.cc', 'android/library_loader/library_prefetcher_unittest.cc', 'android/path_utils_unittest.cc', 'android/scoped_java_ref_unittest.cc', 'android/sys_utils_unittest.cc',", "Enable more direct string conversions on platforms with native utf8", "'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc',", "'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc', 'mac/foundation_util_unittest.mm',", "# dynamic library. Note that this library cannot depend on", "enable_nacl_nonsfi_test==1', { 'type': 'static_library', 'sources': [ 'test/launcher/test_launcher_nacl_nonsfi.cc', ], 'dependencies': [", "{ 'targets': [ { 'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies': [", "Remove this when gyp finally supports a clean model. #", "for a main() function that simply instantiates # and runs", "'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc',", "we use our own fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ],", "'third_party/xdg_user_dirs/xdg_user_dir_lookup.h', ], }, { 'target_name': 'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd):", "{ # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables': {", "'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base', ], 'export_dependent_settings':", "}], ['use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], },", "[ 'base', ], 'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h',", "'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'sources!': [ #", "['host', 'target'], 'variables': { 'chromium_code': 0, }, 'conditions': [ ['OS", "'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone == 1', { 'sources!':", "[ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS ==", "{ 'defines': [ 'NO_TCMALLOC', ], }, }], ], }], ['OS", "{ 'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework',", "'targets': [ { 'target_name': 'base_unittests_run', 'type': 'none', 'dependencies': [ 'base_unittests',", "'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc', 'android/linker/legacy_linker_jni.h', 'android/linker/linker_jni.cc', 'android/linker/linker_jni.h', 'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The", "== \"android\" and _toolset == \"target\"', { 'dependencies': [ 'base_java',", "], }], ['OS==\"ios\"', { 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ] }],", "TODO(gregoryd): direct_dependent_settings should be shared with the # 32-bit target,", "'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc',", "tests are dependent # on tcmalloc. # TODO(wfh): crbug.com/246278 Move", "'<@(nacl_win64_defines)', ], # TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [", "[ 'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc', ], }], ], }],", "{ 'main_class': 'org.chromium.testing.local.JunitTestMain', 'src_paths': [ '../base/android/junit/', ], }, 'includes': [", "'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c',", "[ # iOS does not support FilePathWatcher. ['exclude', '^files/file_path_watcher_unittest\\\\.cc$'], #", "'test/launcher/test_launcher.cc', 'test/launcher/test_launcher.h', 'test/launcher/test_result.cc', 'test/launcher/test_result.h', 'test/launcher/test_results_tracker.cc', 'test/launcher/test_results_tracker.h', 'test/launcher/unit_test_launcher.cc', 'test/launcher/unit_test_launcher.h', 'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h',", "'prefs/json_pref_store.cc', 'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h',", "chromeos == 1', { 'conditions': [ ['chromeos==1', { 'sources/': [", "TODO(mark): This should not be necessary. 'dependencies': [ '../third_party/icu/icu.gyp:icudata', ],", "'export_dependent_settings': [ 'base', ], 'conditions': [ ['os_posix==0', { 'sources!': [", "], 'sources': [ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c',", "'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java', ], 'variables': {", "}, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, { # GN: //base:base_unittests_jni_headers", "# The NDK contains the crazy_linker here: # '<(android_ndk_root)/crazy_linker.gyp:crazy_linker' #", "], # conditions 'target_conditions': [ ['OS == \"ios\" and _toolset", "'base_i18n', 'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest',", "'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc',", "'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c', 'third_party/xdg_mime/xdgmimeicon.h', 'third_party/xdg_mime/xdgmimeint.c', 'third_party/xdg_mime/xdgmimeint.h', 'third_party/xdg_mime/xdgmimemagic.c', 'third_party/xdg_mime/xdgmimemagic.h', 'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h',", "\"target\"', { 'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings':", "[ { 'target_name': 'base', 'type': '<(component)', 'toolsets': ['host', 'target'], 'variables':", "(OS != \"ios\" or _toolset == \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'],", "'executable', 'dependencies': [ 'test_support_base', ], 'sources': [ 'test/launcher/test_launcher_ios.cc', ], },", "], }, { # GN: //base:base_unittests_apk 'target_name': 'base_unittests_apk', 'type': 'none',", "base because # base depends on base_static. 'target_name': 'base_static', 'type':", "'callback_list_unittest.nc', 'callback_unittest.cc', 'callback_unittest.nc', 'cancelable_callback_unittest.cc', 'command_line_unittest.cc', 'containers/adapters_unittest.cc', 'containers/hash_tables_unittest.cc', 'containers/linked_list_unittest.cc', 'containers/mru_cache_unittest.cc', 'containers/scoped_ptr_hash_map_unittest.cc',", "for components that link with base_win64.lib. 'all_dependent_settings': { 'msvs_settings': {", "[ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', },", "'rand_util_unittest.cc', 'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc',", "# GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies': [ 'base_perftests',", "defined. 'conditions': [ ['host_os == \"mac\"', { 'sources/': [ ['exclude',", "'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java',", "'target_name': 'base_java_memory_pressure_level', 'type': 'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h', }, 'includes':", "'base_java_memory_pressure_level', 'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi' ],", "{ 'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': {", "{ 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code', ], }], ['OS == \"ios\"", "TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [ 4267,", "}, { 'type': 'none', }], ], }, ], 'conditions': [", "== \"win\" and target_arch==\"x64\"', { 'targets': [ { 'target_name': 'base_profiler_test_support_library',", "'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc',", "'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings': {", "'sources': [ 'test/malloc_wrapper.cc', ], } ], }], ['OS == \"android\"',", "'conditions': [ ['OS == \"android\"', { 'dependencies': [ 'android/jni_generator/jni_generator.gyp:jni_generator_tests', '../testing/android/native_test.gyp:native_test_native_code',", "], }, { # TODO(jbudorick): Remove this once we roll", "'target_conditions': [ ['OS == \"ios\" and _toolset != \"host\"', {", "own fork. See bug 384700. '../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { #", "{ # GN: //base:base_unittests_jni_headers 'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources': [", "'^process/process_util_unittest_ios\\\\.cc$'], # iOS does not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ],", "'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc', 'third_party/xdg_user_dirs/xdg_user_dir_lookup.cc',", "'files/file_util_proxy_unittest.cc', 'files/file_util_unittest.cc', 'files/important_file_writer_unittest.cc', 'files/memory_mapped_file_unittest.cc', 'files/scoped_temp_dir_unittest.cc', 'gmock_unittest.cc', 'guid_unittest.cc', 'hash_unittest.cc', 'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc',", "[ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h', ], 'include_dirs': [ '..', ],", "}, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], #", "_toolset == \"target\"', { 'sources!': [ # iOS uses its", "{ 'source_file': 'android/library_loader/library_loader_hooks.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, {", "clean model. # See bug 36232. 'target_name': 'base_static_win64', 'type': 'static_library',", "library. crbug.com/522043 # GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support', 'type': 'none', 'dependencies':", "[ 'BASE_WIN64', '<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64',", "'^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include', '^mac/objc_property_releaser_unittest\\\\.mm$'], ['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ],", "['component==\"shared_library\"', { 'conditions': [ ['OS==\"win\"', { 'sources!': [ 'debug/debug_on_start_win.cc', ],", "{ 'defines': ['SYSTEM_NATIVE_UTF8'], }], # SyncSocket isn't used on iOS", "\"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], #", "], }, 'includes': ['../build/android/java_cpp_template.gypi'], }, { # GN: //base:base_android_java_enums_srcjar 'target_name':", "'^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does not use message_pump_libevent. ['exclude',", "'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc',", "'enable_wexit_time_destructors': 1, 'optimize': 'max', }, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod',", "'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ], 'sources': [ 'third_party/symbolize/config.h', 'third_party/symbolize/demangle.cc', 'third_party/symbolize/demangle.h', 'third_party/symbolize/glog/logging.h',", "'sources!': [ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', { 'include_dirs': [ '/usr/local/include',", "Win64 targets # (the normal build is 32 bits). {", "[ 'nix/xdg_util_unittest.cc', ], }], ], }], ['use_glib == 1', {", "'$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS == \"ios\"", "'android_runtime_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class', },", "{ 'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': {", "finally supports a clean model. # See bug 36232. 'target_name':", "\"x64\"', { 'sources': [ 'profiler/win32_stack_frame_unwinder_unittest.cc', ], 'dependencies': [ 'base_profiler_test_support_library', ],", "== \"ios\" and _toolset == \"host\"', { 'sources!': [ 'test/launcher/unit_test_launcher_ios.cc',", "[ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS == \"linux\"', { 'dependencies': [", "'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc',", "'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS == \"win\"',", "'target_name': 'base_perftests_apk', 'type': 'none', 'dependencies': [ 'base_perftests', ], 'variables': {", "\"android\" and _toolset == \"host\"', { # Always build base", "{ 'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings': [ '../build/linux/system.gyp:glib', ], }],", "{ 'target_name': 'base_prefs', 'type': '<(component)', 'variables': { 'enable_wexit_time_destructors': 1, 'optimize':", "have OS_ANDROID / ANDROID defined. 'conditions': [ ['host_os == \"mac\"',", "'base_native_libraries_gen', 'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name':", "[ 'debug/debug_on_start_win.cc', ], }], ], # Specify delayload for base_win64.dll.", "this when gyp finally supports a clean model. # See", "'target_name': 'base_java', 'type': 'none', 'variables': { 'java_in_dir': 'android/java', 'jar_excluded_classes': [", "'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc', 'synchronization/waitable_event_watcher_unittest.cc', 'sys_info_unittest.cc', 'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc',", "{ # TODO(jbudorick): Remove this once we roll to robolectric", "'../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate', ], }, ] } ],", "when building for host, but getting the gyp magic #", "[ '..', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name':", "_toolset != \"host\"', { 'sources/': [ # Pull in specific", "['include', '_chromeos\\\\.cc$'] ] }], ], 'dependencies': [ 'symbolize', 'xdg_mime', ],", "'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc', 'prefs/testing_pref_service.h', 'prefs/testing_pref_store.cc', 'prefs/testing_pref_store.h', ], }, { # This", "'base_message_loop_tests', 'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n',", "the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes':", "'x64', }, }, 'conditions': [ ['component == \"shared_library\"', { 'sources!':", "'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc', 'profiler/stack_sampling_profiler_unittest.cc', 'profiler/tracked_time_unittest.cc', 'rand_util_unittest.cc',", "{ 'sources!': [ # iOS uses its own unit test", "[ 'i18n/streaming_utf8_validator_perftest.cc', ], }, { # GN: //base/test:test_support 'target_name': 'test_support_base',", "'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java',", "'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc', 'test/perf_test_suite.h', 'test/perf_time_logger.cc', 'test/perf_time_logger.h', 'test/power_monitor_test_base.cc', 'test/power_monitor_test_base.h', 'test/scoped_locale.cc',", "'max', }, 'toolsets': ['host', 'target'], 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc',", "for host support is the minimum required to run the", "depend on base because # base depends on base_static. 'target_name':", "'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java',", "['OS == \"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc',", "'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc', 'test/perf_log.h', 'test/perf_test_suite.cc',", "}, }, { 'target_name': 'test_launcher_nacl_nonsfi', 'conditions': [ ['disable_nacl==0 and disable_nacl_untrusted==0", "suite. ['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', {", "'link_settings': { 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework', '$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework',", "'target_name': 'symbolize', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code':", "'target_name': 'base_unittests_jni_headers', 'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables':", "], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC', ],", "# TODO(gregoryd): direct_dependent_settings should be shared with the # 32-bit", "'powrprof.lib', 'setupapi.lib', ], }, }, }, # TODO(rvargas): Bug 78117.", "}, 'includes': [ '../build/copy_test_data_ios.gypi' ], }, ], }], ['desktop_linux ==", "'toolsets': ['host', 'target'], 'variables': { 'chromium_code': 0, }, 'conditions': [", "3.0 and pull # in the multidex shadow library. crbug.com/522043", "1, }, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions':", "'target_name': 'base_jni_headers', 'type': 'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java',", "], }, ], 'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets':", "hard, and we really only # need base on host.", "'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc',", "all # targets when building for host, but getting the", "needed to trigger the dll copy step on windows. #", "'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code', ], }], ], }, { # GN:", "}, { # desktop_linux == 0 and chromeos == 0", "'java_in_dir': '../base/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { #", "], # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings':", "'prefs/json_pref_store.h', 'prefs/overlay_user_pref_store.cc', 'prefs/overlay_user_pref_store.h', 'prefs/persistent_pref_store.h', 'prefs/pref_change_registrar.cc', 'prefs/pref_change_registrar.h', 'prefs/pref_filter.h', 'prefs/pref_member.cc', 'prefs/pref_member.h', 'prefs/pref_notifier.h',", "//base:check_example 'target_name': 'check_example', 'type': 'executable', 'sources': [ 'check_example.cc', ], 'dependencies':", "'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc', 'time/time_unittest.cc', 'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc',", "'../build/host_jar.gypi' ] }, { # GN: //base:base_junit_tests 'target_name': 'base_junit_tests', 'type':", "'_nss\\\\.cc$'], ], }], ['use_glib==1', { 'dependencies': [ '../build/linux/system.gyp:glib', ], 'export_dependent_settings':", "'max', }, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ],", "rules). ['include', '^test/test_file_util_mac\\\\.cc$'], ], }], ['OS == \"ios\" and _toolset", "'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc', 'threading/thread_local_storage_unittest.cc', 'threading/thread_local_unittest.cc', 'threading/thread_unittest.cc', 'threading/watchdog_unittest.cc', 'threading/worker_pool_posix_unittest.cc', 'threading/worker_pool_unittest.cc', 'time/pr_time_unittest.cc',", "}], ['OS==\"ios\"', { 'sources!': [ 'sync_socket.h', 'sync_socket_posix.cc', ] }], ],", "should be shared with the # 32-bit target, but it", "'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc', 'sync_socket_win.cc',", "'path_service_unittest.cc', 'pickle_unittest.cc', 'posix/file_descriptor_shuffle_unittest.cc', 'posix/unix_domain_socket_linux_unittest.cc', 'power_monitor/power_monitor_unittest.cc', 'prefs/default_pref_store_unittest.cc', 'prefs/json_pref_store_unittest.cc', 'prefs/mock_pref_change_callback.h', 'prefs/overlay_user_pref_store_unittest.cc', 'prefs/pref_change_registrar_unittest.cc',", "are # focusing on. In theory we should do this", "'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name':", "on iOS ['OS==\"ios\"', { 'sources!': [ 'sync_socket_unittest.cc', ], }], ],", "the multidex shadow library. crbug.com/522043 # GN: //base:base_junit_test_support 'target_name': 'base_junit_test_support',", "this target for a main() function that simply instantiates #", "'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java',", "'strings/string_tokenizer_unittest.cc', 'strings/string_util_unittest.cc', 'strings/stringize_macros_unittest.cc', 'strings/stringprintf_unittest.cc', 'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc',", "['OS != \"win\" and (OS != \"ios\" or _toolset ==", "[ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h',", "'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc', 'metrics/field_trial_unittest.cc', 'metrics/histogram_base_unittest.cc', 'metrics/histogram_delta_serialization_unittest.cc', 'metrics/histogram_macros_unittest.cc', 'metrics/histogram_snapshot_manager_unittest.cc',", "[ 'third_party/xdg_mime/xdgmime.c', 'third_party/xdg_mime/xdgmime.h', 'third_party/xdg_mime/xdgmimealias.c', 'third_party/xdg_mime/xdgmimealias.h', 'third_party/xdg_mime/xdgmimecache.c', 'third_party/xdg_mime/xdgmimecache.h', 'third_party/xdg_mime/xdgmimeglob.c', 'third_party/xdg_mime/xdgmimeglob.h', 'third_party/xdg_mime/xdgmimeicon.c',", "[ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h', 'test/gtest_xml_util.cc', 'test/gtest_xml_util.h', 'test/histogram_tester.cc', 'test/histogram_tester.h', 'test/icu_test_util.cc',", "'files': [ '../build/win/dbghelp_xp/dbghelp.dll', ], }, ], 'dependencies': [ 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ],", "], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_memory_pressure_level', 'type': 'none',", "}, # Include this target for a main() function that", "'test_launcher', 'toolsets': ['host'], 'type': 'executable', 'dependencies': [ 'test_support_base', ], 'sources':", "rt for clock_gettime(). '-lrt', # For 'native_library_linux.cc' '-ldl', ], },", "\"mac\" or (OS == \"ios\" and _toolset == \"host\")', {", "'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc',", "crazy linker is never instrumented. 'cflags!': [ '-finstrument-functions', ], 'dependencies':", "[ 'symbolize', 'xdg_mime', ], 'defines': [ 'USE_SYMBOLIZE', ], }, {", "'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h', 'test/perf_log.cc',", "'ios/device_util_unittest.mm', 'ios/weak_nsobject_unittest.mm', 'json/json_parser_unittest.cc', 'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc',", "'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ], 'link_settings': { 'libraries': [ '-llog',", "'scoped_clear_errno_unittest.cc', 'scoped_generic_unittest.cc', 'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc',", "GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf',", "target_arch==\"ia32\"', { 'targets': [ # The base_win64 target here allows", "}, { # GN: //base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies':", "be shared with the # 32-bit target, but it doesn't", "doesn't work due to a bug in gyp 'direct_dependent_settings': {", "], }], ['OS == \"android\" and _toolset == \"host\"', {", "== \"host\")', { 'dependencies': ['../third_party/libevent/libevent.gyp:libevent'], },], ['component==\"shared_library\"', { 'conditions': [", "['exclude', '^sys_info_linux\\\\.cc$'], ['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ], }],", "[ '../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths': [ '../base/test/android/junit/', ],", "'third_party/symbolize/glog/logging.h', 'third_party/symbolize/glog/raw_logging.h', 'third_party/symbolize/symbolize.cc', 'third_party/symbolize/symbolize.h', 'third_party/symbolize/utilities.h', ], 'include_dirs': [ '..', ],", "'org/chromium/base/library_loader', 'template_deps': [], }, 'includes': [ '../build/android/java_cpp_template.gypi' ], }, {", "'base_prefs', 'base_prefs_test_support', 'base_static', 'run_all_unittests', 'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc',", "['use_ozone == 1', { 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS", "'defines': [ 'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC', ],", "supports a clean model. # See bug 36232. 'target_name': 'base_static_win64',", "and we really only # need base on host. 'type':", "'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, # Specify", "'-llog', ], }, 'sources!': [ 'debug/stack_trace_posix.cc', ], }], ['os_bsd==1', {", "'test/launcher/unit_test_launcher_ios.cc', 'test/mock_chrome_application_mac.h', 'test/mock_chrome_application_mac.mm', 'test/mock_devices_changed_observer.cc', 'test/mock_devices_changed_observer.h', 'test/mock_entropy_provider.cc', 'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc',", "'base_multidex_gen', 'base_native_libraries_gen', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', '../third_party/jsr-305/jsr-305.gyp:jsr_305_javalib', ], 'includes': [ '../build/java.gypi' ], },", "what developers are # focusing on. In theory we should", "'/usr/local/include', ], 'link_settings': { 'libraries': [ '-L/usr/local/lib -lexecinfo', ], },", "'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc', 'strings/string_piece_unittest.cc', 'strings/string_split_unittest.cc', 'strings/string_tokenizer_unittest.cc',", "generally for all # targets when building for host, but", "'none', 'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ], 'variables': {", "'static_library', 'dependencies': [ 'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml',", "'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h',", "'..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc', ], 'configurations': { 'Common_Base': {", "'android/linker/modern_linker_jni.h', ], # The crazy linker is never instrumented. 'cflags!':", "'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], # TODO(gregoryd): direct_dependent_settings should be", "do this more generally for all # targets when building", "'<(gtest_target_type)', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc',", "[ # base64.cc depends on modp_b64. 'base64.cc', ], 'include_dirs': [", "'$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS == \"ios\" and _toolset !=", "}], ], # target_conditions }, { # GN: //base:base_perftests 'target_name':", "'targets': [ { 'target_name': 'symbolize', 'type': 'static_library', 'toolsets': ['host', 'target'],", "GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ],", "test launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS == \"ios\" and _toolset", "['../build/nocompile.gypi'], 'variables': { # TODO(ajwong): Is there a way to", "[ '-finstrument-functions', ], 'dependencies': [ # The NDK contains the", "1, 'optimize': 'max', }, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64',", "'../build/android/increase_size_for_speed.gypi', ], }, ], }], ['OS == \"linux\"', { 'targets':", "'sources': [ 'i18n/build_utf8_validator_tables.cc' ], }, ], }], ['OS == \"win\"", "], 'variables': { 'jni_gen_package': 'base', }, 'includes': [ '../build/jni_generator.gypi' ],", "'static_library', 'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc',", "{ 'test_suite_name': 'base_unittests', 'isolate_file': 'base_unittests.isolate', }, 'includes': [ '../build/apk_test.gypi' ],", "'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java', 'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java',", "_toolset == \"target\"', { 'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem',", "'-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'defines': [ 'GLOG_BUILD_CONFIG_INCLUDE=\"build/build_config.h\"', ],", "'target_name': 'base_profiler_test_support_library', # Must be a shared library so that", "[ 'NO_TCMALLOC', ], 'direct_dependent_settings': { 'defines': [ 'NO_TCMALLOC', ], },", "}, 'dependencies': [ 'base', ], 'export_dependent_settings': [ 'base', ], 'defines':", "'prefs/scoped_user_pref_update.cc', 'prefs/scoped_user_pref_update.h', 'prefs/value_map_pref_store.cc', 'prefs/value_map_pref_store.h', 'prefs/writeable_pref_store.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ],", "'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc', 'memory/memory_pressure_monitor_mac_unittest.cc', 'memory/memory_pressure_monitor_win_unittest.cc', 'memory/ref_counted_memory_unittest.cc', 'memory/ref_counted_unittest.cc', 'memory/scoped_ptr_unittest.cc', 'memory/scoped_ptr_unittest.nc', 'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc',", "'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package': 'base', },", "Specify delayload for base.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [", "[ '../build/jni_generator.gypi' ], }, { # GN: //base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen',", "}, 'includes': ['../build/android/java_cpp_template.gypi'], }, { # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type',", "[ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib',", "'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, # Specify delayload for", "'powrprof.lib', 'setupapi.lib', ], }, }, }, 'copies': [ { 'destination':", "'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc', 'threading/thread_checker_unittest.cc', 'threading/thread_collision_warner_unittest.cc', 'threading/thread_id_name_manager_unittest.cc',", "[ # We need rt for clock_gettime(). '-lrt', # For", "'test_support_perf', 'type': 'static_library', 'dependencies': [ 'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources':", "'src_paths': [ '../base/test/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ] },", "'test/scoped_locale.cc', 'test/scoped_locale.h', ], }], ['os_bsd==1', { 'sources!': [ 'test/test_file_util_linux.cc', ],", "{ # GN: //base:check_example 'target_name': 'check_example', 'type': 'executable', 'sources': [", "'third_party/xdg_mime/xdgmimeparent.c', 'third_party/xdg_mime/xdgmimeparent.h', ], 'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, ], }],", "'$(SDKROOT)/System/Library/Frameworks/Carbon.framework', '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/Security.framework', ], }, }], ['OS ==", "'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java',", "[ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', { # This is needed", "'base', 'base_static', 'base_i18n', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings':", "'md5.cc', 'md5.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'metrics/field_trial.cc', 'metrics/field_trial.h', 'posix/file_descriptor_shuffle.cc', 'posix/file_descriptor_shuffle.h', 'sync_socket.h', 'sync_socket_posix.cc',", "'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll', 'setupapi.dll', ],", "'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ], # TODO(gregoryd): direct_dependent_settings should be shared with the", "'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc', 'win/dllmain.cc', 'win/enum_variant_unittest.cc', 'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc',", "['OS!=\"ios\"', { 'targets': [ { # GN: //base:check_example 'target_name': 'check_example',", "'native_library_linux.cc' '-ldl', ], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines': [", "[ '../build/host_jar.gypi' ] }, { # GN: //base:base_junit_tests 'target_name': 'base_junit_tests',", "//base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library', 'dependencies': [ 'base', 'base_static', 'base_i18n',", "}], ], # conditions 'target_conditions': [ ['OS == \"ios\" and", "host toolset, even if # we're doing a component build.", "], }], ['OS == \"android\" and _toolset == \"target\"', {", "}, 'conditions': [ ['component == \"shared_library\"', { 'sources!': [ 'debug/debug_on_start_win.cc',", "which is checked into # base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library',", "Note that this library cannot depend on base because #", "uses its own unit test launcher. 'test/launcher/unit_test_launcher.cc', ], }], ['OS", "'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc', 'win/scoped_comptr_unittest.cc', 'win/scoped_handle_unittest.cc', 'win/scoped_process_information_unittest.cc', 'win/scoped_variant_unittest.cc', 'win/shortcut_unittest.cc', 'win/startup_information_unittest.cc', 'win/win_util_unittest.cc',", "-lexecinfo', ], }, }], ['OS == \"linux\"', { 'link_settings': {", "LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [", "'../third_party/icu/icu.gyp:icuuc', '../third_party/libxml/libxml.gyp:libxml', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], 'export_dependent_settings': [ 'base', ], 'conditions': [", "'base', 'test_support_base', '../testing/gtest.gyp:gtest', ], 'sources': [ 'message_loop/message_pump_perftest.cc', 'test/run_all_unittests.cc', 'threading/thread_perftest.cc', '../testing/perf/perf_test.cc'", "iOS uses its own unit test launcher. 'test/launcher/unit_test_launcher.cc', ], }],", "[ 'profiler/test_support_library.cc', ], }, ] }], ['os_posix==1 and OS!=\"mac\" and", "instantiates # and runs a base::TestSuite. { 'target_name': 'run_all_unittests', 'type':", "'mac/foundation_util_unittest.mm', 'mac/libdispatch_task_runner_unittest.cc', 'mac/mac_util_unittest.mm', 'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc',", "'scoped_native_library_unittest.cc', 'security_unittest.cc', 'sequence_checker_unittest.cc', 'sha1_unittest.cc', 'stl_util_unittest.cc', 'strings/nullable_string16_unittest.cc', 'strings/pattern_unittest.cc', 'strings/safe_sprintf_unittest.cc', 'strings/string16_unittest.cc', 'strings/string_number_conversions_unittest.cc',", "1, }, 'dependencies': [ 'base_static_win64', 'allocator/allocator.gyp:allocator_extension_thunks_win64', '../third_party/modp_b64/modp_b64.gyp:modp_b64_win64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations_win64', 'trace_event/etw_manifest/etw_manifest.gyp:etw_manifest', ],", "], }], # Enable more direct string conversions on platforms", "'prefs/pref_change_registrar_unittest.cc', 'prefs/pref_member_unittest.cc', 'prefs/pref_notifier_impl_unittest.cc', 'prefs/pref_service_unittest.cc', 'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm',", "'defines': [ 'BASE_PREFS_IMPLEMENTATION', ], 'sources': [ 'prefs/base_prefs_export.h', 'prefs/default_pref_store.cc', 'prefs/default_pref_store.h', 'prefs/json_pref_store.cc',", "# GN: //base/test:test_support 'target_name': 'test_support_base', 'type': 'static_library', 'dependencies': [ 'base',", "'chromium_code': 0, }, 'cflags!': [ '-Wextra', ], 'sources': [ 'third_party/xdg_mime/xdgmime.c',", "'android/java/src/org/chromium/base/CpuFeatures.java', 'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java',", "'includes': [ '../build/host_jar.gypi' ], }, { # GN: //base:base_javatests 'target_name':", "'setupapi.lib', ], }, }, # Specify delayload for components that", "['OS == \"ios\"', { 'toolsets': ['host', 'target'], }], ], 'sources':", "}], ], }, ], 'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', {", "'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE'], }, { # else icu_use_data_file_flag !=1 'conditions': [", "], }], ['OS!=\"ios\"', { 'targets': [ { # GN: //base:check_example", "'base_junit_tests', 'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', 'base_junit_test_support', '../testing/android/junit/junit_test.gyp:junit_test_support', ],", "'../base/test/android/javatests', }, 'includes': [ '../build/java.gypi' ], }, { # TODO(jbudorick):", "['host', 'target'], }], ], 'export_dependent_settings': [ 'base', '../third_party/icu/icu.gyp:icuuc', '../third_party/icu/icu.gyp:icui18n', ],", "{ # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_load_from_apk_status_codes', 'type': 'none', 'variables': {", "'DelayLoadDLLs': [ 'cfgmgr32.dll', 'shell32.dll', ], 'AdditionalDependencies': [ 'cfgmgr32.lib', 'shell32.lib', ],", "'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java',", "'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'metrics/bucket_ranges_unittest.cc',", "'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc', 'test/test_file_util_posix.cc', 'test/test_file_util_win.cc', 'test/test_io_thread.cc',", "{ 'target_name': 'run_all_unittests', 'type': 'static_library', 'dependencies': [ 'test_support_base', ], 'sources':", "'base_prefs_test_support', 'type': 'static_library', 'dependencies': [ 'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources':", "'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc', 'threading/simple_thread_unittest.cc',", "'../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables': { #", "for host, gyp has OS == \"android\", # hence the", "//base:base_native_libraries_gen 'target_name': 'base_native_libraries_gen', 'type': 'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables':", "[ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'base_i18n', 'type': '<(component)', 'variables':", "'../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables': { # TODO(ajwong): Is there", "dependent # on tcmalloc. # TODO(wfh): crbug.com/246278 Move tcmalloc specific", "'../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc' ], }, ], }], ['OS", "== \"android\" and _toolset == \"host\"', { # Always build", "their own test suite. ['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ],", "'../base/android/junit/', ], }, 'includes': [ '../build/host_jar.gypi' ], }, { #", "[ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ], # target_conditions },", "'android/java/src/org/chromium/base/EventLog.java', 'android/java/src/org/chromium/base/FieldTrialList.java', 'android/java/src/org/chromium/base/ImportantFileWriterAndroid.java', 'android/java/src/org/chromium/base/JNIUtils.java', 'android/java/src/org/chromium/base/JavaHandlerThread.java', 'android/java/src/org/chromium/base/LocaleUtils.java', 'android/java/src/org/chromium/base/MemoryPressureListener.java', 'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java',", "'AdditionalDependencies': [ 'cfgmgr32.lib', 'powrprof.lib', 'setupapi.lib', ], }, }, }, #", "], }, ] }], ['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"', {", "'includes': [ '../build/android/increase_size_for_speed.gypi', ], }, { 'target_name': 'xdg_mime', 'type': 'static_library',", "'includes': [ '../build/java.gypi' ], }, { # TODO(jbudorick): Remove this", "'_chromeos\\\\.cc$'] ] }], ], 'dependencies': [ 'symbolize', 'xdg_mime', ], 'defines':", "[ { 'target_name': 'malloc_wrapper', 'type': 'shared_library', 'dependencies': [ 'base', ],", "and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [ { 'target_name': 'test_launcher', 'toolsets': ['host'],", "[ # This is needed so base_unittests uses the allocator", "'sources': [ 'i18n/streaming_utf8_validator_perftest.cc', ], }, { # GN: //base/test:test_support 'target_name':", "{ 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0', { # This", "'target_name': 'xdg_mime', 'type': 'static_library', 'toolsets': ['host', 'target'], 'variables': { 'chromium_code':", "[ '../build/android/java_cpp_enum.gypi' ], }, { # GN: //base:base_java 'target_name': 'base_java',", "'prefs/pref_value_map_unittest.cc', 'prefs/pref_value_store_unittest.cc', 'prefs/scoped_user_pref_update_unittest.cc', 'process/memory_unittest.cc', 'process/memory_unittest_mac.h', 'process/memory_unittest_mac.mm', 'process/process_metrics_unittest.cc', 'process/process_metrics_unittest_ios.cc', 'process/process_unittest.cc', 'process/process_util_unittest.cc',", "'android/java/src/org/chromium/base/PathService.java', 'android/java/src/org/chromium/base/PathUtils.java', 'android/java/src/org/chromium/base/PowerMonitor.java', 'android/java/src/org/chromium/base/SysUtils.java', 'android/java/src/org/chromium/base/SystemMessageHandler.java', 'android/java/src/org/chromium/base/ThreadUtils.java', 'android/java/src/org/chromium/base/TraceEvent.java', 'android/java/src/org/chromium/base/library_loader/LibraryLoader.java', 'android/java/src/org/chromium/base/metrics/RecordHistogram.java', 'android/java/src/org/chromium/base/metrics/RecordUserAction.java',", "[ 'base_java', ], 'variables': { 'java_in_dir': '../base/test/android/java', }, 'includes': [", "when building for host, gyp has OS == \"android\", #", "'sources!': [ 'test/launcher/unit_test_launcher_ios.cc', 'test/test_support_ios.h', 'test/test_support_ios.mm', ], }], ], # target_conditions", "2012 The Chromium Authors. All rights reserved. # Use of", "'../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir': '../base/test/android/javatests', }, 'includes': [ '../build/java.gypi'", "'android/linker/modern_linker_jni.cc', 'android/linker/modern_linker_jni.h', ], # The crazy linker is never instrumented.", "== \"target\"', { 'dependencies': [ 'base_java', 'base_jni_headers', '../build/android/ndk.gyp:cpu_features', '../third_party/ashmem/ashmem.gyp:ashmem', ],", "'cflags!': [ '-finstrument-functions', ], 'dependencies': [ # The NDK contains", "'none', 'sources': [ 'android/java/templates/NativeLibraries.template', ], 'variables': { 'package_name': 'org/chromium/base/library_loader', 'template_deps':", "'base_i18n_target': 1, }, 'dependencies': [ 'base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ],", "], }, { # GN: //base:base_java_test_support 'target_name': 'base_java_test_support', 'type': 'none',", "== \"linux\"', { 'targets': [ { 'target_name': 'malloc_wrapper', 'type': 'shared_library',", "iOS does not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [", "checked into # base/test/data/pe_image. 'target_name': 'pe_image_test', 'type': 'shared_library', 'sources': [", "['use_allocator!=\"none\"', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ]}, ], [", "], }, { 'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies': [ 'base',", "{ 'source_file': 'android/application_status_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ], }, {", "}, 'dependencies': [ 'base_static', 'allocator/allocator.gyp:allocator_extension_thunks', '../testing/gtest.gyp:gtest_prod', '../third_party/modp_b64/modp_b64.gyp:modp_b64', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', ], #", "'../third_party/android_crazy_linker/crazy_linker.gyp:crazy_linker', ], }, { # GN: //base:base_perftests_apk 'target_name': 'base_perftests_apk', 'type':", "GN: //base/android/linker:chromium_android_linker 'target_name': 'chromium_android_linker', 'type': 'shared_library', 'sources': [ 'android/linker/android_dlext.h', 'android/linker/legacy_linker_jni.cc',", "}, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..', ],", "'target'], 'variables': { 'chromium_code': 0, }, 'cflags!': [ '-Wextra', ],", "] }], ['OS == \"linux\"', { 'dependencies': [ 'malloc_wrapper', ],", "for base_win64.dll. 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll', 'powrprof.dll',", "for the \"component\" variable is hard, and we really only", "}], ], }], ['use_glib == 1', { 'dependencies': [ '../build/linux/system.gyp:glib',", "//base:base_java_unittest_support 'target_name': 'base_java_unittest_support', 'type': 'none', 'dependencies': [ 'base_java', ], 'variables':", "'json/json_reader_unittest.cc', 'json/json_value_converter_unittest.cc', 'json/json_value_serializer_unittest.cc', 'json/json_writer_unittest.cc', 'json/string_escape_unittest.cc', 'lazy_instance_unittest.cc', 'logging_unittest.cc', 'mac/bind_objc_block_unittest.mm', 'mac/call_with_eh_frame_unittest.mm', 'mac/dispatch_source_mach_unittest.cc',", "'test/mock_entropy_provider.h', 'test/mock_log.cc', 'test/mock_log.h', 'test/multiprocess_test.cc', 'test/multiprocess_test.h', 'test/multiprocess_test_android.cc', 'test/null_task_runner.cc', 'test/null_task_runner.h', 'test/opaque_ref_counted.cc', 'test/opaque_ref_counted.h',", "[ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir': '../base/test/android/javatests', }, 'includes':", "# on tcmalloc. # TODO(wfh): crbug.com/246278 Move tcmalloc specific tests", "['exclude', '^process/process_unittest\\\\.cc$'], ['exclude', '^process/process_util_unittest\\\\.cc$'], ['include', '^process/process_util_unittest_ios\\\\.cc$'], # iOS does not", "does not use message_pump_libevent. ['exclude', '^message_loop/message_pump_libevent_unittest\\\\.cc$'], ], 'actions': [ {", "# Enable more direct string conversions on platforms with native", "'java_in_dir': 'android/java', 'jar_excluded_classes': [ '*/NativeLibraries.class' ], }, 'dependencies': [ 'base_java_application_state',", "'<@(nacl_win64_defines)', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, },", "'memory/scoped_vector_unittest.cc', 'memory/shared_memory_unittest.cc', 'memory/shared_memory_mac_unittest.cc', 'memory/singleton_unittest.cc', 'memory/weak_ptr_unittest.cc', 'memory/weak_ptr_unittest.nc', 'message_loop/message_loop_task_runner_unittest.cc', 'message_loop/message_loop_unittest.cc', 'message_loop/message_pump_glib_unittest.cc', 'message_loop/message_pump_io_ios_unittest.cc',", "{ 'sources!': [ 'file_descriptor_shuffle_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'message_loop/message_pump_libevent_unittest.cc', 'threading/worker_pool_posix_unittest.cc', ], # TODO(jschuh):", "'none', 'sources': [ 'android/java/src/org/chromium/base/ApkAssets.java', 'android/java/src/org/chromium/base/ApplicationStatus.java', 'android/java/src/org/chromium/base/AnimationFrameTimeHistogram.java', 'android/java/src/org/chromium/base/BuildInfo.java', 'android/java/src/org/chromium/base/CommandLine.java', 'android/java/src/org/chromium/base/ContentUriUtils.java', 'android/java/src/org/chromium/base/ContextUtils.java',", "{ 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['OS == \"linux\"', {", "'debug/task_annotator_unittest.cc', 'deferred_sequenced_task_runner_unittest.cc', 'environment_unittest.cc', 'feature_list_unittest.cc', 'file_version_info_unittest.cc', 'files/dir_reader_posix_unittest.cc', 'files/file_path_unittest.cc', 'files/file_path_watcher_unittest.cc', 'files/file_proxy_unittest.cc', 'files/file_unittest.cc',", "} ], }], ['OS == \"android\"', { 'targets': [ {", "# by file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'], ['include', '^mac/foundation_util_unittest\\\\.mm$',], ['include',", "[ '../build/host_jar.gypi' ], }, { # GN: //base:base_javatests 'target_name': 'base_javatests',", "'../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS == \"win\"', { # TODO(jschuh):", "'target_name': 'base_static_win64', 'type': 'static_library', 'sources': [ 'base_switches.cc', 'base_switches.h', 'win/pe_image.cc', 'win/pe_image.h',", "# However, we use our own fork. See bug 384700.", "], }, { # GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)',", "== \"android\"', { 'targets': [ { # GN: //base:base_jni_headers 'target_name':", "{ # GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [", "'base_i18n_nacl_win64', 'type': '<(component)', # TODO(gregoryd): direct_dependent_settings should be shared with", "] } ], ], }], ['OS == \"win\"', { 'targets':", "'target_name': 'base_i18n_perftests', 'type': '<(gtest_target_type)', 'dependencies': [ 'test_support_base', 'test_support_perf', '../testing/gtest.gyp:gtest', 'base_i18n',", "], }], ], }, { # GN: //base:base_i18n_perftests 'target_name': 'base_i18n_perftests',", "[ 'android_runtime_jni_headers', ], 'includes': [ '../build/jni_generator.gypi' ], }, { #", "'base_profiler_test_support_library', ], }], ['OS == \"win\"', { 'sources!': [ 'file_descriptor_shuffle_unittest.cc',", "}, ], 'conditions': [ ['OS==\"ios\" and \"<(GENERATOR)\"==\"ninja\"', { 'targets': [", "{ # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings':", "'type': 'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi'", "'../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables': { # TODO(ajwong):", "'additional_gcc_preprocess_options': [ '--defines', 'MULTIDEX_CONFIGURATION_<(CONFIGURATION_NAME)', ], }, 'includes': ['../build/android/java_cpp_template.gypi'], }, {", "memory and process_utils. ['exclude', '^memory/discardable_shared_memory_unittest\\\\.cc$'], ['exclude', '^memory/shared_memory_unittest\\\\.cc$'], ['exclude', '^process/memory_unittest'], ['exclude',", "subset of files from base that should not be used", "['include', '^mac/scoped_nsobject_unittest\\\\.mm$'], ['include', '^sys_string_conversions_mac_unittest\\\\.mm$'], ], }], ['OS == \"android\"', {", "'targets': [ { 'target_name': 'base_unittests_apk_run', 'type': 'none', 'dependencies': [ 'base_unittests_apk',", "been filtered out # by file name rules). ['include', '^mac/bind_objc_block_unittest\\\\.mm$'],", "'base_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate', ],", "{ # GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_application_state', 'type': 'none', 'variables': {", "[ { # Target to manually rebuild pe_image_test.dll which is", "{ 'sources/': [ # iOS does not support FilePathWatcher. ['exclude',", "], 'conditions': [ ['OS == \"android\"', { 'dependencies': [ '../testing/android/native_test.gyp:native_test_native_code',", "'conditions': [ [ 'desktop_linux==1', { 'sources': [ 'nix/xdg_util_unittest.cc', ], }],", "base for Win64 targets # (the normal build is 32", "!= \"noop\"', { 'targets': [ { 'target_name': 'base_unittests_run', 'type': 'none',", "], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h',", "'test/test_file_util_win.cc', 'test/test_io_thread.cc', 'test/test_io_thread.h', 'test/test_listener_ios.h', 'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc',", "for host, but getting the gyp magic # per-toolset for", "test suite. ['win_use_allocator_shim==1', { 'dependencies': [ 'allocator/allocator.gyp:allocator', ], }], ['icu_use_data_file_flag==0',", "'<(component)', 'toolsets': ['host', 'target'], 'variables': { 'base_target': 1, 'enable_wexit_time_destructors': 1,", "a way to autodetect this? 'module_dir': 'base' }, 'conditions': [", "'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc', 'threading/platform_thread_unittest.cc', 'threading/sequenced_worker_pool_unittest.cc', 'threading/sequenced_task_runner_handle_unittest.cc',", "[ '../build/linux/system.gyp:glib', ], }], ['OS == \"android\" and _toolset ==", "'time/time_win_unittest.cc', 'timer/hi_res_timer_manager_unittest.cc', 'timer/mock_timer_unittest.cc', 'timer/timer_unittest.cc', 'tools_sanity_unittest.cc', 'tracked_objects_unittest.cc', 'tuple_unittest.cc', 'values_unittest.cc', 'version_unittest.cc', 'vlog_unittest.cc',", "}], ]}, ], [ 'OS == \"win\" and target_arch ==", "'mac/objc_property_releaser_unittest.mm', 'mac/scoped_nsobject_unittest.mm', 'mac/scoped_objc_class_swizzler_unittest.mm', 'mac/scoped_sending_event_unittest.mm', 'md5_unittest.cc', 'memory/aligned_memory_unittest.cc', 'memory/discardable_shared_memory_unittest.cc', 'memory/linked_ptr_unittest.cc', 'memory/memory_pressure_listener_unittest.cc', 'memory/memory_pressure_monitor_chromeos_unittest.cc',", "['host', 'target'], }], ], 'sources': [ 'test/gtest_util.cc', 'test/gtest_util.h', 'test/gtest_xml_unittest_result_printer.cc', 'test/gtest_xml_unittest_result_printer.h',", "['os_posix==1 and OS!=\"mac\" and OS!=\"ios\"', { 'targets': [ { 'target_name':", "'i18n/break_iterator_unittest.cc', 'i18n/case_conversion_unittest.cc', 'i18n/char_iterator_unittest.cc', 'i18n/file_util_icu_unittest.cc', 'i18n/icu_string_conversions_unittest.cc', 'i18n/message_formatter_unittest.cc', 'i18n/number_formatting_unittest.cc', 'i18n/rtl_unittest.cc', 'i18n/streaming_utf8_validator_unittest.cc', 'i18n/string_search_unittest.cc',", "library. Note that this library cannot depend on base because", "TODO(rvargas): Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, ], },", "!= \"win\" 'dependencies': [ '../third_party/libevent/libevent.gyp:libevent' ], }], ], # conditions", "'base', 'input_java_class': 'java/lang/Runtime.class', }, 'includes': [ '../build/jar_file_jni_generator.gypi' ], }, {", "'none', 'dependencies': [ 'base_java', ], 'variables': { 'java_in_dir': '../base/test/android/java', },", "TODO(jbudorick): Remove this once we roll to robolectric 3.0 and", "'message_loop/message_pump_android.cc', 'message_loop/message_pump_android.h', 'message_loop/message_pump_glib.cc', 'message_loop/message_pump_glib.h', 'message_loop/message_pump_io_ios.cc', 'message_loop/message_pump_io_ios.h', 'message_loop/message_pump_libevent.cc', 'message_loop/message_pump_libevent.h', 'message_loop/message_pump_mac.h', 'message_loop/message_pump_mac.mm',", "['OS == \"ios\"', { 'toolsets': ['host', 'target'], }], ], 'export_dependent_settings':", "'<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ], 'include_dirs': [ '..', ], 'sources': [ 'i18n/icu_util_nacl_win64.cc',", "# TODO(jbudorick): Remove this once we roll to robolectric 3.0", "'type': 'none', 'dependencies': [ 'base_java', '../testing/android/on_device_instrumentation.gyp:reporter_java', ], 'variables': { 'java_in_dir':", "'../testing/android/junit/junit_test.gyp:junit_test_support', '../third_party/android_tools/android_tools.gyp:android_support_multidex_javalib', ], 'variables': { 'src_paths': [ '../base/test/android/junit/', ], },", "'type': 'static_library', # Base for host support is the minimum", "['desktop_linux == 1 or chromeos == 1', { 'conditions': [", "base_win64.lib. 'all_dependent_settings': { 'msvs_settings': { 'VCLinkerTool': { 'DelayLoadDLLs': [ 'cfgmgr32.dll',", "'none', 'variables': { 'source_file': 'memory/memory_pressure_listener.h', }, 'includes': [ '../build/android/java_cpp_enum.gypi' ],", "'type': 'none', 'dependencies': [ 'base_java', 'base_java_test_support', ], 'variables': { 'java_in_dir':", "'defines': ['ICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC'], }], ], }], ['OS == \"ios\"', { 'toolsets':", "GN: //base:base_android_java_enums_srcjar 'target_name': 'base_java_library_process_type', 'type': 'none', 'variables': { 'source_file': 'android/library_loader/library_loader_hooks.h',", "'test_support_base', 'third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '../testing/gmock.gyp:gmock', '../testing/gtest.gyp:gtest', '../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'includes': ['../build/nocompile.gypi'], 'variables':", "'target_name': 'android_runtime_jni_headers', 'type': 'none', 'variables': { 'jni_gen_package': 'base', 'input_java_class': 'java/lang/Runtime.class',", "'<(android_ndk_root)/crazy_linker.gyp:crazy_linker' # However, we use our own fork. See bug", "model. # See bug 36232. 'target_name': 'base_static_win64', 'type': 'static_library', 'sources':", "'system_monitor/system_monitor_unittest.cc', 'task/cancelable_task_tracker_unittest.cc', 'task_runner_util_unittest.cc', 'template_util_unittest.cc', 'test/histogram_tester_unittest.cc', 'test/test_pending_task_unittest.cc', 'test/test_reg_util_win_unittest.cc', 'test/trace_event_analyzer_unittest.cc', 'test/user_action_tester_unittest.cc', 'threading/non_thread_safe_unittest.cc',", "], }], ['OS == \"linux\"', { 'targets': [ { 'target_name':", "'test/test_listener_ios.mm', 'test/test_mock_time_task_runner.cc', 'test/test_mock_time_task_runner.h', 'test/test_pending_task.cc', 'test/test_pending_task.h', 'test/test_reg_util_win.cc', 'test/test_reg_util_win.h', 'test/test_shortcut_win.cc', 'test/test_shortcut_win.h', 'test/test_simple_task_runner.cc',", "use_glib == 0 'sources!': [ 'message_loop/message_pump_glib_unittest.cc', ] }], ['use_ozone ==", "ssl false start blacklist tool. It requires further changes #", "'includes': [ '../build/isolate.gypi', ], 'sources': [ 'base_unittests_apk.isolate', ], }, ]", "== \"ios\" and _toolset == \"target\"', { 'sources!': [ #", "'strings/sys_string_conversions_mac_unittest.mm', 'strings/sys_string_conversions_unittest.cc', 'strings/utf_offset_string_conversions_unittest.cc', 'strings/utf_string_conversions_unittest.cc', 'supports_user_data_unittest.cc', 'sync_socket_unittest.cc', 'synchronization/cancellation_flag_unittest.cc', 'synchronization/condition_variable_unittest.cc', 'synchronization/lock_unittest.cc', 'synchronization/waitable_event_unittest.cc',", "'target_name': 'base_message_loop_tests', 'type': 'static_library', 'dependencies': [ 'base', '../testing/gtest.gyp:gtest', ], 'sources':", "'type': 'none', 'sources': [ 'test/android/java/src/org/chromium/base/ContentUriTestUtils.java', 'test/android/java/src/org/chromium/base/TestUiThread.java', ], 'variables': { 'jni_gen_package':", "'dependencies': [ '../build/linux/system.gyp:glib', ], }, { # use_glib == 0", "'test/simple_test_tick_clock.h', 'test/task_runner_test_template.cc', 'test/task_runner_test_template.h', 'test/test_discardable_memory_allocator.cc', 'test/test_discardable_memory_allocator.h', 'test/test_file_util.cc', 'test/test_file_util.h', 'test/test_file_util_android.cc', 'test/test_file_util_linux.cc', 'test/test_file_util_mac.cc',", "'-ldl', ], }, 'conditions': [ ['use_allocator!=\"tcmalloc\"', { 'defines': [ 'NO_TCMALLOC',", "4244, 4996, 4267, ], 'sources': [ 'auto_reset.h', 'linux_util.cc', 'linux_util.h', 'md5.cc',", "'$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/CoreGraphics.framework', '$(SDKROOT)/System/Library/Frameworks/CoreText.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/UIKit.framework', ], }, }], ['OS !=", "'include_dirs': [ '..', ], }, 'defines': [ '<@(nacl_win64_defines)', 'BASE_I18N_IMPLEMENTATION', ],", "'variables': { 'chromium_code': 0, }, 'conditions': [ ['OS == \"solaris\"',", "'../third_party/icu/icu.gyp:icui18n', '../third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS == \"win\"', { #", "'win/event_trace_consumer_unittest.cc', 'win/event_trace_controller_unittest.cc', 'win/event_trace_provider_unittest.cc', 'win/i18n_unittest.cc', 'win/iunknown_impl_unittest.cc', 'win/message_window_unittest.cc', 'win/object_watcher_unittest.cc', 'win/pe_image_unittest.cc', 'win/registry_unittest.cc', 'win/scoped_bstr_unittest.cc',", "'toolsets': ['host'], 'dependencies': [ 'base', '../third_party/icu/icu.gyp:icuuc', ], 'sources': [ 'i18n/build_utf8_validator_tables.cc'", "'base', 'base_prefs', '../testing/gmock.gyp:gmock', ], 'sources': [ 'prefs/mock_pref_change_callback.cc', 'prefs/pref_store_observer_mock.cc', 'prefs/pref_store_observer_mock.h', 'prefs/testing_pref_service.cc',", "[ '/usr/gnu/include', '/usr/gnu/include/libelf', ], },], ], 'cflags': [ '-Wno-sign-compare', ],", "\"<(GENERATOR)\"==\"ninja\"', { 'targets': [ { 'target_name': 'test_launcher', 'toolsets': ['host'], 'type':", "'test/trace_to_file.h', 'test/user_action_tester.cc', 'test/user_action_tester.h', 'test/values_test_util.cc', 'test/values_test_util.h', ], 'target_conditions': [ ['OS ==", "Bug 78117. Remove this. 'msvs_disabled_warnings': [ 4244, ], }, ],", "['exclude', '^sys_string_conversions_linux\\\\.cc$'], ['exclude', '^worker_pool_linux\\\\.cc$'], ], }], ], }], ['OS ==", "library so that it can be unloaded during testing. 'type':" ]
[ "3-digit numbers. ANSWER: 906609 Solve time ~ 0.760 seconds \"\"\"", "from the product of two 2-digit numbers is 9009 =", "self.problem = Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve()) if __name__ ==", "def solve(self): pds = [] for i, j in product(range(self.lower,", "made from the product of two 3-digit numbers. ANSWER: 906609", "* j) return max(pds) class Solution4(unittest.TestCase): def setUp(self): self.problem =", "numbers is 9009 = 91 × 99. Find the largest", "the product of two 3-digit numbers. ANSWER: 906609 Solve time", "solve(self): pds = [] for i, j in product(range(self.lower, self.upper),", "is_palindrome(num): return str(num) == str(num)[::-1] @timeit def solve(self): pds =", "\"\"\" from itertools import product import unittest from util.utils import", "1 @staticmethod def is_palindrome(num): return str(num) == str(num)[::-1] @timeit def", "largest palindrome made from the product of two 3-digit numbers.", "util.utils import timeit class Problem4: def __init__(self, num_digits): self.lower =", "return str(num) == str(num)[::-1] @timeit def solve(self): pds = []", "made from the product of two 2-digit numbers is 9009", "Solve time ~ 0.760 seconds \"\"\" from itertools import product", "max(pds) class Solution4(unittest.TestCase): def setUp(self): self.problem = Problem4(3) def test_solution(self):", "Solution4(unittest.TestCase): def setUp(self): self.problem = Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve())", "pds.append(i * j) return max(pds) class Solution4(unittest.TestCase): def setUp(self): self.problem", "PROBLEM A palindromic number reads the same both ways. The", "2-digit numbers is 9009 = 91 × 99. Find the", "j) return max(pds) class Solution4(unittest.TestCase): def setUp(self): self.problem = Problem4(3)", "palindrome made from the product of two 2-digit numbers is", "= Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve()) if __name__ == '__main__':", "1) - 1 self.upper = 10 ** num_digits - 1", "num_digits): self.lower = 10 ** (num_digits - 1) - 1", "num_digits - 1 @staticmethod def is_palindrome(num): return str(num) == str(num)[::-1]", "product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i * j): pds.append(i * j)", "i, j in product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i * j):", "import unittest from util.utils import timeit class Problem4: def __init__(self,", "def __init__(self, num_digits): self.lower = 10 ** (num_digits - 1)", "** num_digits - 1 @staticmethod def is_palindrome(num): return str(num) ==", "the same both ways. The largest palindrome made from the", "both ways. The largest palindrome made from the product of", "self.upper), repeat=2): if self.is_palindrome(i * j): pds.append(i * j) return", "timeit class Problem4: def __init__(self, num_digits): self.lower = 10 **", "self.is_palindrome(i * j): pds.append(i * j) return max(pds) class Solution4(unittest.TestCase):", "Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve()) if __name__ == '__main__': unittest.main()", "str(num) == str(num)[::-1] @timeit def solve(self): pds = [] for", "Find the largest palindrome made from the product of two", "palindrome made from the product of two 3-digit numbers. ANSWER:", "from itertools import product import unittest from util.utils import timeit", "is 9009 = 91 × 99. Find the largest palindrome", "product of two 2-digit numbers is 9009 = 91 ×", "@staticmethod def is_palindrome(num): return str(num) == str(num)[::-1] @timeit def solve(self):", "9009 = 91 × 99. Find the largest palindrome made", "class Solution4(unittest.TestCase): def setUp(self): self.problem = Problem4(3) def test_solution(self): self.assertEqual(906609,", "from util.utils import timeit class Problem4: def __init__(self, num_digits): self.lower", "two 2-digit numbers is 9009 = 91 × 99. Find", "if self.is_palindrome(i * j): pds.append(i * j) return max(pds) class", "- 1 self.upper = 10 ** num_digits - 1 @staticmethod", "j): pds.append(i * j) return max(pds) class Solution4(unittest.TestCase): def setUp(self):", "× 99. Find the largest palindrome made from the product", "Problem4: def __init__(self, num_digits): self.lower = 10 ** (num_digits -", "the product of two 2-digit numbers is 9009 = 91", "reads the same both ways. The largest palindrome made from", "(num_digits - 1) - 1 self.upper = 10 ** num_digits", "palindromic number reads the same both ways. The largest palindrome", "self.upper = 10 ** num_digits - 1 @staticmethod def is_palindrome(num):", "@timeit def solve(self): pds = [] for i, j in", "two 3-digit numbers. ANSWER: 906609 Solve time ~ 0.760 seconds", "= 10 ** num_digits - 1 @staticmethod def is_palindrome(num): return", "906609 Solve time ~ 0.760 seconds \"\"\" from itertools import", "in product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i * j): pds.append(i *", "numbers. ANSWER: 906609 Solve time ~ 0.760 seconds \"\"\" from", "of two 3-digit numbers. ANSWER: 906609 Solve time ~ 0.760", "str(num)[::-1] @timeit def solve(self): pds = [] for i, j", "\"\"\" PROBLEM A palindromic number reads the same both ways.", "number reads the same both ways. The largest palindrome made", "setUp(self): self.problem = Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve()) if __name__", "self.lower = 10 ** (num_digits - 1) - 1 self.upper", "- 1) - 1 self.upper = 10 ** num_digits -", "== str(num)[::-1] @timeit def solve(self): pds = [] for i,", "* j): pds.append(i * j) return max(pds) class Solution4(unittest.TestCase): def", "of two 2-digit numbers is 9009 = 91 × 99.", "import timeit class Problem4: def __init__(self, num_digits): self.lower = 10", "largest palindrome made from the product of two 2-digit numbers", "same both ways. The largest palindrome made from the product", "= [] for i, j in product(range(self.lower, self.upper), repeat=2): if", "from the product of two 3-digit numbers. ANSWER: 906609 Solve", "pds = [] for i, j in product(range(self.lower, self.upper), repeat=2):", "= 10 ** (num_digits - 1) - 1 self.upper =", "seconds \"\"\" from itertools import product import unittest from util.utils", "91 × 99. Find the largest palindrome made from the", "10 ** num_digits - 1 @staticmethod def is_palindrome(num): return str(num)", "= 91 × 99. Find the largest palindrome made from", "0.760 seconds \"\"\" from itertools import product import unittest from", "** (num_digits - 1) - 1 self.upper = 10 **", "def is_palindrome(num): return str(num) == str(num)[::-1] @timeit def solve(self): pds", "product import unittest from util.utils import timeit class Problem4: def", "j in product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i * j): pds.append(i", "for i, j in product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i *", "the largest palindrome made from the product of two 3-digit", "unittest from util.utils import timeit class Problem4: def __init__(self, num_digits):", "The largest palindrome made from the product of two 2-digit", "return max(pds) class Solution4(unittest.TestCase): def setUp(self): self.problem = Problem4(3) def", "~ 0.760 seconds \"\"\" from itertools import product import unittest", "repeat=2): if self.is_palindrome(i * j): pds.append(i * j) return max(pds)", "itertools import product import unittest from util.utils import timeit class", "ways. The largest palindrome made from the product of two", "A palindromic number reads the same both ways. The largest", "- 1 @staticmethod def is_palindrome(num): return str(num) == str(num)[::-1] @timeit", "product of two 3-digit numbers. ANSWER: 906609 Solve time ~", "10 ** (num_digits - 1) - 1 self.upper = 10", "def setUp(self): self.problem = Problem4(3) def test_solution(self): self.assertEqual(906609, self.problem.solve()) if", "1 self.upper = 10 ** num_digits - 1 @staticmethod def", "class Problem4: def __init__(self, num_digits): self.lower = 10 ** (num_digits", "99. Find the largest palindrome made from the product of", "import product import unittest from util.utils import timeit class Problem4:", "[] for i, j in product(range(self.lower, self.upper), repeat=2): if self.is_palindrome(i", "time ~ 0.760 seconds \"\"\" from itertools import product import", "__init__(self, num_digits): self.lower = 10 ** (num_digits - 1) -", "ANSWER: 906609 Solve time ~ 0.760 seconds \"\"\" from itertools" ]
[ "port=port, name=name ) res = requests.get(resource) try: res.raise_for_status() except Exception", "-- interacts with old `/alias/` endpoint. # For creating aliases", "name. \"\"\" warnings.warn( ( \"This function is deprecated. For creating", "Configure the info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\", help=\"name of information", "by name. \"\"\" warnings.warn( ( \"This function is deprecated. For", "import logging import argparse import warnings import requests from indexclient", "sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure the info command. \"\"\" parser.set_defaults(func=info)", "try: res.raise_for_status() except Exception as err: raise errors.BaseIndexError(res.status_code, res.text) try:", "except Exception as err: raise errors.BaseIndexError(res.status_code, res.text) try: doc =", ") res = requests.get(resource) try: res.raise_for_status() except Exception as err:", "# the `add_alias` function, which interacts with the new #", "creating aliases for indexd \" \"records, prefer using the `add_alias_for_did`", "errors # DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint.", "\" \"records, prefer using the `add_alias_for_did` function, which \" \"interacts", "**kwargs): \"\"\" Retrieve info by name. \"\"\" warnings.warn( ( \"This", "resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name ) res = requests.get(resource)", "For creating aliases for indexd \" \"records, prefer using the", ") resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name ) res =", "\" \"interacts with the new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, )", "json.dumps({\"error\": \"invalid json payload returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def", "for indexd records, prefer using # the `add_alias` function, which", "deprecated. For creating aliases for indexd \" \"records, prefer using", "ValueError as err: reason = json.dumps({\"error\": \"invalid json payload returned\"})", "port, name, **kwargs): \"\"\" Retrieve info by name. \"\"\" warnings.warn(", "\"\"\" Retrieve info by name. \"\"\" warnings.warn( ( \"This function", "res.text) try: doc = res.json() except ValueError as err: reason", "with old `/alias/` endpoint. # For creating aliases for indexd", "import warnings import requests from indexclient import errors # DEPRECATED", "the new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format(", "the new # `/index/{GUID}/aliases` endpoint. def info(host, port, name, **kwargs):", "info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\", help=\"name of information to retrieve\")", "DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint. # For", "def config(parser): \"\"\" Configure the info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\",", "`/index/{GUID}/aliases` endpoint. def info(host, port, name, **kwargs): \"\"\" Retrieve info", "using the `add_alias_for_did` function, which \" \"interacts with the new", "logging import argparse import warnings import requests from indexclient import", "function is deprecated. For creating aliases for indexd \" \"records,", "indexclient import errors # DEPRECATED 11/2019 -- interacts with old", "using # the `add_alias` function, which interacts with the new", "new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format( host=host,", "res = requests.get(resource) try: res.raise_for_status() except Exception as err: raise", "function, which \" \"interacts with the new `/index/{GUID}/aliases` endpoint.\" ),", "Exception as err: raise errors.BaseIndexError(res.status_code, res.text) try: doc = res.json()", "as err: raise errors.BaseIndexError(res.status_code, res.text) try: doc = res.json() except", "= \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name ) res = requests.get(resource) try:", "\"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name ) res = requests.get(resource) try: res.raise_for_status()", "( \"This function is deprecated. For creating aliases for indexd", "indexd \" \"records, prefer using the `add_alias_for_did` function, which \"", "config(parser): \"\"\" Configure the info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\", help=\"name", "is deprecated. For creating aliases for indexd \" \"records, prefer", "the `add_alias_for_did` function, which \" \"interacts with the new `/index/{GUID}/aliases`", "endpoint. def info(host, port, name, **kwargs): \"\"\" Retrieve info by", "old `/alias/` endpoint. # For creating aliases for indexd records,", "import sys import json import logging import argparse import warnings", "name, **kwargs): \"\"\" Retrieve info by name. \"\"\" warnings.warn( (", "reason = json.dumps({\"error\": \"invalid json payload returned\"}) raise errors.BaseIndexError(res.status_code, reason)", "returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure the", "payload returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure", "import argparse import warnings import requests from indexclient import errors", "as err: reason = json.dumps({\"error\": \"invalid json payload returned\"}) raise", "\"invalid json payload returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser):", "`add_alias_for_did` function, which \" \"interacts with the new `/index/{GUID}/aliases` endpoint.\"", "raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure the info", "\"This function is deprecated. For creating aliases for indexd \"", "argparse import warnings import requests from indexclient import errors #", "creating aliases for indexd records, prefer using # the `add_alias`", "requests from indexclient import errors # DEPRECATED 11/2019 -- interacts", "prefer using the `add_alias_for_did` function, which \" \"interacts with the", "\"\"\" warnings.warn( ( \"This function is deprecated. For creating aliases", "res.json() except ValueError as err: reason = json.dumps({\"error\": \"invalid json", "`/alias/` endpoint. # For creating aliases for indexd records, prefer", "= res.json() except ValueError as err: reason = json.dumps({\"error\": \"invalid", "interacts with the new # `/index/{GUID}/aliases` endpoint. def info(host, port,", "\"records, prefer using the `add_alias_for_did` function, which \" \"interacts with", "= requests.get(resource) try: res.raise_for_status() except Exception as err: raise errors.BaseIndexError(res.status_code,", "doc = res.json() except ValueError as err: reason = json.dumps({\"error\":", "), DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name )", "errors.BaseIndexError(res.status_code, res.text) try: doc = res.json() except ValueError as err:", "err: raise errors.BaseIndexError(res.status_code, res.text) try: doc = res.json() except ValueError", "for indexd \" \"records, prefer using the `add_alias_for_did` function, which", "# For creating aliases for indexd records, prefer using #", "info(host, port, name, **kwargs): \"\"\" Retrieve info by name. \"\"\"", "`/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port,", "prefer using # the `add_alias` function, which interacts with the", "with the new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, ) resource =", "warnings.warn( ( \"This function is deprecated. For creating aliases for", "warnings import requests from indexclient import errors # DEPRECATED 11/2019", "new # `/index/{GUID}/aliases` endpoint. def info(host, port, name, **kwargs): \"\"\"", "Retrieve info by name. \"\"\" warnings.warn( ( \"This function is", "err: reason = json.dumps({\"error\": \"invalid json payload returned\"}) raise errors.BaseIndexError(res.status_code,", "info by name. \"\"\" warnings.warn( ( \"This function is deprecated.", "from indexclient import errors # DEPRECATED 11/2019 -- interacts with", "endpoint. # For creating aliases for indexd records, prefer using", "records, prefer using # the `add_alias` function, which interacts with", "with the new # `/index/{GUID}/aliases` endpoint. def info(host, port, name,", "11/2019 -- interacts with old `/alias/` endpoint. # For creating", "\"\"\" Configure the info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\", help=\"name of", "except ValueError as err: reason = json.dumps({\"error\": \"invalid json payload", "interacts with old `/alias/` endpoint. # For creating aliases for", "raise errors.BaseIndexError(res.status_code, res.text) try: doc = res.json() except ValueError as", "try: doc = res.json() except ValueError as err: reason =", "the `add_alias` function, which interacts with the new # `/index/{GUID}/aliases`", "\"interacts with the new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning, ) resource", "name=name ) res = requests.get(resource) try: res.raise_for_status() except Exception as", "# `/index/{GUID}/aliases` endpoint. def info(host, port, name, **kwargs): \"\"\" Retrieve", "host=host, port=port, name=name ) res = requests.get(resource) try: res.raise_for_status() except", "res.raise_for_status() except Exception as err: raise errors.BaseIndexError(res.status_code, res.text) try: doc", "import requests from indexclient import errors # DEPRECATED 11/2019 --", "function, which interacts with the new # `/index/{GUID}/aliases` endpoint. def", "reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure the info command. \"\"\"", "indexd records, prefer using # the `add_alias` function, which interacts", "aliases for indexd \" \"records, prefer using the `add_alias_for_did` function,", "aliases for indexd records, prefer using # the `add_alias` function,", "def info(host, port, name, **kwargs): \"\"\" Retrieve info by name.", "# DEPRECATED 11/2019 -- interacts with old `/alias/` endpoint. #", "json import logging import argparse import warnings import requests from", "DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name ) res", "the info command. \"\"\" parser.set_defaults(func=info) parser.add_argument(\"name\", help=\"name of information to", "sys import json import logging import argparse import warnings import", "import errors # DEPRECATED 11/2019 -- interacts with old `/alias/`", "which \" \"interacts with the new `/index/{GUID}/aliases` endpoint.\" ), DeprecationWarning,", "requests.get(resource) try: res.raise_for_status() except Exception as err: raise errors.BaseIndexError(res.status_code, res.text)", "errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\" Configure the info command.", "= json.dumps({\"error\": \"invalid json payload returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc))", "endpoint.\" ), DeprecationWarning, ) resource = \"http://{host}:{port}/alias/{name}\".format( host=host, port=port, name=name", "For creating aliases for indexd records, prefer using # the", "import json import logging import argparse import warnings import requests", "`add_alias` function, which interacts with the new # `/index/{GUID}/aliases` endpoint.", "which interacts with the new # `/index/{GUID}/aliases` endpoint. def info(host,", "json payload returned\"}) raise errors.BaseIndexError(res.status_code, reason) sys.stdout.write(json.dumps(doc)) def config(parser): \"\"\"" ]
[ "assunto, mensagem): SQL = 'INSERT INTO emails (assunto, mensagem) VALUES", "INTO emails (assunto, mensagem) VALUES (%s, %s)' cur = self.conn.cursor()", "mensagem): SQL = 'INSERT INTO emails (assunto, mensagem) VALUES (%s,", "psycopg2.connect(DSN) def register_message(self, assunto, mensagem): SQL = 'INSERT INTO emails", "from bottle import Bottle, request class Sender(Bottle): def __init__(self): super().__init__()", "register_message(self, assunto, mensagem): SQL = 'INSERT INTO emails (assunto, mensagem)", "cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close() msg = {'assunto': assunto, 'mensagem':", ") if __name__ == '__main__': sender = Sender() sender.run(host='0.0.0.0', port=8080,", "= {'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def", "= request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message queued!", "import redis import json from bottle import Bottle, request class", "json.dumps(msg)) print('Message registered!') def send(self): assunto = request.forms.get('assunto') mensagem =", "return 'Message queued! Assunto: {} Mensage: {}'.format( assunto, mensagem )", "= 'INSERT INTO emails (assunto, mensagem) VALUES (%s, %s)' cur", "{}'.format( assunto, mensagem ) if __name__ == '__main__': sender =", "json from bottle import Bottle, request class Sender(Bottle): def __init__(self):", "import json from bottle import Bottle, request class Sender(Bottle): def", "assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def send(self): assunto", "cur.close() msg = {'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message", "print('Message registered!') def send(self): assunto = request.forms.get('assunto') mensagem = request.forms.get('mensagem')", "self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender user=postgress host=db'", "Mensage: {}'.format( assunto, mensagem ) if __name__ == '__main__': sender", "%s)' cur = self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close() msg", "self.conn = psycopg2.connect(DSN) def register_message(self, assunto, mensagem): SQL = 'INSERT", "mensagem) VALUES (%s, %s)' cur = self.conn.cursor() cur.execute(SQL, (assunto, mensagem))", "port=6379, db=0) DSN = 'dbname=email_sender user=postgress host=db' self.conn = psycopg2.connect(DSN)", "redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender user=postgress host=db' self.conn =", "class Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila =", "queued! Assunto: {} Mensage: {}'.format( assunto, mensagem ) if __name__", "psycopg2 import redis import json from bottle import Bottle, request", "host=db' self.conn = psycopg2.connect(DSN) def register_message(self, assunto, mensagem): SQL =", "def send(self): assunto = request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem)", "def register_message(self, assunto, mensagem): SQL = 'INSERT INTO emails (assunto,", "Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue',", "= psycopg2.connect(DSN) def register_message(self, assunto, mensagem): SQL = 'INSERT INTO", "request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message queued! Assunto:", "VALUES (%s, %s)' cur = self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit()", "request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message queued! Assunto: {} Mensage: {}'.format(", "send(self): assunto = request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem) return", "Assunto: {} Mensage: {}'.format( assunto, mensagem ) if __name__ ==", "db=0) DSN = 'dbname=email_sender user=postgress host=db' self.conn = psycopg2.connect(DSN) def", "mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def send(self): assunto = request.forms.get('assunto')", "self.register_message(assunto, mensagem) return 'Message queued! Assunto: {} Mensage: {}'.format( assunto,", "callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender user=postgress", "request class Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila", "= 'dbname=email_sender user=postgress host=db' self.conn = psycopg2.connect(DSN) def register_message(self, assunto,", "(assunto, mensagem) VALUES (%s, %s)' cur = self.conn.cursor() cur.execute(SQL, (assunto,", "method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender", "'dbname=email_sender user=postgress host=db' self.conn = psycopg2.connect(DSN) def register_message(self, assunto, mensagem):", "self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def send(self): assunto = request.forms.get('assunto') mensagem", "(%s, %s)' cur = self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close()", "mensagem) return 'Message queued! Assunto: {} Mensage: {}'.format( assunto, mensagem", "bottle import Bottle, request class Sender(Bottle): def __init__(self): super().__init__() self.route('/',", "if __name__ == '__main__': sender = Sender() sender.run(host='0.0.0.0', port=8080, debug=True)", "self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close() msg = {'assunto': assunto,", "<reponame>guilhermebc/docker-playground<filename>email-worker-compose/app/sender.py import psycopg2 import redis import json from bottle import", "self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN =", "super().__init__() self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0) DSN", "mensagem)) self.conn.commit() cur.close() msg = {'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender',", "'Message queued! Assunto: {} Mensage: {}'.format( assunto, mensagem ) if", "def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379,", "import psycopg2 import redis import json from bottle import Bottle,", "{} Mensage: {}'.format( assunto, mensagem ) if __name__ == '__main__':", "= request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message queued! Assunto: {} Mensage:", "msg = {'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!')", "emails (assunto, mensagem) VALUES (%s, %s)' cur = self.conn.cursor() cur.execute(SQL,", "assunto = request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message", "user=postgress host=db' self.conn = psycopg2.connect(DSN) def register_message(self, assunto, mensagem): SQL", "DSN = 'dbname=email_sender user=postgress host=db' self.conn = psycopg2.connect(DSN) def register_message(self,", "'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def send(self): assunto =", "redis import json from bottle import Bottle, request class Sender(Bottle):", "import Bottle, request class Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST',", "SQL = 'INSERT INTO emails (assunto, mensagem) VALUES (%s, %s)'", "mensagem ) if __name__ == '__main__': sender = Sender() sender.run(host='0.0.0.0',", "mensagem = request.forms.get('mensagem') self.register_message(assunto, mensagem) return 'Message queued! Assunto: {}", "= redis.StrictRedis(host='queue', port=6379, db=0) DSN = 'dbname=email_sender user=postgress host=db' self.conn", "__init__(self): super().__init__() self.route('/', method='POST', callback=self.send) self.fila = redis.StrictRedis(host='queue', port=6379, db=0)", "Bottle, request class Sender(Bottle): def __init__(self): super().__init__() self.route('/', method='POST', callback=self.send)", "registered!') def send(self): assunto = request.forms.get('assunto') mensagem = request.forms.get('mensagem') self.register_message(assunto,", "{'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg)) print('Message registered!') def send(self):", "= self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close() msg = {'assunto':", "assunto, mensagem ) if __name__ == '__main__': sender = Sender()", "cur = self.conn.cursor() cur.execute(SQL, (assunto, mensagem)) self.conn.commit() cur.close() msg =", "self.conn.commit() cur.close() msg = {'assunto': assunto, 'mensagem': mensagem} self.fila.rpush('sender', json.dumps(msg))", "'INSERT INTO emails (assunto, mensagem) VALUES (%s, %s)' cur =", "(assunto, mensagem)) self.conn.commit() cur.close() msg = {'assunto': assunto, 'mensagem': mensagem}" ]
[ "yaml as pyyaml from zyaml import load_path, load_string, tokens_from_path, tokens_from_string", "result.append(ruamel_passthrough_tags(loader, tag, v)) return result if \"Map\" in name: result", "= \" \".join(str(s) for s in runez.flattened(value)) elif token.id ==", "s in runez.flattened(value)) else: assert False result = \"%s %s\"", "- %s\" % (message, rep)) return print(message) print(rep) def get_outcome(self,", "= None def track_result_combination(self, impl, data): if isinstance(data, Exception): value", "| None): Optional: exact number of implementations that have to", "StrictImplementation] self.available = dict((m.name, m()) for m in av) self.unknown", "runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s - %s\" % (message, rep))", "ruamel_passthrough_tags(loader, tag, node): name = node.__class__.__name__ if \"Seq\" in name:", "in i.name: if i.name not in seen: seen[i.name] = True", "if count and len(impls) != count: if count == 1:", "isinstance(value, list) and len(value) == 1: return value[0] return value", "\"-i\", callback=_callback, **kwargs) def show_result(self, data, tokens=False): rtype = \"tokens\"", "poyo import ruamel.yaml import runez import strictyaml import yaml as", "= token.start_mark.column + 1 result = \"%s[%s,%s]\" % (token.__class__.__name__, linenum,", "with open(path) as fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise", "\"%s,%s\" % (names[1:], default) names = [s.strip() for s in", "tokens_from_string(source) def _simplified(self, value): return value def ruamel_passthrough_tags(loader, tag, node):", "v return result return default_marshal(node.value) class RuamelImplementation(Implementation): name = \"ruamel\"", "value): if not value: return None impls = ImplementationCollection(value, default=default)", "implementation\") raise click.BadParameter(\"Need exactly %s\" % runez.plural(count, \"implementation\")) if count", "= self.tokens(content) if isinstance(data, list): data = \"\\n\".join(self.represented_token(t) for t", "def _tokens_from_path(self, path): with open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def", "= set() for names, values in self.combinations.items(): if name in", "return self._simplified(value) def tokens(self, source): return TestSettings.protected_call(self._tokenize, source) def represented_token(self,", "+= 1 if found == 0: self.unknown.append(name) self.combinations = None", "return str(token) def _deserialized(self, source): if hasattr(source, \"path\"): return self._deserialized_from_path(source.path)", "runez.flattened(value)) else: assert False result = \"%s %s\" % (result,", "def _deserialized_from_path(self, path): return load_path(path) def _deserialized_from_string(self, source): return load_string(source)", "return tokens_from_path(path) def _tokens_from_string(self, source): return tokens_from_string(source) def _simplified(self, value):", "impls metavar = \"I1,...\" hlp = \"Implementation(s)\" if count: hlp", "value is not None: if token.id == \"<scalar>\": value =", "av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available = dict((m.name,", "column = token.start_mark.column + 1 result = \"%s[%s,%s]\" % (token.__class__.__name__,", "s] seen = {} for name in names: found =", "RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available = dict((m.name, m()) for m", "or isinstance(data, Exception): rep = TestSettings.represented(data) message = \"---- %s:", "Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation):", "== 1: return impls.selected[0] return impls metavar = \"I1,...\" hlp", "[] self.selected = [] if names.startswith(\"+\"): names = \"%s,%s\" %", "if tokens else data.__class__.__name__ if data is not None else", "tokens or isinstance(data, Exception): rep = TestSettings.represented(data) message = \"----", "\"ruamel\" def _deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader)", "None impls = ImplementationCollection(value, default=default) if impls.unknown: raise click.BadParameter(\"Unknown implementation(s):", "if name == \"all\" or name in i.name: if i.name", "name = node.__class__.__name__ if \"Seq\" in name: result = []", "{} for i1 in self.selected: for i2 in self.selected: if", "node): name = node.__class__.__name__ if \"Seq\" in name: result =", "not None: if token.id == \"<scalar>\": value = represented_scalar(token.style, value)", "def represented_token(self, token): return str(token) def _deserialized(self, source): if hasattr(source,", "== \"<scalar>\": value = represented_scalar(token.style, value) elif token.id == \"<anchor>\":", "[s.strip() for s in names.split(\",\")] names = [s for s", "not None else \"None\" rep = data if not tokens", "result = \"%s %s\" % (result, value) return result class", "\"\"\"Implementation of loading a yml file\"\"\" name = None #", "source) return self._simplified(value) def tokens(self, source): return TestSettings.protected_call(self._tokenize, source) def", "(result, value) return result class PoyoImplementation(Implementation): name = \"poyo\" def", "(int | None): Optional: exact number of implementations that have", "return impls metavar = \"I1,...\" hlp = \"Implementation(s)\" if count:", "metavar = \"I1,...\" hlp = \"Implementation(s)\" if count: hlp =", "if impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\" % \", \".join(impls.unknown)) if", "TestSettings.protected_call(self._tokenize, source) def represented_token(self, token): return str(token) def _deserialized(self, source):", "\"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self, path): with open(path)", "def __init__(self, names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation,", "v in node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return result if \"Map\"", "\"Map\" in name: result = {} for k, v in", "_tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def", "= impl.name if self.combinations is None: self.combinations = {} for", "count: if count == 1: raise click.BadParameter(\"Need exactly 1 implementation\")", "a yml file\"\"\" name = None # type: str def", "name = \"implementation\" if count == 1 else \"implementations\" return", "= \"implementation\" if count == 1 else \"implementations\" return click.option(name,", "return click.option(name, \"-i\", callback=_callback, **kwargs) def show_result(self, data, tokens=False): rtype", "result return default_marshal(node.value) class RuamelImplementation(Implementation): name = \"ruamel\" def _deserialized_from_string(self,", "= ruamel_passthrough_tags(loader, tag, v) result[k] = v return result return", "track_result_combination(self, impl, data): if isinstance(data, Exception): value = runez.stringified(data) else:", "i in range(count)) kwargs.setdefault(\"help\", \"%s to use\" % hlp) kwargs.setdefault(\"show_default\",", "tag, v)) return result if \"Map\" in name: result =", "1: raise click.BadParameter(\"Need exactly 1 implementation\") raise click.BadParameter(\"Need exactly %s\"", "\"%s %s\" % (result, value) return result class PoyoImplementation(Implementation): name", "default_marshal, represented_scalar from . import TestSettings class ImplementationCollection(object): def __init__(self,", "impls = ImplementationCollection(value, default=default) if impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\"", "seen = {} for name in names: found = 0", "load_string, tokens_from_path, tokens_from_string from zyaml.marshal import decode, default_marshal, represented_scalar from", "\"<tag>\": assert isinstance(value, tuple) value = \" \".join(str(s) for s", "== \"<tag>\": assert isinstance(value, tuple) value = \" \".join(str(s) for", "return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise NotImplementedError() def _tokenize(self, source):", "curr = yaml_loader.get_token() while curr is not None: yield curr", "None) if value is not None: if token.id == \"<scalar>\":", "% token.name value = \" \".join(str(s) for s in runez.flattened(value))", "value = runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name = impl.name if", "<reponame>zsimic/sandbox import click import poyo import ruamel.yaml import runez import", "_deserialized_from_path(self, path): return load_path(path) def _deserialized_from_string(self, source): return load_string(source) def", "str def __repr__(self): return self.name @classmethod def option(cls, default=\"zyaml,ruamel\", count=None,", "\"strict\" def _deserialized_from_string(self, source): obj = strictyaml.dirty_load(source, allow_flow_style=True) return obj.data", "yaml_loader.get_token() while curr is not None: yield curr curr =", "hasattr(source, \"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self, path): with", "Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source) curr = yaml_loader.get_token()", "for s in names.split(\",\")] names = [s for s in", "av) self.unknown = [] self.selected = [] if names.startswith(\"+\"): names", "\".join(str(s) for s in runez.flattened(value)) elif token.id == \"<directive>\": result", ". import TestSettings class ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"): av", "if count == 1: return impls.selected[0] return impls metavar =", "class RuamelImplementation(Implementation): name = \"ruamel\" def _deserialized_from_string(self, source): y =", "= data if not tokens or isinstance(data, Exception): rep =", "implementation(s): %s\" % \", \".join(impls.unknown)) if count and len(impls) !=", "= [s.strip() for s in names.split(\",\")] names = [s for", "\" %s\" % token.name value = \" \".join(str(s) for s", "node.value: k = ruamel_passthrough_tags(loader, tag, k) v = ruamel_passthrough_tags(loader, tag,", "stringify=decode, keep_none=True, none_key=\"-null-\") name = impl.name if self.combinations is None:", "of implementations that have to specified **kwargs: Passed-through to click", "else data.__class__.__name__ if data is not None else \"None\" rep", "name = \"pyyaml\" def _deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def", "node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return result if \"Map\" in name:", "runez.stringified(data) else: value = runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name =", "return result if \"Map\" in name: result = {} for", "_tokenize(self, source): if hasattr(source, \"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source) def", "rep = TestSettings.represented(data) message = \"---- %s: %s\" % (runez.bold(self.name),", "path): return load_path(path) def _deserialized_from_string(self, source): return load_string(source) def _tokens_from_path(self,", "class PoyoImplementation(Implementation): name = \"poyo\" def _deserialized_from_string(self, source): return [poyo.parse_string(source)]", "\"\"\" Args: default (str | None): Default implementation(s) to use", "= \"ruamel\" def _deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags,", "__len__(self): return len(self.selected) def __iter__(self): for i in self.selected: yield", "< i2.name: self.combinations[(i1.name, i2.name)] = set() for names, values in", "click.option(name, \"-i\", callback=_callback, **kwargs) def show_result(self, data, tokens=False): rtype =", "s in names.split(\",\")] names = [s for s in names", "in node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return result if \"Map\" in", "\"%s[%s,%s]\" % (token.__class__.__name__, linenum, column) value = getattr(token, \"value\", None)", "self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self, path): with open(path) as fh:", "= node.__class__.__name__ if \"Seq\" in name: result = [] for", "that have to specified **kwargs: Passed-through to click \"\"\" kwargs[\"default\"]", "== 1: return value[0] return value class ZyamlImplementation(Implementation): name =", "is not None: if token.id == \"<scalar>\": value = represented_scalar(token.style,", "1 implementation\") raise click.BadParameter(\"Need exactly %s\" % runez.plural(count, \"implementation\")) if", "tag, k) v = ruamel_passthrough_tags(loader, tag, v) result[k] = v", "pyyaml from zyaml import load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal", "t in data) return data return self.deserialized(content) def deserialized(self, source):", "PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available = dict((m.name, m()) for m in", "for i2 in self.selected: if i1.name < i2.name: self.combinations[(i1.name, i2.name)]", "yield i class Implementation(object): \"\"\"Implementation of loading a yml file\"\"\"", "names = [s for s in names if s] seen", "return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self, path): with open(path) as", "return [poyo.parse_string(source)] class StrictImplementation(Implementation): name = \"strict\" def _deserialized_from_string(self, source):", "import TestSettings class ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"): av =", "% runez.plural(count, \"implementation\")) if count == 1: return impls.selected[0] return", "len(self.selected) def __iter__(self): for i in self.selected: yield i class", "curr = yaml_loader.get_token() def represented_token(self, token): linenum = token.start_mark.line +", "_tokens_from_string(self, source): raise NotImplementedError() def _simplified(self, value): if isinstance(value, list)", "{} for name in names: found = 0 for i", "RuamelImplementation(Implementation): name = \"ruamel\" def _deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\")", "for i in self.selected) def __len__(self): return len(self.selected) def __iter__(self):", "data.__class__.__name__ if data is not None else \"None\" rep =", "return self._tokens_from_string(source) def _tokens_from_path(self, path): with open(path) as fh: return", "= \" \".join(str(s) for s in runez.flattened(value)) else: assert False", "in names: values.add(value) def __repr__(self): return \",\".join(str(i) for i in", "class StrictImplementation(Implementation): name = \"strict\" def _deserialized_from_string(self, source): obj =", "(token.__class__.__name__, linenum, column) value = getattr(token, \"value\", None) if value", "StrictImplementation(Implementation): name = \"strict\" def _deserialized_from_string(self, source): obj = strictyaml.dirty_load(source,", "return None impls = ImplementationCollection(value, default=default) if impls.unknown: raise click.BadParameter(\"Unknown", "len(value) == 1: return value[0] return value class ZyamlImplementation(Implementation): name", "%s\" % (runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s - %s\"", "represented_scalar(token.style, value) elif token.id == \"<anchor>\": value = \"&%s\" %", "is not None else \"None\" rep = data if not", "tuple) value = \" \".join(str(s) for s in runez.flattened(value)) elif", "print(rep) def get_outcome(self, content, tokens=False): if tokens: data = self.tokens(content)", "% (message, rep)) return print(message) print(rep) def get_outcome(self, content, tokens=False):", "name = \"zyaml\" def _deserialized_from_path(self, path): return load_path(path) def _deserialized_from_string(self,", "value = runez.stringified(data) else: value = runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\")", "elif token.id == \"<tag>\": assert isinstance(value, tuple) value = \"", "def show_result(self, data, tokens=False): rtype = \"tokens\" if tokens else", "default_marshal(node.value) class RuamelImplementation(Implementation): name = \"ruamel\" def _deserialized_from_string(self, source): y", "_deserialized_from_string(self, source): return [poyo.parse_string(source)] class StrictImplementation(Implementation): name = \"strict\" def", "rep)) return print(message) print(rep) def get_outcome(self, content, tokens=False): if tokens:", "value elif token.id == \"<tag>\": assert isinstance(value, tuple) value =", "return result class PoyoImplementation(Implementation): name = \"poyo\" def _deserialized_from_string(self, source):", "values.add(value) def __repr__(self): return \",\".join(str(i) for i in self.selected) def", "ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source)", "show_result(self, data, tokens=False): rtype = \"tokens\" if tokens else data.__class__.__name__", "= {} for k, v in node.value: k = ruamel_passthrough_tags(loader,", "if isinstance(value, list) and len(value) == 1: return value[0] return", "list) and len(value) == 1: return value[0] return value class", "{} for k, v in node.value: k = ruamel_passthrough_tags(loader, tag,", "= [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available = dict((m.name, m())", "set() for names, values in self.combinations.items(): if name in names:", "\"%s to use\" % hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name", "default def _callback(_ctx, _param, value): if not value: return None", "in self.available.values(): if name == \"all\" or name in i.name:", "return value def ruamel_passthrough_tags(loader, tag, node): name = node.__class__.__name__ if", "default=default) if impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\" % \", \".join(impls.unknown))", "\"value\", None) if value is not None: if token.id ==", "tokens_from_path, tokens_from_string from zyaml.marshal import decode, default_marshal, represented_scalar from .", "Exception): value = runez.stringified(data) else: value = runez.represented_json(data, stringify=decode, keep_none=True,", "data, tokens=False): rtype = \"tokens\" if tokens else data.__class__.__name__ if", "default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available =", "[ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available = dict((m.name, m()) for", "= TestSettings.represented(data) message = \"---- %s: %s\" % (runez.bold(self.name), runez.dim(rtype))", "import click import poyo import ruamel.yaml import runez import strictyaml", "impl, data): if isinstance(data, Exception): value = runez.stringified(data) else: value", "value = TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def tokens(self, source): return", "y.load_all(source) def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name =", "result = [] for v in node.value: result.append(ruamel_passthrough_tags(loader, tag, v))", "source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def", "if token.id == \"<scalar>\": value = represented_scalar(token.style, value) elif token.id", "\"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self, path): with open(path)", "file\"\"\" name = None # type: str def __repr__(self): return", "and len(impls) != count: if count == 1: raise click.BadParameter(\"Need", "TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise NotImplementedError() def _simplified(self, value): if", "in node.value: k = ruamel_passthrough_tags(loader, tag, k) v = ruamel_passthrough_tags(loader,", "hlp = runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\" % (i +", "i2.name: self.combinations[(i1.name, i2.name)] = set() for names, values in self.combinations.items():", "ruamel_passthrough_tags(loader, tag, k) v = ruamel_passthrough_tags(loader, tag, v) result[k] =", "names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation] self.available", "elif token.id == \"<directive>\": result += \" %s\" % token.name", "kwargs.setdefault(\"help\", \"%s to use\" % hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar)", "value = \" \".join(str(s) for s in runez.flattened(value)) else: assert", "return value[0] return value class ZyamlImplementation(Implementation): name = \"zyaml\" def", "to use\" % hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name =", "% value elif token.id == \"<tag>\": assert isinstance(value, tuple) value", "to specified **kwargs: Passed-through to click \"\"\" kwargs[\"default\"] = default", "self.selected: yield i class Implementation(object): \"\"\"Implementation of loading a yml", "0 for i in self.available.values(): if name == \"all\" or", "True) kwargs.setdefault(\"metavar\", metavar) name = \"implementation\" if count == 1", "click.BadParameter(\"Need exactly %s\" % runez.plural(count, \"implementation\")) if count == 1:", "v)) return result if \"Map\" in name: result = {}", "import runez import strictyaml import yaml as pyyaml from zyaml", "value): return value def ruamel_passthrough_tags(loader, tag, node): name = node.__class__.__name__", "if count == 1: raise click.BadParameter(\"Need exactly 1 implementation\") raise", "source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def _deserialized_from_string(self,", "in runez.flattened(value)) elif token.id == \"<directive>\": result += \" %s\"", "path): return tokens_from_path(path) def _tokens_from_string(self, source): return tokens_from_string(source) def _simplified(self,", "= \"%s[%s,%s]\" % (token.__class__.__name__, linenum, column) value = getattr(token, \"value\",", "self.unknown = [] self.selected = [] if names.startswith(\"+\"): names =", "+= \" %s\" % token.name value = \" \".join(str(s) for", "= 0 for i in self.available.values(): if name == \"all\"", "self.selected.append(i) found += 1 if found == 0: self.unknown.append(name) self.combinations", "linenum = token.start_mark.line + 1 column = token.start_mark.column + 1", "i.name: if i.name not in seen: seen[i.name] = True self.selected.append(i)", "value = \"*%s\" % value elif token.id == \"<tag>\": assert", "class Implementation(object): \"\"\"Implementation of loading a yml file\"\"\" name =", "== 0: self.unknown.append(name) self.combinations = None def track_result_combination(self, impl, data):", "= runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name = impl.name if self.combinations", "count and len(impls) != count: if count == 1: raise", "names if s] seen = {} for name in names:", "load_path(path) def _deserialized_from_string(self, source): return load_string(source) def _tokens_from_path(self, path): return", "False result = \"%s %s\" % (result, value) return result", "\"implementation\") metavar = \",\".join(\"I%s\" % (i + 1) for i", "token.id == \"<anchor>\": value = \"&%s\" % value elif token.id", "PoyoImplementation(Implementation): name = \"poyo\" def _deserialized_from_string(self, source): return [poyo.parse_string(source)] class", "self.combinations = {} for i1 in self.selected: for i2 in", "for i in range(count)) kwargs.setdefault(\"help\", \"%s to use\" % hlp)", "if name in names: values.add(value) def __repr__(self): return \",\".join(str(i) for", "**kwargs): \"\"\" Args: default (str | None): Default implementation(s) to", "| None): Default implementation(s) to use count (int | None):", "kwargs[\"default\"] = default def _callback(_ctx, _param, value): if not value:", "data if not tokens or isinstance(data, Exception): rep = TestSettings.represented(data)", "count == 1: raise click.BadParameter(\"Need exactly 1 implementation\") raise click.BadParameter(\"Need", "name = \"strict\" def _deserialized_from_string(self, source): obj = strictyaml.dirty_load(source, allow_flow_style=True)", "= v return result return default_marshal(node.value) class RuamelImplementation(Implementation): name =", "specified **kwargs: Passed-through to click \"\"\" kwargs[\"default\"] = default def", "in av) self.unknown = [] self.selected = [] if names.startswith(\"+\"):", "y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self,", "k = ruamel_passthrough_tags(loader, tag, k) v = ruamel_passthrough_tags(loader, tag, v)", "type: str def __repr__(self): return self.name @classmethod def option(cls, default=\"zyaml,ruamel\",", "def represented_token(self, token): linenum = token.start_mark.line + 1 column =", "else: assert False result = \"%s %s\" % (result, value)", "names, values in self.combinations.items(): if name in names: values.add(value) def", "_deserialized(self, source): if hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def", "def _tokens_from_path(self, path): return tokens_from_path(path) def _tokens_from_string(self, source): return tokens_from_string(source)", "callback=_callback, **kwargs) def show_result(self, data, tokens=False): rtype = \"tokens\" if", "= \"---- %s: %s\" % (runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError):", "for m in av) self.unknown = [] self.selected = []", "i2 in self.selected: if i1.name < i2.name: self.combinations[(i1.name, i2.name)] =", "def _deserialized_from_string(self, source): raise NotImplementedError() def _tokenize(self, source): if hasattr(source,", "= \"%s,%s\" % (names[1:], default) names = [s.strip() for s", "data is not None else \"None\" rep = data if", "def tokens(self, source): return TestSettings.protected_call(self._tokenize, source) def represented_token(self, token): return", "= \"strict\" def _deserialized_from_string(self, source): obj = strictyaml.dirty_load(source, allow_flow_style=True) return", "result class PoyoImplementation(Implementation): name = \"poyo\" def _deserialized_from_string(self, source): return", "pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source) curr =", "for s in names if s] seen = {} for", "== \"all\" or name in i.name: if i.name not in", "in names: found = 0 for i in self.available.values(): if", "= ImplementationCollection(value, default=default) if impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\" %", "represented_scalar from . import TestSettings class ImplementationCollection(object): def __init__(self, names,", "\" \".join(str(s) for s in runez.flattened(value)) elif token.id == \"<directive>\":", "for t in data) return data return self.deserialized(content) def deserialized(self,", "tokens=False): rtype = \"tokens\" if tokens else data.__class__.__name__ if data", "**kwargs) def show_result(self, data, tokens=False): rtype = \"tokens\" if tokens", "None: if token.id == \"<scalar>\": value = represented_scalar(token.style, value) elif", "value: return None impls = ImplementationCollection(value, default=default) if impls.unknown: raise", "self.selected: if i1.name < i2.name: self.combinations[(i1.name, i2.name)] = set() for", "return self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self, path): with open(path) as", "self.available = dict((m.name, m()) for m in av) self.unknown =", "\"<scalar>\": value = represented_scalar(token.style, value) elif token.id == \"<anchor>\": value", "in seen: seen[i.name] = True self.selected.append(i) found += 1 if", "self._simplified(value) def tokens(self, source): return TestSettings.protected_call(self._tokenize, source) def represented_token(self, token):", "runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name = impl.name if self.combinations is", "def _deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader", "source): return tokens_from_string(source) def _simplified(self, value): return value def ruamel_passthrough_tags(loader,", "isinstance(value, tuple) value = \" \".join(str(s) for s in runez.flattened(value))", "def _tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while", "token): return str(token) def _deserialized(self, source): if hasattr(source, \"path\"): return", "name in names: values.add(value) def __repr__(self): return \",\".join(str(i) for i", "range(count)) kwargs.setdefault(\"help\", \"%s to use\" % hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\",", "if not value: return None impls = ImplementationCollection(value, default=default) if", "NotImplementedError() def _simplified(self, value): if isinstance(value, list) and len(value) ==", "\"<anchor>\": value = \"&%s\" % value elif token.id == \"<alias>\":", "k) v = ruamel_passthrough_tags(loader, tag, v) result[k] = v return", "\".join(str(s) for s in runez.flattened(value)) else: assert False result =", "seen[i.name] = True self.selected.append(i) found += 1 if found ==", "_tokens_from_path(self, path): with open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self,", "data) return data return self.deserialized(content) def deserialized(self, source): value =", "class ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation,", "click \"\"\" kwargs[\"default\"] = default def _callback(_ctx, _param, value): if", "[] if names.startswith(\"+\"): names = \"%s,%s\" % (names[1:], default) names", "names: values.add(value) def __repr__(self): return \",\".join(str(i) for i in self.selected)", "value) elif token.id == \"<anchor>\": value = \"&%s\" % value", "default (str | None): Default implementation(s) to use count (int", "ImplementationCollection(value, default=default) if impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\" % \",", "= \"tokens\" if tokens else data.__class__.__name__ if data is not", "_callback(_ctx, _param, value): if not value: return None impls =", "i class Implementation(object): \"\"\"Implementation of loading a yml file\"\"\" name", "[poyo.parse_string(source)] class StrictImplementation(Implementation): name = \"strict\" def _deserialized_from_string(self, source): obj", "getattr(token, \"value\", None) if value is not None: if token.id", "found = 0 for i in self.available.values(): if name ==", "_tokens_from_path(self, path): return tokens_from_path(path) def _tokens_from_string(self, source): return tokens_from_string(source) def", "class PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def _deserialized_from_string(self, source): return pyyaml.load_all(source,", "ruamel_passthrough_tags(loader, tag, v) result[k] = v return result return default_marshal(node.value)", "TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def tokens(self, source): return TestSettings.protected_call(self._tokenize, source)", "tokens(self, source): return TestSettings.protected_call(self._tokenize, source) def represented_token(self, token): return str(token)", "True self.selected.append(i) found += 1 if found == 0: self.unknown.append(name)", "else: value = runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name = impl.name", "name in i.name: if i.name not in seen: seen[i.name] =", "count: hlp = runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\" % (i", "v = ruamel_passthrough_tags(loader, tag, v) result[k] = v return result", "_deserialized_from_string(self, source): return load_string(source) def _tokens_from_path(self, path): return tokens_from_path(path) def", "1 result = \"%s[%s,%s]\" % (token.__class__.__name__, linenum, column) value =", "isinstance(data, list): data = \"\\n\".join(self.represented_token(t) for t in data) return", "self.selected) def __len__(self): return len(self.selected) def __iter__(self): for i in", "click.BadParameter(\"Need exactly 1 implementation\") raise click.BadParameter(\"Need exactly %s\" % runez.plural(count,", "TestSettings.represented(data) message = \"---- %s: %s\" % (runez.bold(self.name), runez.dim(rtype)) if", "source): if hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self,", "source): value = TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def tokens(self, source):", "self._deserialized_from_string(source) def _deserialized_from_path(self, path): with open(path) as fh: return self._deserialized_from_string(fh.read())", "result = {} for k, v in node.value: k =", "(runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s - %s\" % (message,", "while curr is not None: yield curr curr = yaml_loader.get_token()", "runez.flattened(value)) elif token.id == \"<directive>\": result += \" %s\" %", "open(path) as fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise NotImplementedError()", "= [s for s in names if s] seen =", "_simplified(self, value): if isinstance(value, list) and len(value) == 1: return", "result = \"%s[%s,%s]\" % (token.__class__.__name__, linenum, column) value = getattr(token,", "i in self.selected: yield i class Implementation(object): \"\"\"Implementation of loading", "%s: %s\" % (runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s -", "to use count (int | None): Optional: exact number of", "if \"Seq\" in name: result = [] for v in", "0: self.unknown.append(name) self.combinations = None def track_result_combination(self, impl, data): if", "in name: result = [] for v in node.value: result.append(ruamel_passthrough_tags(loader,", "= runez.stringified(data) else: value = runez.represented_json(data, stringify=decode, keep_none=True, none_key=\"-null-\") name", "def _deserialized_from_path(self, path): with open(path) as fh: return self._deserialized_from_string(fh.read()) def", "\"all\" or name in i.name: if i.name not in seen:", "if i1.name < i2.name: self.combinations[(i1.name, i2.name)] = set() for names,", "Implementation(object): \"\"\"Implementation of loading a yml file\"\"\" name = None", "in self.selected: yield i class Implementation(object): \"\"\"Implementation of loading a", "token.id == \"<scalar>\": value = represented_scalar(token.style, value) elif token.id ==", "name = \"poyo\" def _deserialized_from_string(self, source): return [poyo.parse_string(source)] class StrictImplementation(Implementation):", "not tokens or isinstance(data, Exception): rep = TestSettings.represented(data) message =", "if value is not None: if token.id == \"<scalar>\": value", "name = \"ruamel\" def _deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\",", "have to specified **kwargs: Passed-through to click \"\"\" kwargs[\"default\"] =", "s in names if s] seen = {} for name", "token.start_mark.column + 1 result = \"%s[%s,%s]\" % (token.__class__.__name__, linenum, column)", "= \"pyyaml\" def _deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self,", "k, v in node.value: k = ruamel_passthrough_tags(loader, tag, k) v", "source): if hasattr(source, \"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self,", "import ruamel.yaml import runez import strictyaml import yaml as pyyaml", "= True self.selected.append(i) found += 1 if found == 0:", "None # type: str def __repr__(self): return self.name @classmethod def", "\"implementations\" return click.option(name, \"-i\", callback=_callback, **kwargs) def show_result(self, data, tokens=False):", "represented_token(self, token): return str(token) def _deserialized(self, source): if hasattr(source, \"path\"):", "data return self.deserialized(content) def deserialized(self, source): value = TestSettings.protected_call(self._deserialized, source)", "%s\" % \", \".join(impls.unknown)) if count and len(impls) != count:", "in self.selected) def __len__(self): return len(self.selected) def __iter__(self): for i", "loading a yml file\"\"\" name = None # type: str", "== \"<alias>\": value = \"*%s\" % value elif token.id ==", "content, tokens=False): if tokens: data = self.tokens(content) if isinstance(data, list):", "if isinstance(data, Exception): value = runez.stringified(data) else: value = runez.represented_json(data,", "impl.name if self.combinations is None: self.combinations = {} for i1", "isinstance(data, Exception): rep = TestSettings.represented(data) message = \"---- %s: %s\"", "return self.name @classmethod def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args:", "click import poyo import ruamel.yaml import runez import strictyaml import", "tokens=False): if tokens: data = self.tokens(content) if isinstance(data, list): data", "not value: return None impls = ImplementationCollection(value, default=default) if impls.unknown:", "if count: hlp = runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\" %", "= \",\".join(\"I%s\" % (i + 1) for i in range(count))", "as fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise NotImplementedError() def", "fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise NotImplementedError() def _simplified(self,", "return load_string(source) def _tokens_from_path(self, path): return tokens_from_path(path) def _tokens_from_string(self, source):", "== \"<directive>\": result += \" %s\" % token.name value =", "impls.selected[0] return impls metavar = \"I1,...\" hlp = \"Implementation(s)\" if", "= \"zyaml\" def _deserialized_from_path(self, path): return load_path(path) def _deserialized_from_string(self, source):", "count == 1 else \"implementations\" return click.option(name, \"-i\", callback=_callback, **kwargs)", "return default_marshal(node.value) class RuamelImplementation(Implementation): name = \"ruamel\" def _deserialized_from_string(self, source):", "m in av) self.unknown = [] self.selected = [] if", "in range(count)) kwargs.setdefault(\"help\", \"%s to use\" % hlp) kwargs.setdefault(\"show_default\", True)", "__init__(self, names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation, PoyoImplementation, StrictImplementation]", "return value class ZyamlImplementation(Implementation): name = \"zyaml\" def _deserialized_from_path(self, path):", "if isinstance(data, list): data = \"\\n\".join(self.represented_token(t) for t in data)", "runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\" % (i + 1) for", "= yaml_loader.get_token() def represented_token(self, token): linenum = token.start_mark.line + 1", "\"None\" rep = data if not tokens or isinstance(data, Exception):", "in data) return data return self.deserialized(content) def deserialized(self, source): value", "ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation, RuamelImplementation, PyyamlBaseImplementation,", "\"\\n\".join(self.represented_token(t) for t in data) return data return self.deserialized(content) def", "\" \".join(str(s) for s in runez.flattened(value)) else: assert False result", "value def ruamel_passthrough_tags(loader, tag, node): name = node.__class__.__name__ if \"Seq\"", "def _deserialized_from_string(self, source): return load_string(source) def _tokens_from_path(self, path): return tokens_from_path(path)", "import yaml as pyyaml from zyaml import load_path, load_string, tokens_from_path,", "(message, rep)) return print(message) print(rep) def get_outcome(self, content, tokens=False): if", "def ruamel_passthrough_tags(loader, tag, node): name = node.__class__.__name__ if \"Seq\" in", "= [] if names.startswith(\"+\"): names = \"%s,%s\" % (names[1:], default)", "to click \"\"\" kwargs[\"default\"] = default def _callback(_ctx, _param, value):", "isinstance(data, Exception): value = runez.stringified(data) else: value = runez.represented_json(data, stringify=decode,", "= yaml_loader.get_token() while curr is not None: yield curr curr", "# type: str def __repr__(self): return self.name @classmethod def option(cls,", "name: result = [] for v in node.value: result.append(ruamel_passthrough_tags(loader, tag,", "else \"None\" rep = data if not tokens or isinstance(data,", "\"zyaml\" def _deserialized_from_path(self, path): return load_path(path) def _deserialized_from_string(self, source): return", "= ruamel_passthrough_tags(loader, tag, k) v = ruamel_passthrough_tags(loader, tag, v) result[k]", "return TestSettings.protected_call(self._tokenize, source) def represented_token(self, token): return str(token) def _deserialized(self,", "def _tokenize(self, source): if hasattr(source, \"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source)", "as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise NotImplementedError() def", "value[0] return value class ZyamlImplementation(Implementation): name = \"zyaml\" def _deserialized_from_path(self,", "import decode, default_marshal, represented_scalar from . import TestSettings class ImplementationCollection(object):", "token.id == \"<tag>\": assert isinstance(value, tuple) value = \" \".join(str(s)", "\"Implementation(s)\" if count: hlp = runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\"", "of loading a yml file\"\"\" name = None # type:", "count == 1: return impls.selected[0] return impls metavar = \"I1,...\"", "raise click.BadParameter(\"Need exactly %s\" % runez.plural(count, \"implementation\")) if count ==", "node.__class__.__name__ if \"Seq\" in name: result = [] for v", "assert isinstance(value, tuple) value = \" \".join(str(s) for s in", "m()) for m in av) self.unknown = [] self.selected =", "def __iter__(self): for i in self.selected: yield i class Implementation(object):", "kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name = \"implementation\" if count ==", "+ 1 result = \"%s[%s,%s]\" % (token.__class__.__name__, linenum, column) value", "path): with open(path) as fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source):", "= \"Implementation(s)\" if count: hlp = runez.plural(count, \"implementation\") metavar =", "names = [s.strip() for s in names.split(\",\")] names = [s", "[] for v in node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return result", "result += \" %s\" % token.name value = \" \".join(str(s)", "== 1: raise click.BadParameter(\"Need exactly 1 implementation\") raise click.BadParameter(\"Need exactly", "return impls.selected[0] return impls metavar = \"I1,...\" hlp = \"Implementation(s)\"", "fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise NotImplementedError() def _tokenize(self,", "names.split(\",\")] names = [s for s in names if s]", "= runez.plural(count, \"implementation\") metavar = \",\".join(\"I%s\" % (i + 1)", "pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while curr is not None: yield", "ZyamlImplementation(Implementation): name = \"zyaml\" def _deserialized_from_path(self, path): return load_path(path) def", "= [] for v in node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return", "yaml_loader = pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while curr is not", "if \"Map\" in name: result = {} for k, v", "in self.selected: for i2 in self.selected: if i1.name < i2.name:", "use count (int | None): Optional: exact number of implementations", "i.name not in seen: seen[i.name] = True self.selected.append(i) found +=", "1: return impls.selected[0] return impls metavar = \"I1,...\" hlp =", "open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise NotImplementedError()", "value = represented_scalar(token.style, value) elif token.id == \"<anchor>\": value =", "metavar = \",\".join(\"I%s\" % (i + 1) for i in", "= \"I1,...\" hlp = \"Implementation(s)\" if count: hlp = runez.plural(count,", "decode, default_marshal, represented_scalar from . import TestSettings class ImplementationCollection(object): def", "if data is not None else \"None\" rep = data", "self.deserialized(content) def deserialized(self, source): value = TestSettings.protected_call(self._deserialized, source) return self._simplified(value)", "if isinstance(data, NotImplementedError): print(\"%s - %s\" % (message, rep)) return", "_tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while curr", "\", \".join(impls.unknown)) if count and len(impls) != count: if count", "dict((m.name, m()) for m in av) self.unknown = [] self.selected", "import strictyaml import yaml as pyyaml from zyaml import load_path,", "or name in i.name: if i.name not in seen: seen[i.name]", "\"implementation\")) if count == 1: return impls.selected[0] return impls metavar", "= {} for i1 in self.selected: for i2 in self.selected:", "metavar) name = \"implementation\" if count == 1 else \"implementations\"", "if count == 1 else \"implementations\" return click.option(name, \"-i\", callback=_callback,", "return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def _deserialized_from_string(self, source):", "= dict((m.name, m()) for m in av) self.unknown = []", "yml file\"\"\" name = None # type: str def __repr__(self):", "value = getattr(token, \"value\", None) if value is not None:", "value elif token.id == \"<alias>\": value = \"*%s\" % value", "for names, values in self.combinations.items(): if name in names: values.add(value)", "assert False result = \"%s %s\" % (result, value) return", "Exception): rep = TestSettings.represented(data) message = \"---- %s: %s\" %", "% (runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s - %s\" %", "def _simplified(self, value): if isinstance(value, list) and len(value) == 1:", "if self.combinations is None: self.combinations = {} for i1 in", "count=None, **kwargs): \"\"\" Args: default (str | None): Default implementation(s)", "%s\" % (message, rep)) return print(message) print(rep) def get_outcome(self, content,", "found += 1 if found == 0: self.unknown.append(name) self.combinations =", "def _deserialized_from_string(self, source): return [poyo.parse_string(source)] class StrictImplementation(Implementation): name = \"strict\"", "rep = data if not tokens or isinstance(data, Exception): rep", "= \"%s %s\" % (result, value) return result class PoyoImplementation(Implementation):", "\",\".join(str(i) for i in self.selected) def __len__(self): return len(self.selected) def", "ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self, source): return", "self.selected = [] if names.startswith(\"+\"): names = \"%s,%s\" % (names[1:],", "result[k] = v return result return default_marshal(node.value) class RuamelImplementation(Implementation): name", "% (result, value) return result class PoyoImplementation(Implementation): name = \"poyo\"", "keep_none=True, none_key=\"-null-\") name = impl.name if self.combinations is None: self.combinations", "use\" % hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name = \"implementation\"", "name = None # type: str def __repr__(self): return self.name", "default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args: default (str | None): Default", "click.BadParameter(\"Unknown implementation(s): %s\" % \", \".join(impls.unknown)) if count and len(impls)", "default) names = [s.strip() for s in names.split(\",\")] names =", "source): raise NotImplementedError() def _tokenize(self, source): if hasattr(source, \"path\"): return", "!= count: if count == 1: raise click.BadParameter(\"Need exactly 1", "curr is not None: yield curr curr = yaml_loader.get_token() def", "= \"\\n\".join(self.represented_token(t) for t in data) return data return self.deserialized(content)", "def _deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return", "ruamel.yaml import runez import strictyaml import yaml as pyyaml from", "name = impl.name if self.combinations is None: self.combinations = {}", "number of implementations that have to specified **kwargs: Passed-through to", "def track_result_combination(self, impl, data): if isinstance(data, Exception): value = runez.stringified(data)", "load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal import decode, default_marshal, represented_scalar", "self.combinations[(i1.name, i2.name)] = set() for names, values in self.combinations.items(): if", "def get_outcome(self, content, tokens=False): if tokens: data = self.tokens(content) if", "tokens: data = self.tokens(content) if isinstance(data, list): data = \"\\n\".join(self.represented_token(t)", "return self.deserialized(content) def deserialized(self, source): value = TestSettings.protected_call(self._deserialized, source) return", "None: yield curr curr = yaml_loader.get_token() def represented_token(self, token): linenum", "yaml_loader.get_token() def represented_token(self, token): linenum = token.start_mark.line + 1 column", "% value elif token.id == \"<alias>\": value = \"*%s\" %", "import poyo import ruamel.yaml import runez import strictyaml import yaml", "raise NotImplementedError() def _tokenize(self, source): if hasattr(source, \"path\"): return self._tokens_from_path(source.path)", "result if \"Map\" in name: result = {} for k,", "elif token.id == \"<alias>\": value = \"*%s\" % value elif", "name: result = {} for k, v in node.value: k", "implementations that have to specified **kwargs: Passed-through to click \"\"\"", "column) value = getattr(token, \"value\", None) if value is not", "if not tokens or isinstance(data, Exception): rep = TestSettings.represented(data) message", "= default def _callback(_ctx, _param, value): if not value: return", "(names[1:], default) names = [s.strip() for s in names.split(\",\")] names", "self.name @classmethod def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args: default", "values in self.combinations.items(): if name in names: values.add(value) def __repr__(self):", "self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self, path): with open(path) as fh:", "strictyaml import yaml as pyyaml from zyaml import load_path, load_string,", "def __repr__(self): return self.name @classmethod def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs):", "_tokens_from_string(self, source): return tokens_from_string(source) def _simplified(self, value): return value def", "print(\"%s - %s\" % (message, rep)) return print(message) print(rep) def", "value = \"&%s\" % value elif token.id == \"<alias>\": value", "self._tokens_from_string(source) def _tokens_from_path(self, path): with open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read()))", "exact number of implementations that have to specified **kwargs: Passed-through", "_deserialized_from_string(self, source): y = ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source)", "is None: self.combinations = {} for i1 in self.selected: for", "ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def _deserialized_from_string(self, source): return", "_simplified(self, value): return value def ruamel_passthrough_tags(loader, tag, node): name =", "is not None: yield curr curr = yaml_loader.get_token() def represented_token(self,", "len(impls) != count: if count == 1: raise click.BadParameter(\"Need exactly", "with open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise", "\"I1,...\" hlp = \"Implementation(s)\" if count: hlp = runez.plural(count, \"implementation\")", "_deserialized_from_string(self, source): raise NotImplementedError() def _tokenize(self, source): if hasattr(source, \"path\"):", "= pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while curr is not None:", "for i in self.selected: yield i class Implementation(object): \"\"\"Implementation of", "in names.split(\",\")] names = [s for s in names if", "tag, v) result[k] = v return result return default_marshal(node.value) class", "raise click.BadParameter(\"Unknown implementation(s): %s\" % \", \".join(impls.unknown)) if count and", "names = \"%s,%s\" % (names[1:], default) names = [s.strip() for", "names.startswith(\"+\"): names = \"%s,%s\" % (names[1:], default) names = [s.strip()", "tokens else data.__class__.__name__ if data is not None else \"None\"", "hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self, path): with", "== 1 else \"implementations\" return click.option(name, \"-i\", callback=_callback, **kwargs) def", "value) return result class PoyoImplementation(Implementation): name = \"poyo\" def _deserialized_from_string(self,", "v) result[k] = v return result return default_marshal(node.value) class RuamelImplementation(Implementation):", "value = \" \".join(str(s) for s in runez.flattened(value)) elif token.id", "in name: result = {} for k, v in node.value:", "return self._deserialized_from_string(source) def _deserialized_from_path(self, path): with open(path) as fh: return", "[s for s in names if s] seen = {}", "__iter__(self): for i in self.selected: yield i class Implementation(object): \"\"\"Implementation", "def _tokens_from_string(self, source): return tokens_from_string(source) def _simplified(self, value): return value", "= None # type: str def __repr__(self): return self.name @classmethod", "1) for i in range(count)) kwargs.setdefault(\"help\", \"%s to use\" %", "\"tokens\" if tokens else data.__class__.__name__ if data is not None", "name in names: found = 0 for i in self.available.values():", "found == 0: self.unknown.append(name) self.combinations = None def track_result_combination(self, impl,", "\"---- %s: %s\" % (runez.bold(self.name), runez.dim(rtype)) if isinstance(data, NotImplementedError): print(\"%s", "token.id == \"<alias>\": value = \"*%s\" % value elif token.id", "Default implementation(s) to use count (int | None): Optional: exact", "self.selected: for i2 in self.selected: if i1.name < i2.name: self.combinations[(i1.name,", "= \"*%s\" % value elif token.id == \"<tag>\": assert isinstance(value,", "self.tokens(content) if isinstance(data, list): data = \"\\n\".join(self.represented_token(t) for t in", "rtype = \"tokens\" if tokens else data.__class__.__name__ if data is", "tokens_from_string from zyaml.marshal import decode, default_marshal, represented_scalar from . import", "return len(self.selected) def __iter__(self): for i in self.selected: yield i", "source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source)", "def __repr__(self): return \",\".join(str(i) for i in self.selected) def __len__(self):", "self.combinations = None def track_result_combination(self, impl, data): if isinstance(data, Exception):", "for name in names: found = 0 for i in", "tokens_from_path(path) def _tokens_from_string(self, source): return tokens_from_string(source) def _simplified(self, value): return", "path): with open(path) as fh: return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source):", "exactly 1 implementation\") raise click.BadParameter(\"Need exactly %s\" % runez.plural(count, \"implementation\"))", "TestSettings class ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"): av = [ZyamlImplementation,", "\"pyyaml\" def _deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source):", "return result return default_marshal(node.value) class RuamelImplementation(Implementation): name = \"ruamel\" def", "for i1 in self.selected: for i2 in self.selected: if i1.name", "i1 in self.selected: for i2 in self.selected: if i1.name <", "token.name value = \" \".join(str(s) for s in runez.flattened(value)) else:", "== \"<anchor>\": value = \"&%s\" % value elif token.id ==", "def deserialized(self, source): value = TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def", "= [] self.selected = [] if names.startswith(\"+\"): names = \"%s,%s\"", "runez.plural(count, \"implementation\")) if count == 1: return impls.selected[0] return impls", "yield curr curr = yaml_loader.get_token() def represented_token(self, token): linenum =", "print(message) print(rep) def get_outcome(self, content, tokens=False): if tokens: data =", "if i.name not in seen: seen[i.name] = True self.selected.append(i) found", "Passed-through to click \"\"\" kwargs[\"default\"] = default def _callback(_ctx, _param,", "message = \"---- %s: %s\" % (runez.bold(self.name), runez.dim(rtype)) if isinstance(data,", "None def track_result_combination(self, impl, data): if isinstance(data, Exception): value =", "if found == 0: self.unknown.append(name) self.combinations = None def track_result_combination(self,", "hlp = \"Implementation(s)\" if count: hlp = runez.plural(count, \"implementation\") metavar", "% \", \".join(impls.unknown)) if count and len(impls) != count: if", "\"<directive>\": result += \" %s\" % token.name value = \"", "source) def represented_token(self, token): return str(token) def _deserialized(self, source): if", "s in runez.flattened(value)) elif token.id == \"<directive>\": result += \"", "i in self.available.values(): if name == \"all\" or name in", "_param, value): if not value: return None impls = ImplementationCollection(value,", "from zyaml import load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal import", "self.available.values(): if name == \"all\" or name in i.name: if", "not in seen: seen[i.name] = True self.selected.append(i) found += 1", "+ 1) for i in range(count)) kwargs.setdefault(\"help\", \"%s to use\"", "raise NotImplementedError() def _simplified(self, value): if isinstance(value, list) and len(value)", "def __len__(self): return len(self.selected) def __iter__(self): for i in self.selected:", "from zyaml.marshal import decode, default_marshal, represented_scalar from . import TestSettings", "\".join(impls.unknown)) if count and len(impls) != count: if count ==", "return load_path(path) def _deserialized_from_string(self, source): return load_string(source) def _tokens_from_path(self, path):", "\"implementation\" if count == 1 else \"implementations\" return click.option(name, \"-i\",", "%s\" % runez.plural(count, \"implementation\")) if count == 1: return impls.selected[0]", "get_outcome(self, content, tokens=False): if tokens: data = self.tokens(content) if isinstance(data,", "Optional: exact number of implementations that have to specified **kwargs:", "list): data = \"\\n\".join(self.represented_token(t) for t in data) return data", "def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name = \"pyyaml\"", "curr curr = yaml_loader.get_token() def represented_token(self, token): linenum = token.start_mark.line", "i1.name < i2.name: self.combinations[(i1.name, i2.name)] = set() for names, values", "if tokens: data = self.tokens(content) if isinstance(data, list): data =", "_deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader =", "token): linenum = token.start_mark.line + 1 column = token.start_mark.column +", "return y.load_all(source) def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class PyyamlBaseImplementation(Implementation): name", "in names if s] seen = {} for name in", "if s] seen = {} for name in names: found", "__repr__(self): return self.name @classmethod def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\"", "1 else \"implementations\" return click.option(name, \"-i\", callback=_callback, **kwargs) def show_result(self,", "= ruamel.yaml.YAML(typ=\"safe\") ruamel.yaml.add_multi_constructor(\"\", ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self, source):", "if hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source) def _deserialized_from_path(self, path):", "1 if found == 0: self.unknown.append(name) self.combinations = None def", "(str | None): Default implementation(s) to use count (int |", "self.combinations is None: self.combinations = {} for i1 in self.selected:", "= {} for name in names: found = 0 for", "def _simplified(self, value): return value def ruamel_passthrough_tags(loader, tag, node): name", "for s in runez.flattened(value)) else: assert False result = \"%s", "runez import strictyaml import yaml as pyyaml from zyaml import", "None: self.combinations = {} for i1 in self.selected: for i2", "None): Default implementation(s) to use count (int | None): Optional:", "+ 1 column = token.start_mark.column + 1 result = \"%s[%s,%s]\"", "count (int | None): Optional: exact number of implementations that", "%s\" % (result, value) return result class PoyoImplementation(Implementation): name =", "@classmethod def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args: default (str", "% (names[1:], default) names = [s.strip() for s in names.split(\",\")]", "str(token) def _deserialized(self, source): if hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return", "def option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args: default (str |", "in runez.flattened(value)) else: assert False result = \"%s %s\" %", "source): return load_string(source) def _tokens_from_path(self, path): return tokens_from_path(path) def _tokens_from_string(self,", "\"<alias>\": value = \"*%s\" % value elif token.id == \"<tag>\":", "None else \"None\" rep = data if not tokens or", "option(cls, default=\"zyaml,ruamel\", count=None, **kwargs): \"\"\" Args: default (str | None):", "elif token.id == \"<anchor>\": value = \"&%s\" % value elif", "token.start_mark.line + 1 column = token.start_mark.column + 1 result =", "and len(value) == 1: return value[0] return value class ZyamlImplementation(Implementation):", "as pyyaml from zyaml import load_path, load_string, tokens_from_path, tokens_from_string from", "= TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def tokens(self, source): return TestSettings.protected_call(self._tokenize,", "tag, node): name = node.__class__.__name__ if \"Seq\" in name: result", "represented_token(self, token): linenum = token.start_mark.line + 1 column = token.start_mark.column", "= getattr(token, \"value\", None) if value is not None: if", "= token.start_mark.line + 1 column = token.start_mark.column + 1 result", "% (token.__class__.__name__, linenum, column) value = getattr(token, \"value\", None) if", "NotImplementedError): print(\"%s - %s\" % (message, rep)) return print(message) print(rep)", "return TestSettings.unwrapped(self._tokens_from_string(fh.read())) def _tokens_from_string(self, source): raise NotImplementedError() def _simplified(self, value):", "%s\" % token.name value = \" \".join(str(s) for s in", "return data return self.deserialized(content) def deserialized(self, source): value = TestSettings.protected_call(self._deserialized,", "\"Seq\" in name: result = [] for v in node.value:", "\"*%s\" % value elif token.id == \"<tag>\": assert isinstance(value, tuple)", "= \"&%s\" % value elif token.id == \"<alias>\": value =", "v in node.value: k = ruamel_passthrough_tags(loader, tag, k) v =", "(i + 1) for i in range(count)) kwargs.setdefault(\"help\", \"%s to", "hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name = \"implementation\" if count", "1: return value[0] return value class ZyamlImplementation(Implementation): name = \"zyaml\"", "PyyamlBaseImplementation(Implementation): name = \"pyyaml\" def _deserialized_from_string(self, source): return pyyaml.load_all(source, Loader=pyyaml.BaseLoader)", "value): if isinstance(value, list) and len(value) == 1: return value[0]", "import load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal import decode, default_marshal,", "return \",\".join(str(i) for i in self.selected) def __len__(self): return len(self.selected)", "return print(message) print(rep) def get_outcome(self, content, tokens=False): if tokens: data", "if names.startswith(\"+\"): names = \"%s,%s\" % (names[1:], default) names =", "name == \"all\" or name in i.name: if i.name not", "for i in self.available.values(): if name == \"all\" or name", "for k, v in node.value: k = ruamel_passthrough_tags(loader, tag, k)", "data = self.tokens(content) if isinstance(data, list): data = \"\\n\".join(self.represented_token(t) for", "impls.unknown: raise click.BadParameter(\"Unknown implementation(s): %s\" % \", \".join(impls.unknown)) if count", "self._deserialized_from_string(fh.read()) def _deserialized_from_string(self, source): raise NotImplementedError() def _tokenize(self, source): if", "in self.combinations.items(): if name in names: values.add(value) def __repr__(self): return", "self.combinations.items(): if name in names: values.add(value) def __repr__(self): return \",\".join(str(i)", "zyaml.marshal import decode, default_marshal, represented_scalar from . import TestSettings class", "load_string(source) def _tokens_from_path(self, path): return tokens_from_path(path) def _tokens_from_string(self, source): return", "else \"implementations\" return click.option(name, \"-i\", callback=_callback, **kwargs) def show_result(self, data,", "PoyoImplementation, StrictImplementation] self.available = dict((m.name, m()) for m in av)", "% hlp) kwargs.setdefault(\"show_default\", True) kwargs.setdefault(\"metavar\", metavar) name = \"implementation\" if", "source): return TestSettings.protected_call(self._tokenize, source) def represented_token(self, token): return str(token) def", "implementation(s) to use count (int | None): Optional: exact number", "Args: default (str | None): Default implementation(s) to use count", "zyaml import load_path, load_string, tokens_from_path, tokens_from_string from zyaml.marshal import decode,", "none_key=\"-null-\") name = impl.name if self.combinations is None: self.combinations =", "class ZyamlImplementation(Implementation): name = \"zyaml\" def _deserialized_from_path(self, path): return load_path(path)", "for v in node.value: result.append(ruamel_passthrough_tags(loader, tag, v)) return result if", "= represented_scalar(token.style, value) elif token.id == \"<anchor>\": value = \"&%s\"", "data = \"\\n\".join(self.represented_token(t) for t in data) return data return", "data): if isinstance(data, Exception): value = runez.stringified(data) else: value =", "raise click.BadParameter(\"Need exactly 1 implementation\") raise click.BadParameter(\"Need exactly %s\" %", "NotImplementedError() def _tokenize(self, source): if hasattr(source, \"path\"): return self._tokens_from_path(source.path) return", "names: found = 0 for i in self.available.values(): if name", "self.unknown.append(name) self.combinations = None def track_result_combination(self, impl, data): if isinstance(data,", "ruamel_passthrough_tags, Loader=ruamel.yaml.SafeLoader) return y.load_all(source) def _tokens_from_string(self, source): return ruamel.yaml.main.scan(source) class", "\"&%s\" % value elif token.id == \"<alias>\": value = \"*%s\"", "exactly %s\" % runez.plural(count, \"implementation\")) if count == 1: return", "source): return [poyo.parse_string(source)] class StrictImplementation(Implementation): name = \"strict\" def _deserialized_from_string(self,", "None): Optional: exact number of implementations that have to specified", "\"poyo\" def _deserialized_from_string(self, source): return [poyo.parse_string(source)] class StrictImplementation(Implementation): name =", "\"\"\" kwargs[\"default\"] = default def _callback(_ctx, _param, value): if not", "not None: yield curr curr = yaml_loader.get_token() def represented_token(self, token):", "for s in runez.flattened(value)) elif token.id == \"<directive>\": result +=", "in self.selected: if i1.name < i2.name: self.combinations[(i1.name, i2.name)] = set()", "i in self.selected) def __len__(self): return len(self.selected) def __iter__(self): for", "**kwargs: Passed-through to click \"\"\" kwargs[\"default\"] = default def _callback(_ctx,", "value class ZyamlImplementation(Implementation): name = \"zyaml\" def _deserialized_from_path(self, path): return", "source): yaml_loader = pyyaml.BaseLoader(source) curr = yaml_loader.get_token() while curr is", "if hasattr(source, \"path\"): return self._tokens_from_path(source.path) return self._tokens_from_string(source) def _tokens_from_path(self, path):", "from . import TestSettings class ImplementationCollection(object): def __init__(self, names, default=\"zyaml,ruamel\"):", "return pyyaml.load_all(source, Loader=pyyaml.BaseLoader) def _tokens_from_string(self, source): yaml_loader = pyyaml.BaseLoader(source) curr", "kwargs.setdefault(\"metavar\", metavar) name = \"implementation\" if count == 1 else", "def _callback(_ctx, _param, value): if not value: return None impls", "= \"poyo\" def _deserialized_from_string(self, source): return [poyo.parse_string(source)] class StrictImplementation(Implementation): name", "1 column = token.start_mark.column + 1 result = \"%s[%s,%s]\" %", "\",\".join(\"I%s\" % (i + 1) for i in range(count)) kwargs.setdefault(\"help\",", "isinstance(data, NotImplementedError): print(\"%s - %s\" % (message, rep)) return print(message)", "seen: seen[i.name] = True self.selected.append(i) found += 1 if found", "i2.name)] = set() for names, values in self.combinations.items(): if name", "__repr__(self): return \",\".join(str(i) for i in self.selected) def __len__(self): return", "source): raise NotImplementedError() def _simplified(self, value): if isinstance(value, list) and", "linenum, column) value = getattr(token, \"value\", None) if value is", "return tokens_from_string(source) def _simplified(self, value): return value def ruamel_passthrough_tags(loader, tag,", "def _tokens_from_string(self, source): raise NotImplementedError() def _simplified(self, value): if isinstance(value,", "deserialized(self, source): value = TestSettings.protected_call(self._deserialized, source) return self._simplified(value) def tokens(self,", "% (i + 1) for i in range(count)) kwargs.setdefault(\"help\", \"%s", "_deserialized_from_path(self, path): with open(path) as fh: return self._deserialized_from_string(fh.read()) def _deserialized_from_string(self,", "def _deserialized(self, source): if hasattr(source, \"path\"): return self._deserialized_from_path(source.path) return self._deserialized_from_string(source)", "token.id == \"<directive>\": result += \" %s\" % token.name value" ]
[ "[] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or name", "to run make_whole() # krases0_BB.guess_bonds() # TODO: CS, turn off", "in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i])", "TODO: CS, for AA need bonds to run make_whole() #", "below, which can be used for the make_whole... # krases0_BB", "OROT[i] = -(OROT[i]) for i in range(len(OROT)): if OFORSIGN[i] <", "##### for i in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) # made", "= np.concatenate((OC, OS), axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:,", "take into account the periodic nature of the rotation ######", "four_states will shift that to index 4 ####### # four_states", "wrong with ref0 from get_kras_ref() # just making ref0 =", "structure is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe =", "= kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' '", "in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info protein_info = sorted(protein_info)", "so it is only done once ######### # kras_indices =", "= [] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or", "for x4 proteins; instead using protein_systems below to set num_res", "RAF = u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else: RAF = []", "RAS-RAF ########## RAS_only_num_res = 184 RAS_RAF_num_res = 320 ######### Above", "= [] ############### NEED TO CONFIRM THE SELECTION OF THE", "for i in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i, :])", "# --------------------------------------- # ALLOUT = [] # for k in", "TODO: TSC, zshifting is set to -1 (instead of -2),", "== 'RAS-RAF': z_pos = [] ############### NEED TO CONFIRM THE", "1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:, None] ORS_tp = np.concatenate((OC, OS),", "kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\", "in the script from logging import getLogger LOGGER = getLogger(__name__)", "that reads this information? i.e. will there be knock-on effects?", "kras_indices = get_protein_info(u,'resname ACE1 and name BB') ########## Above is", "four_states = np.zeros(len(OROT)) # for j in range(len(OROT)): # diff0", "class is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+'", "of all proteins in the systems.\\ Outputs a list of", "None] OACRS = np.cross(OA, ORS) OZCA = OA * OA[:,", "-45 or OROT[j] > 140) and z_pos[j] > 4.8: states[j]", "RotMatNP = np.array(RotMat) OS = np.array(OS) OA = RotMatNP[:, 2,", "that the tilt remains positive for i in range(len(OROT)): if", "= -(OROT[i]) for i in range(len(OROT)): if OFORSIGN[i] < 0.25:", "'+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name", "krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\", "krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or name BB)')", "account for upper vs. lower leaflet ##### for i in", "= [item[protein_x4] for item in protein_systems][0][1] except: LOGGER.error('Check KRas naming", "BB)') ############### NEED TO CONFIRM THE SELECTION OF THE RAF", "KRAS proteins in path.\"\"\" # res_shift = 8 # all_glycine", "remove this? Where is the code that reads this information?", "TODO: CS, not using these for x4 proteins; instead using", "from get_kras_ref() # just making ref0 = mobile0 to test", "protein_type == 'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in", "BEEN REDONE WITH A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN", "just making ref0 = mobile0 to test for now #", "Above introduces new shift to account for upper vs. lower", "# four_states[j] = diff0[0][1]+1 ###### below: old output details.... ######################################", "THE RAF LOOP RESIDUES ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if", "absolute value so that the tilt remains positive for i", "[] for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort()", "segs = u.segments segs = segs.segids ras_segids = [] rasraf_segids", "if k == len(kras_indices)-1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+'", "else: zshifting = 0 LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection =", "RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ####### #", "between modules') raise Exception('Error: unknown KRas name') # TODO: CS,", "into account the periodic nature of the rotation ###### if", "now # ref0 = mobile0 # TSC removed this R,", "ALLOUT = [] # for k in range(len(kras_indices)): # start_of_g", "140) and z_pos[j] > 4.8: states[j] = 3 else: ###", "# krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or name", "rotation ###### ###### Assume we want to remove this? Where", "might have to be updated to take into account the", "protein_type == 'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in", "diff0.sort() # four_states[j] = diff0[0][1]+1 ###### below: old output details....", "# 'RAS-ONLY' OR 'RAS-RAF' num_res = [item[protein_x4] for item in", "making ref0 = mobile0 to test for now # ref0", "[] # for i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) #", "states \"\"\" import MDAnalysis as mda from MDAnalysis.analysis import align", "and (name CA or name BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res))", "HAS TO BE FIXED FOR BACKBONE ATOMS FOR SPECIFIC PROTEIN", "taken out of the function so it is only done", "26): # kras_indices.append(all_glycine[i].index) ########## Below is taken out of the", "######## sort protein info return protein_info def get_ref_kras(): \"\"\"Gets the", "z_pos[j] > 4.8: states[j] = 3 else: ### above: adding", "str(kras_indices[k][1]) # ########## BELOW SECTION TO DETERMINE WHICH RESIDUES ARE", "ATOMS FOR SPECIFIC PROTEIN # # elif len(kras_indices) > 1:", "1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp = (OA - OZPACBCRS)**2 OFORSIGN =", "in range(len(OROT)): if OROT[i] < 0: OROT[i] = OROT[i]+180 elif", "get_segids to make a list of all proteins in the", "ORS_tp = np.concatenate((OC, OS), axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:,", "ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :],", "runs *** ''' # @Tim and <NAME>. this was commented", "codes the number of residues/beads in the RAS-ONLY and RAS-RAF", "syst.atoms[kras_start:kras_start+428] ####### This can be removed def get_segids(u): \"\"\"Identifies the", "information? i.e. will there be knock-on effects? ###### ###### If", "kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref frames (only need", "OROT[j] > 140) and z_pos[j] > 4.8: states[j] = 3", "OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF': z_pos = [] ###############", "nature of the rotation ###### ###### Assume we want to", "BB)' mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something", "timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT) #np.savetxt(str(tpr)+\"_tilt_rot_z_state.KRAS_\"+str(k+1)+\".txt\", OUTPUT,", "###### Updated - RAS-only to NOT HAVE the Z-distance ######################", "######################### # --------------------------------------- # TODO: TSC, I changed the selection", "len(kras_indices)-1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB')", "in range(len(OROT)): # OUTPUT[i] = timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i],", "RESIDUES BELOW #################### ############### TODO: TSC, zshifting is set to", "(name CA or name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions", "kras_indices = [] # for i in range(0, len(all_glycine), 26):", "0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP =", "= RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:,", "hard codes the number of residues within RAS-only and RAS-RAF", "these on import make them as an init mummi_core.init() dirKRASStates", "(name CA or name BB)') u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+'", "DPSM PAPS PAP6 CHOL') lipids = u.select_atoms('resname POPC PAPC POPE", "RESIDUES ARE PART OF THE PROTEIN GROUP - NEEDED FOR", "' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and (name CA or", "> 1: # # if k == len(kras_indices)-1: # #", "REMOVAL ############## # ########## POTENTIALLY REDO WITH A 'HARD-CODED' NUMBER", "> 0: RAF = u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else: RAF", "for a KRAS protein starting at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428]", "# --------------------------------------- # TODO: TSC, I changed the selection below,", "to be uncommented ############ import mummi_core import mummi_ras from mummi_core.utils", "path to the reference structure is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures,", "CS, for x4 cases: # [{protein_x4: (protein_type, num_res)}] protein_systems =", "= -(OROT[i]) ###### Below introduces new shift to account for", "modules') raise Exception('Error: unknown KRas name') # TODO: CS, replacing", "### above: adding in the requirements for the 'high-z' state", "Above hard codes the number of residues/beads in the RAS-ONLY", "for i in range(len(OROT)): # OUTPUT[i] = timeframes[i], OWAS[i], OROT[i],", "CS, for AA need bonds to run make_whole() # krases0_BB.guess_bonds()", "to currently be set as the 'RAS-ONLY-reference-structure.gro' # TODO: TSC,", "= OROT[i]-180 ###### Above introduces new shift to account for", "and (name CA or name BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+'", "thing in the script from logging import getLogger LOGGER =", "don't have these on import make them as an init", "number of residues within RAS-only and RAS-RAF ########## ####### This", "RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent number of columns", "details.... ###################################### ###### below: NEW output details.... ###################################### if protein_type", "or name BB)') timeframes = [] # TODO: CS, for", "the requirements for the 'high-z' state ### diff0 = []", "###### ###### If feedback code needs index 5 (two_states) from", "of the protein. i.e. 'resname ACE1 and name BB'.\\ Only", "Logger has to be initialized the first thing in the", "4 ####### # four_states = np.zeros(len(OROT)) # for j in", "TO BE FIXED FOR BACKBONE ATOMS FOR SPECIFIC PROTEIN #", "please check. #make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass())", "############### TODO: TSC, zshifting is set to -1 (instead of", "184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT = [] for k in", "range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) # made this an absolute value", "RAS-RAF) ####### # ########## HAS BEEN REDONE WITH A 'HARD-CODED'", "it is 'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag' input defines what", "the systems.\\ Outputs a list of the first residue number", "'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)): OUTPUT[i]", "# for k in range(len(kras_indices)): # start_of_g = kras_indices[k][0] #", "ACE1 and name BB'.\\ Only needs to be called x1", "Z_unit = Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:,", "to set num_res ######### Below hard codes the number of", "######## # # if len(kras_indices) == 1: # # krases0_BB", "Only called x1 time when class is loaded\"\"\" start_of_g_ref =", "range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :],", "if it has not been done before # MUMMI_ROOT =", "= (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS =", "in range(len(segs)): # print(segs[i]) if segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if", "0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:,", "import numpy as np import math ############## Below section needs", "# \"\"\"Gets all atoms for a KRAS protein starting at", "# return syst.atoms[kras_start:kras_start+428] ####### This can be removed def get_segids(u):", "fix this so we don't have these on import make", "BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load", "0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp = (OA - OZPACBCRS)**2 OFORSIGN", "= np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp = np.concatenate((OA, OS), axis=1) t", "#RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate", "protein_x4 type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' '", "the Naming works below #@TODO fix this so we don't", "do this once) ref0 = get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states", "[] # for i in range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index)", "now to test beyond this point ''' *** for AA,", "if protein_type == 'RAS-ONLY': # num_res = RAS_only_num_res # elif", "lower leaflet ##### for i in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180)", "RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1] ###### Above might have to", "if protein_type == 'RAS-RAF': z_pos = [] ############### NEED TO", "WITH A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN GROUP (WHETHER", "= Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:,", "0: OROT[i] = OROT[i]-180 ###### Above introduces new shift to", "[] for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort()", "test for now # ref0 = mobile0 # TSC removed", "= OROTNOTSIGNED for i in range(len(OROT)): if OROT[i] < 0:", "zshifting = 0 else: zshifting = 0 LOGGER.error('Found unsupported protein_x4", "shift to account for upper vs. lower leaflet ##### for", "#diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1] ###### Above", "RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above section needs to be uncommented", "0: OROT[i] = -(OROT[i]) for i in range(len(OROT)): if OFORSIGN[i]", "Load inital ref frames (only need to do this once)", "u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something wrong with ref0 from get_kras_ref()", "@Tim and <NAME>. this was commented out - please check.", "RAS_RAF_num_res # ########## Above hard codes the number of residues/beads", "of the first residue number of the protein, and whether", "None] OFORSIGN_temp = (OA - OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:,", "###### above: old output details.... ###################################### ###### below: NEW output", "= OA*t[:, None] ORS_tp = np.concatenate((OC, OS), axis=1) ORS_norm =", "BACKBONE ATOMS FOR SPECIFIC PROTEIN # # elif len(kras_indices) >", "(name CA or name BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and", "= mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not using these for x4", "import os import numpy as np import math ############## Below", "residues in AA #zshifting=-1 if protein_x4 == 'rasraf': zshifting =", "unknown KRas name') # TODO: CS, replacing this comment section", "list of all proteins in the systems.\\ Outputs a list", "OWAS[i], OROT[i], 'n/a', int(states[i]) elif protein_type == 'RAS-RAF': OUTPUT =", "below to set num_res ######### Below hard codes the number", "(WHETHER RAS-ONLY OR RAS-RAF) ####### # ########## HAS BEEN REDONE", "range(len(OROT)): ### below: adding in the requirements for the 'high-z'", "2, 2])*180/math.pi OC_temp = np.concatenate((OA, OS), axis=1) t = ((OC_temp[:,", "kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref frames", "krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' '", "4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC =", "'tag' input defines what is used to identify the first", "+\\ 'and (name CA or name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection))", "mummi_core.utils import Naming # # Logger has to be initialized", "i in range(len(OROT)): # OUTPUT[i] = timeframes[i], OWAS[i], OROT[i], z_pos[i],", "x4 protein types # --------------------------------------- # ALLOUT = [] #", "# TODO: CS, for AA need bonds to run make_whole()", "DIPE DPSM PAPS PAP6 CHOL') lipids = u.select_atoms('resname POPC PAPC", "mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro')", "this once) ref0 = get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states for", "# ########## BELOW SECTION TO DETERMINE WHICH RESIDUES ARE PART", "OWAS[i] = abs(-(OWAS[i])+180) # made this an absolute value so", "RAS-ONLY OR RAS-RAF) ######## # # if len(kras_indices) == 1:", "' +\\ ' and (name CA or name BB)') ###############", "protein_info = sorted(protein_info) ######## sort protein info return protein_info def", "start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+'", "ref0 RotMat = [] OS = [] r152_165 = krases0_BB.select_atoms('resid", "OROTNOTSIGNED = np.zeros([len(ORS)]) for i in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i,", "i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] =", "cases: # [{protein_x4: (protein_type, num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY', 185),", "is the code that reads this information? i.e. will there", "this? Where is the code that reads this information? i.e.", "four_states[i], two_states[i] ###### above: old output details.... ###################################### ###### below:", "- RAS-only to NOT HAVE the Z-distance ###################### ###### Updated", "FOR PBC REMOVAL ############## # ########## POTENTIALLY REDO WITH A", "'n/a', int(states[i]) elif protein_type == 'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object)", "RAS-ONLY or RAS-RAF ##### # OUTPUT = np.zeros([len(OROT), 6]) #", "'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or", "protein info protein_info = sorted(protein_info) ######## sort protein info return", "all else runs *** ''' # @Tim and <NAME>. this", "np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp = np.concatenate((OA, OS), axis=1) t =", "CA or name BB)') timeframes = [] # TODO: CS,", "and (name CA or name BB)') timeframes = [] #", "account the periodic nature of the rotation ###### if protein_type", "there be knock-on effects? ###### ###### If feedback code needs", "the above, to handle x4 protein types # --------------------------------------- #", "*** for AA, need to bring that back on once", "residue of the protein. i.e. 'resname ACE1 and name BB'.\\", "bonds to run make_whole() # krases0_BB.guess_bonds() # TODO: CS, turn", "getKRASstates(u,kras_indices): \"\"\"Gets states for all KRAS proteins in path.\"\"\" #", "the function so it is only done once ######### #", "== 'ras4araf': zshifting = 0 else: zshifting = 0 LOGGER.error('Found", "edits to test # TODO: TSC, The reference structure has", "item in protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF' num_res = [item[protein_x4]", "name BB)') timeframes = [] # TODO: CS, for AA", "########## Above is taken out of the function so it", "range(len(OROT)): # OUTPUT[i] = timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i]", "= str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i]) elif protein_type ==", "mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") #", "\"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') #", "LOGGER.error('Check KRas naming between modules') raise Exception('Error: unknown KRas name')", ":], ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:,", "of the protein, and whether it is 'RAS-ONLY', or 'RAS-RAF'.\\", "get_protein_info(u,'resname ACE1 and name BB') ########## Above is taken out", "we want to remove this? Where is the code that", "(OROT[j] < -45 or OROT[j] > 140) and z_pos[j] >", "state ### diff0 = [] for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5,", "# OUTPUT[i] = timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i] ######", "them as an init mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures =", "= []#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in", "x4 proteins; instead using protein_systems below to set num_res #########", "periodic nature of the rotation ###### if protein_type == 'RAS-ONLY':", "from MDAnalysis.lib.mdamath import make_whole import os import numpy as np", "('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT =", "# for i in range(len(OROT)): # OUTPUT[i] = timeframes[i], OWAS[i],", "# ALLOUT = [] # for k in range(len(kras_indices)): #", "np import math ############## Below section needs to be uncommented", "the rotation ###### ###### Assume we want to remove this?", "2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp = np.concatenate((OA,", "which can be used for the make_whole... # krases0_BB =", "the system. Only needs to be called x1 time\"\"\" segs", "GROUP - NEEDED FOR PBC REMOVAL ############## # ########## POTENTIALLY", "used to identify the first residue of the protein. i.e.", "was commented out - please check. #make_whole(krases0_BB) j, rmsd_junk =", "np.array(z_pos) RotMatNP = np.array(RotMat) OS = np.array(OS) OA = RotMatNP[:,", "removed this R, RMSD_junk = align.rotation_matrix(mobile0, ref0) ######## TODO: TSC,", "range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info protein_info = sorted(protein_info) ########", "be initialized the first thing in the script from logging", "segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return", "# elif len(kras_indices) > 1: # # if k ==", "below: old output details.... ###################################### ###### Updated - RAS-only to", "in range(len(OROT)): ### below: adding in the requirements for the", "all proteins in the systems.\\ Outputs a list of the", "are separate residues in AA #zshifting=-1 if protein_x4 == 'rasraf':", "as an init mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures')", "to account for upper vs. lower leaflet ##### for i", "# four_states = np.zeros(len(OROT)) # for j in range(len(OROT)): #", "elif protein_x4 == 'ras4araf': zshifting = 0 else: zshifting =", "SECTION TO DETERMINE WHICH RESIDUES ARE PART OF THE PROTEIN", "OA = RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2,", "print(segs[i]) if segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF':", "TSC, path to the reference structure is: mummi_resources/structures/ kras_ref_universe =", "############### NEED TO CONFIRM THE SELECTION OF THE RAF LOOP", "replacing this comment section with the above, to handle x4", "has not been done before # MUMMI_ROOT = mummi.init(True) #", "range(len(OROT)): if OROT[i] < 0: OROT[i] = OROT[i]+180 elif OROT[i]", "OROTNOTSIGNED for i in range(len(OROT)): if OROT[i] < 0: OROT[i]", "from mummi_core.utils import Naming # # Logger has to be", "be uncommented ############ import mummi_core import mummi_ras from mummi_core.utils import", "need bonds to run make_whole() # krases0_BB.guess_bonds() # TODO: CS,", "in range(len(OROT)): # diff0 = [] # for i in", "x1 time\"\"\" segs = u.segments segs = segs.segids ras_segids =", "###### below: old output details.... ###################################### ###### Updated - RAS-only", "'+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and (name CA", "out - please check. #make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords)", "\"\"\" Get's KRAS states \"\"\" import MDAnalysis as mda from", "is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\")", "RAF LOOP RESIDUES ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff", "DIPE SSM PAPS SAPI CHL1') coords = ref0 RotMat =", "np.array(OS) OA = RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:,", "num_res ######### Below hard codes the number of residues within", "name BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or", "\\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA", "num_res = [item[protein_x4] for item in protein_systems][0][1] except: LOGGER.error('Check KRas", "[] for i in range(len(segs)): # print(segs[i]) if segs[i][-3:] ==", "Pilot2-splash-app disclaimer ############################################################################### \"\"\" Get's KRAS states \"\"\" import MDAnalysis", "('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF',", "np.cross(OA, ORS) OZCA = OA * OA[:, 2][:, None] Z_unit", "j in range(len(OROT)): diff0 = [] for i in range(len(RAS_ONLY_macrostate)):", "the Z-distance ###################### ###### Updated - Added in the protein", "2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)]) for i in range(len(ORS)): OROTNOTSIGNED[i]", "for upper vs. lower leaflet ##### for i in range(len(OWAS)):", "rotation ###### if protein_type == 'RAS-ONLY': states = np.zeros(len(OROT)) for", "when class is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection = 'resid", "= diff0[0][1] elif protein_type == 'RAS-RAF': states = np.zeros(len(OROT)) for", "= u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ '", "so index change below # TODO: CS, my edits to", "if OROT[i] < 0: OROT[i] = OROT[i]+180 elif OROT[i] >", "that are separate residues in AA #zshifting=-1 if protein_x4 ==", "Below hard codes the number of residues/beads in the RAS-ONLY", "'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the segments", "protein_type == 'RAS-ONLY': # num_res = RAS_only_num_res # elif protein_type", "coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF': z_pos =", "BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or name", "1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp", "diff0[0][1] elif protein_type == 'RAS-RAF': states = np.zeros(len(OROT)) for j", "point ''' *** for AA, need to bring that back", "u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') # # else: # #", "is only done once ######### # kras_indices = get_protein_info(u,'resname ACE1", "RAS_only_num_res = 184 RAS_RAF_num_res = 320 ######### Above hard codes", "' and (name CA or name BB)') ############### NEED TO", "used for the make_whole... # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and", "states = np.zeros(len(OROT)) for j in range(len(OROT)): ### below: adding", "np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i],", "below #@TODO fix this so we don't have these on", "for the 'high-z' state ### diff0 = [] for i", "function so it is only done once ######### # kras_indices", "called x1 time\"\"\" segs = u.segments segs = segs.segids ras_segids", "the requirements for the 'high-z' state ### if (OROT[j] <", "Get's KRAS states \"\"\" import MDAnalysis as mda from MDAnalysis.analysis", "= np.full([len(OZCA), 3], 1) Z_adjust = np.array([0, 0, 1]) Z_unit", "= kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try: protein_type = [item[protein_x4] for", "to make a list of all proteins in the systems.\\", "\"\"\" import MDAnalysis as mda from MDAnalysis.analysis import align from", "for i in range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ########## Below", "of -2), as there are ACE caps that are separate", "ORS) OZCA = OA * OA[:, 2][:, None] Z_unit =", "j in range(len(OROT)): # diff0 = [] # for i", "protein. i.e. 'resname ACE1 and name BB'.\\ Only needs to", "with ref0 from get_kras_ref() # just making ref0 = mobile0", "Z-distance ###################### ###### Updated - Added in the protein 'tag',", "######### Below hard codes the number of residues within RAS-only", "OF RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ########", "= u.select_atoms('resname POPX POPC PAPC POPE DIPE DPSM PAPS PAP6", "GROUP (WHETHER RAS-ONLY OR RAS-RAF) ######## # # if len(kras_indices)", "import make_whole import os import numpy as np import math", "states for all KRAS proteins in path.\"\"\" # res_shift =", "2] OROT = OROTNOTSIGNED for i in range(len(OROT)): if OROT[i]", "OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)): OUTPUT[i] =", "protein_type = [item[protein_x4] for item in protein_systems][0][0] # 'RAS-ONLY' OR", "3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS -", "on once all else runs *** ''' # @Tim and", "CS, not using these for x4 proteins; instead using protein_systems", "ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the segments identified in get_segids", "- kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref frames (only need to", "TODO: CS, replacing this comment section with the above, to", "u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and", "the first residue of the protein. i.e. 'resname ACE1 and", "is 'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag' input defines what is", "protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info", "to identify the first residue of the protein. i.e. 'resname", "align from MDAnalysis.lib.mdamath import make_whole import os import numpy as", "SAPI CHL1') coords = ref0 RotMat = [] OS =", "the reference KRAS struct. Only called x1 time when class", "########## BELOW SECTION TO DETERMINE WHICH RESIDUES ARE PART OF", "KRas name') # TODO: CS, replacing this comment section with", "1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC", "* OA[:, 2][:, None] Z_unit = np.full([len(OZCA), 3], 1) Z_adjust", "BELOW #################### ############### TODO: TSC, zshifting is set to -1", "'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\", "AA #zshifting=-1 if protein_x4 == 'rasraf': zshifting = -1 elif", "OROT[i] = -(OROT[i]) ###### Below introduces new shift to account", "RAS = [] if len(rasraf_segids) > 0: RAF = u.select_atoms('segid", "184 RAS_RAF_num_res = 320 ######### Above hard codes the number", "for i in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) # made this", "residues within RAS-only and RAS-RAF ########## RAS_only_num_res = 184 RAS_RAF_num_res", "of residues within RAS-only and RAS-RAF ########## RAS_only_num_res = 184", "LOOP RESIDUES BELOW #################### ############### TODO: TSC, zshifting is set", "range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try: protein_type =", "residues/beads in the RAS-ONLY and RAS-RAF simulations ######################### # ---------------------------------------", "to be updated to take into account the periodic nature", "to test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt')", "# kras_indices.append(all_glycine[i].index) ########## Below is taken out of the function", "diffrent number of columns so index change below # TODO:", "for AA need bonds to run make_whole() # krases0_BB.guess_bonds() #", "old output details.... ###################################### ###### Updated - RAS-only to NOT", "above section needs to be uncommented ############ # TODO: CS,", "logging import getLogger LOGGER = getLogger(__name__) # # Innitilize MuMMI", "= [] for k in range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4", "to test beyond this point ''' *** for AA, need", "3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2))", "is only done once ######### # CS, for x4 cases:", "make_whole() # krases0_BB.guess_bonds() # TODO: CS, turn off for now", "= mummi.init(True) # This is needed so the Naming works", "########## ####### This can be removed # def get_kras(syst, kras_start):", "once ######### # kras_indices = get_protein_info(u,'resname ACE1 and name BB')", "'RAS-RAF': # num_res = RAS_RAF_num_res # ########## Above hard codes", "= [] # TODO: CS, for AA need bonds to", "segments within the system. Only needs to be called x1", "the protein 'tag', i.e. RAS-ONLY or RAS-RAF ##### # OUTPUT", "5 (two_states) from the output, deleting this four_states will shift", "# res_shift = 8 # all_glycine = u.select_atoms(\"resname GLY\") #", "ref frames (only need to do this once) ref0 =", "Exception('Error: unknown KRas name') # TODO: CS, replacing this comment", "= diff0[0][1]+1 ###### below: old output details.... ###################################### ###### Updated", "RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ######## #", "in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i,", "as np import math ############## Below section needs to be", "= [] OS = [] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and", "sorted(protein_info) ######## sort protein info return protein_info def get_ref_kras(): \"\"\"Gets", "\"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#')", "CA or name BB)' mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() #", "has to be initialized the first thing in the script", "RAS-ONLY and RAS-RAF simulations ######################### # if protein_type == 'RAS-ONLY':", "uncommented ############ # TODO: CS, my edits to test #", "((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:,", "5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS - OC)/ORS_norm[:, None] OACRS =", "shift to account for upper vs. lower leaflet ##### ######", "'rasraf': ('RAS-RAF', 320)}] ALLOUT = [] for k in range(len(kras_indices)):", "or OROT[j] > 140) and z_pos[j] > 4.8: states[j] =", "np.zeros(len(OROT)) for j in range(len(OROT)): ### below: adding in the", "= np.loadtxt('ras-raf-states.txt') ############## above section needs to be uncommented ############", "= np.zeros([len(ORS)]) for i in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :],", "to index 4 ####### # four_states = np.zeros(len(OROT)) # for", "--------------------------------------- # ALLOUT = [] # for k in range(len(kras_indices)):", "diff < 0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos)", "z_pos[i], four_states[i], two_states[i] ###### above: old output details.... ###################################### ######", "0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS - OC)/ORS_norm[:,", "x1 time\"\"\" ras_segids, rasraf_segids = get_segids(u) if len(ras_segids) > 0:", "section needs to be uncommented ############ # TODO: CS, my", "= np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None]", "Added in the protein 'tag', i.e. RAS-ONLY or RAS-RAF #####", "for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j]", "= np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above section needs", "# for i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort()", "name BB') ####### HAS TO BE FIXED FOR BACKBONE ATOMS", "from the output, deleting this four_states will shift that to", "OROT[i]-180 ###### Above introduces new shift to account for upper", "to test for now # ref0 = mobile0 # TSC", "= (OA - OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2]", "== 'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the", "TODO: CS, my edits to test # TODO: TSC, The", "[{protein_x4: (protein_type, num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF',", "Z_unit = np.full([len(OZCA), 3], 1) Z_adjust = np.array([0, 0, 1])", "in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1]", "states[j] = diff0[0][1] elif protein_type == 'RAS-RAF': states = np.zeros(len(OROT))", "= 3 else: ### above: adding in the requirements for", "if protein_x4 == 'rasraf': zshifting = -1 elif protein_x4 ==", "= np.array(OS) OA = RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2,", "protein_systems][0][1] except: LOGGER.error('Check KRas naming between modules') raise Exception('Error: unknown", "for k in range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4 = str(kras_indices[k][1])", "codes the number of residues within RAS-only and RAS-RAF ##########", "'+str(start_of_g)+':'+str(len(u.residues))+' and name BB') ####### HAS TO BE FIXED FOR", "= str(kras_indices[k][1]) # ########## BELOW SECTION TO DETERMINE WHICH RESIDUES", "Below introduces new shift to account for upper vs. lower", "if protein_type == 'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i", "str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and (name CA or name BB)')", "# # else: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and", "= u.select_atoms('resname POPC PAPC POPE DIPE SSM PAPS SAPI CHL1')", "OF THE RAF LOOP RESIDUES ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10", "np.full([len(OZCA), 3], 1) Z_adjust = np.array([0, 0, 1]) Z_unit =", "to be initialized the first thing in the script from", "and name BB') # ########## ABOVE SECTION TO DETERMINE WHICH", "# lipids = u.select_atoms('resname POPX POPC PAPC POPE DIPE DPSM", "at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] ####### This can be removed", "updated to take into account the periodic nature of the", "of the rotation ###### ###### Assume we want to remove", "GROUP (WHETHER RAS-ONLY OR RAS-RAF) ####### # ########## HAS BEEN", "of segments within the system. Only needs to be called", "= u.select_atoms(\"resname GLY\") # kras_indices = [] # for i", "TODO: CS, turn off for now to test beyond this", "make a list of all proteins in the systems.\\ Outputs", "vs. lower leaflet ##### ###### Below might have to be", "caps that are separate residues in AA #zshifting=-1 if protein_x4", "# just making ref0 = mobile0 to test for now", "i in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a',", "there are ACE caps that are separate residues in AA", "PART OF THE PROTEIN GROUP - NEEDED FOR PBC REMOVAL", "in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) # made this an absolute", "if OROT[i] < 0: OROT[i] = -(OROT[i]) for i in", "try: protein_type = [item[protein_x4] for item in protein_systems][0][0] # 'RAS-ONLY'", "diff0[0][1]+1 ###### below: old output details.... ###################################### ###### Updated -", "320)}] ALLOUT = [] for k in range(len(kras_indices)): start_of_g =", "for i in range(len(OROT)): if OFORSIGN[i] < 0.25: OROT[i] =", "test # TODO: TSC, The reference structure has to currently", "' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name CA or name", "1: # # if k == len(kras_indices)-1: # # krases0_BB", "effects? ###### ###### If feedback code needs index 5 (two_states)", "called x1 time\"\"\" ras_segids, rasraf_segids = get_segids(u) if len(ras_segids) >", "the 'RAS-ONLY-reference-structure.gro' # TODO: TSC, path to the reference structure", "to test # TODO: TSC, The reference structure has to", "OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT) #np.savetxt(str(tpr)+\"_tilt_rot_z_state.KRAS_\"+str(k+1)+\".txt\", OUTPUT, fmt=['%i','%10.3f','%10.3f','%10.3f','%i','%i'], delimiter='", "return protein_info def get_ref_kras(): \"\"\"Gets the reference KRAS struct. Only", "FOR PBC REMOVAL ############## # # ########## Below hard codes", "first residue of the protein. i.e. 'resname ACE1 and name", "# Load inital ref frames (only need to do this", "columns so index change below # TODO: CS, my edits", "OFORSIGN_temp = (OA - OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:,", "something wrong with ref0 from get_kras_ref() # just making ref0", "RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None]", "diff0 = [] # for i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5,", "the list of segments within the system. Only needs to", "'+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and", "kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref frames (only need to do", "for AA lipid names ######## # lipids = u.select_atoms('resname POPX", "############################################################################### \"\"\" Get's KRAS states \"\"\" import MDAnalysis as mda", "= timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i] ###### above: old", "for x4 cases: # [{protein_x4: (protein_type, num_res)}] protein_systems = [{'ras4a':", "* (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS", "ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+'", "= RAS_RAF_num_res # ########## Above hard codes the number of", "LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\", "############ # TODO: CS, my edits to test # TODO:", "for upper vs. lower leaflet ##### ###### Below might have", "POPE DIPE SSM PAPS SAPI CHL1') coords = ref0 RotMat", "res_shift = 8 # all_glycine = u.select_atoms(\"resname GLY\") # kras_indices", "== 'RAS-ONLY': states = np.zeros(len(OROT)) for j in range(len(OROT)): diff0", "= 320 ######### Above hard codes the number of residues", "selection below, which can be used for the make_whole... #", "range(len(OROT)): if OFORSIGN[i] < 0.25: OROT[i] = -(OROT[i]) ###### Below", "'+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' '", "# #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') #", "6]).astype(object) for i in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i],", "PAP6 CHOL') lipids = u.select_atoms('resname POPC PAPC POPE DIPE SSM", "or name BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 =", "ACE caps that are separate residues in AA #zshifting=-1 if", "be removed # def get_kras(syst, kras_start): # \"\"\"Gets all atoms", "in AA #zshifting=-1 if protein_x4 == 'rasraf': zshifting = -1", "'and (name CA or name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return", "rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the segments identified in get_segids to", "info protein_info = sorted(protein_info) ######## sort protein info return protein_info", "####### HAS TO BE FIXED FOR BACKBONE ATOMS FOR SPECIFIC", "# protein_type = str(kras_indices[k][1]) # ########## BELOW SECTION TO DETERMINE", "CS, something wrong with ref0 from get_kras_ref() # just making", "= abs(-(OWAS[i])+180) # made this an absolute value so that", "'+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or name BB)') timeframes = []", "OROT[i] = OROT[i]+180 elif OROT[i] > 0: OROT[i] = OROT[i]-180", "leaflet ##### for i in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) #", "num_res = RAS_only_num_res # elif protein_type == 'RAS-RAF': # num_res", "[] OS = [] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name", "TO DETERMINE WHICH RESIDUES ARE PART OF THE PROTEIN GROUP", "= np.array(z_pos) RotMatNP = np.array(RotMat) OS = np.array(OS) OA =", "OROT[i]+180 elif OROT[i] > 0: OROT[i] = OROT[i]-180 ###### Above", "done before # MUMMI_ROOT = mummi.init(True) # This is needed", "or name BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA", "# ref0 = mobile0 # TSC removed this R, RMSD_junk", "mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not using these for x4 proteins;", "below: adding in the requirements for the 'high-z' state ###", "BELOW SECTION TO DETERMINE WHICH RESIDUES ARE PART OF THE", "'RAS-RAF' num_res = [item[protein_x4] for item in protein_systems][0][1] except: LOGGER.error('Check", "\"\"\"Gets states for all KRAS proteins in path.\"\"\" # res_shift", "-2), as there are ACE caps that are separate residues", "'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)): OUTPUT[i]", "1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED for i in range(len(OROT)): if", "a KRAS protein starting at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] #######", "- please check. #make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j)", "BB') ########## Above is taken out of the function so", "the rotation ###### if protein_type == 'RAS-ONLY': states = np.zeros(len(OROT))", "import MDAnalysis as mda from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath", "u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') # ########## ABOVE SECTION TO", "range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1] ######", "i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info protein_info =", "'RAS-ONLY' OR 'RAS-RAF' num_res = [item[protein_x4] for item in protein_systems][0][1]", "Updated - RAS-only to NOT HAVE the Z-distance ###################### ######", "diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP = np.array(RotMat)", "OROT[i], z_pos[i], four_states[i], two_states[i] ###### above: old output details.... ######################################", "PROTEIN GROUP - NEEDED FOR PBC REMOVAL ############## # ##########", "This is needed so the Naming works below #@TODO fix", "BE FIXED FOR BACKBONE ATOMS FOR SPECIFIC PROTEIN # #", "OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED for", "get_segids(u) if len(ras_segids) > 0: RAS = u.select_atoms('segid '+ras_segids[0]+' and", "z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT) #np.savetxt(str(tpr)+\"_tilt_rot_z_state.KRAS_\"+str(k+1)+\".txt\", OUTPUT, fmt=['%i','%10.3f','%10.3f','%10.3f','%i','%i'], delimiter=' ')", "# RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above section needs to be", "range(len(OROT)): # diff0 = [] # for i in range(len(macrostate4)):", "= str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT)", "if len(ras_segids) > 0: RAS = u.select_atoms('segid '+ras_segids[0]+' and '+str(tag))", "import mummi_ras from mummi_core.utils import Naming # # Logger has", "[] # for k in range(len(kras_indices)): # start_of_g = kras_indices[k][0]", "AA, need to bring that back on once all else", "only done once ######### # CS, for x4 cases: #", "protein_x4 = str(kras_indices[k][1]) try: protein_type = [item[protein_x4] for item in", "i in range(len(OROT)): if OROT[i] < 0: OROT[i] = -(OROT[i])", "= np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent number of columns so", "NOT HAVE the Z-distance ###################### ###### Updated - Added in", "####### This can be removed # def get_kras(syst, kras_start): #", "once all else runs *** ''' # @Tim and <NAME>.", "for i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() #", "# for i in range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ##########", "= u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') ####### HAS TO BE", "# CS, for x4 cases: # [{protein_x4: (protein_type, num_res)}] protein_systems", "zshifting = -1 elif protein_x4 == 'ras4araf': zshifting = 0", "R, RMSD_junk = align.rotation_matrix(mobile0, ref0) ######## TODO: TSC, Adjusted for", "###### if protein_type == 'RAS-ONLY': states = np.zeros(len(OROT)) for j", "comment section with the above, to handle x4 protein types", "r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\", "kras_indices[k][0] # protein_type = str(kras_indices[k][1]) # ########## BELOW SECTION TO", "- Added in the protein 'tag', i.e. RAS-ONLY or RAS-RAF", "RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF': z_pos = []", "an absolute value so that the tilt remains positive for", "############## Below section needs to be uncommented ############ import mummi_core", "diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() # four_states[j] = diff0[0][1]+1 ###### below:", "'high-z' state ### if (OROT[j] < -45 or OROT[j] >", "6]) # for i in range(len(OROT)): # OUTPUT[i] = timeframes[i],", "whether it is 'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag' input defines", "CONFIRM THE SELECTION OF THE RAF LOOP RESIDUES ABOVE ####################", "details.... ###################################### if protein_type == 'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object)", "0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)]) for i in", "###### Below introduces new shift to account for upper vs.", "proteins in the systems.\\ Outputs a list of the first", "# kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not using these", "in range(len(OROT)): if OROT[i] < 0: OROT[i] = -(OROT[i]) for", "u.select_atoms('resname POPX POPC PAPC POPE DIPE DPSM PAPS PAP6 CHOL')", "this so we don't have these on import make them", "t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:,", "script from logging import getLogger LOGGER = getLogger(__name__) # #", "loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\", "to remove this? Where is the code that reads this", "# ########## Above hard codes the number of residues/beads in", "mobile0 to test for now # ref0 = mobile0 #", "protein_x4 == 'ras4araf': zshifting = 0 else: zshifting = 0", "within RAS-only and RAS-RAF ########## ####### This can be removed", "len(kras_indices) > 1: # # if k == len(kras_indices)-1: #", "done once ######### # CS, for x4 cases: # [{protein_x4:", "#zshifting=-1 if protein_x4 == 'rasraf': zshifting = -1 elif protein_x4", "KRAS protein starting at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] ####### This", "the reference structure is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) #", "Above is taken out of the function so it is", "0: OROT[i] = OROT[i]+180 elif OROT[i] > 0: OROT[i] =", "i in range(len(segs)): # print(segs[i]) if segs[i][-3:] == 'RAS': ras_segids.append(segs[i])", "to be uncommented ############ # TODO: CS, my edits to", "== 'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)):", "as mda from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath import make_whole", "= OA * OA[:, 2][:, None] Z_unit = np.full([len(OZCA), 3],", "range(len(OROT)): diff0 = [] for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]])", "MUMMI_ROOT = mummi.init(True) # This is needed so the Naming", "CA or name BB)') r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name", "np.array(RotMat) OS = np.array(OS) OA = RotMatNP[:, 2, :]/(((RotMatNP[:, 2,", "OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED for i in", "states = np.zeros(len(OROT)) for j in range(len(OROT)): diff0 = []", "### below: adding in the requirements for the 'high-z' state", "# kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO:", "commented out - please check. #make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()),", "OR 'RAS-RAF' num_res = [item[protein_x4] for item in protein_systems][0][1] except:", "starting at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] ####### This can be", "# if k == len(kras_indices)-1: # # krases0_BB = u.select_atoms('resid", "can be removed # def get_kras(syst, kras_start): # \"\"\"Gets all", "index change below # TODO: CS, my edits to test", "TO CONFIRM THE SELECTION OF THE RAF LOOP RESIDUES BELOW", "= diff0[0][1] ###### Above might have to be updated to", "within RAS-only and RAS-RAF ########## RAS_only_num_res = 184 RAS_RAF_num_res =", "= align.rotation_matrix(mobile0, ref0) ######## TODO: TSC, Adjusted for AA lipid", "# # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') #", "np.loadtxt('ras-raf-states.txt') ############## above section needs to be uncommented ############ #", "state ### if (OROT[j] < -45 or OROT[j] > 140)", "######## TODO: TSC, Adjusted for AA lipid names ######## #", "in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() # four_states[j] =", "name BB)' mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS,", "timeframes = [] # TODO: CS, for AA need bonds", "OA[:, 2][:, None] Z_unit = np.full([len(OZCA), 3], 1) Z_adjust =", "BB)') u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+'", "want to remove this? Where is the code that reads", "-1 (instead of -2), as there are ACE caps that", "to account for upper vs. lower leaflet ##### ###### Below", "OUTPUT[i] = timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i] ###### above:", "in the requirements for the 'high-z' state ### if (OROT[j]", "+\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and (name CA or name", "2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:,", "for now to test beyond this point ''' *** for", "diff0 = [] for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5,", "# ########## HAS BEEN REDONE WITH A 'HARD-CODED' NUMBER OF", "the code that reads this information? i.e. will there be", "this R, RMSD_junk = align.rotation_matrix(mobile0, ref0) ######## TODO: TSC, Adjusted", "MDAnalysis.analysis import align from MDAnalysis.lib.mdamath import make_whole import os import", "+ (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:,", "and z_pos[j] > 4.8: states[j] = 3 else: ### above:", "of columns so index change below # TODO: CS, my", "len(kras_indices) == 1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and", "identified in get_segids to make a list of all proteins", "reference structure is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe", "TSC, The reference structure has to currently be set as", "ARE PART OF THE PROTEIN GROUP - NEEDED FOR PBC", "protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF' num_res = [item[protein_x4] for item", "def get_protein_info(u,tag): \"\"\"Uses the segments identified in get_segids to make", "get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states for all KRAS proteins in", "set to -1 (instead of -2), as there are ACE", "inital ref frames (only need to do this once) ref0", "residues within RAS-only and RAS-RAF ########## ####### This can be", "output details.... ###################################### ###### below: NEW output details.... ###################################### if", "########## ABOVE SECTION TO DETERMINE WHICH RESIDUES ARE PART OF", "# MUMMI_ROOT = mummi.init(True) # This is needed so the", "reads this information? i.e. will there be knock-on effects? ######", "mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something wrong", "[] if len(rasraf_segids) > 0: RAF = u.select_atoms('segid '+rasraf_segids[0]+' and", "\"\"\"Gets the reference KRAS struct. Only called x1 time when", "len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ########## Below is taken out of", "OROT[i] = OROT[i]-180 ###### Above introduces new shift to account", "= [] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY'))", "AA need bonds to run make_whole() # krases0_BB.guess_bonds() # TODO:", "lipid names ######## # lipids = u.select_atoms('resname POPX POPC PAPC", "range(len(segs)): # print(segs[i]) if segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if segs[i][-3:]", "= u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') # # else: #", "(only need to do this once) ref0 = get_ref_kras() def", "can be removed def get_segids(u): \"\"\"Identifies the list of segments", "[] for k in range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4 =", "to bring that back on once all else runs ***", "(np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS =", "= 8 # all_glycine = u.select_atoms(\"resname GLY\") # kras_indices =", "'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] ####### This can be removed def", "= np.array([0, 0, 1]) Z_unit = Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA", "CS, replacing this comment section with the above, to handle", "None] Z_unit = np.full([len(OZCA), 3], 1) Z_adjust = np.array([0, 0,", ":]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS)", "time when class is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection =", "j in range(len(OROT)): ### below: adding in the requirements for", "above: adding in the requirements for the 'high-z' state ###", "range(len(kras_indices)): # start_of_g = kras_indices[k][0] # protein_type = str(kras_indices[k][1]) #", "str(kras_indices[k][1]) try: protein_type = [item[protein_x4] for item in protein_systems][0][0] #", "and RAS-RAF ########## RAS_only_num_res = 184 RAS_RAF_num_res = 320 #########", "with the above, to handle x4 protein types # ---------------------------------------", "be updated to take into account the periodic nature of", "= \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name", "abs(-(OWAS[i])+180) # made this an absolute value so that the", "# krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') # #", "raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ '", "Only needs to be called x1 time\"\"\" segs = u.segments", "in range(len(OROT)): diff0 = [] for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5,", "in protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF' num_res = [item[protein_x4] for", "= get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states for all KRAS proteins", "is needed so the Naming works below #@TODO fix this", "upper vs. lower leaflet ##### ###### Below might have to", "'+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') # ########## ABOVE SECTION TO DETERMINE", "RAS-RAF) ######## # # if len(kras_indices) == 1: # #", "'+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or name", "above, to handle x4 protein types # --------------------------------------- # ALLOUT", "(OS - OC)/ORS_norm[:, None] OACRS = np.cross(OA, ORS) OZCA =", "= Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED", ":]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS =", "timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF': z_pos = [] ############### NEED", "or 'RAS-RAF'.\\ The 'tag' input defines what is used to", "If feedback code needs index 5 (two_states) from the output,", "krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') ####### HAS TO", "[] # TODO: CS, for AA need bonds to run", "k in range(len(kras_indices)): # start_of_g = kras_indices[k][0] # protein_type =", "for the 'high-z' state ### if (OROT[j] < -45 or", "I changed the selection below, which can be used for", "= (OS - OC)/ORS_norm[:, None] OACRS = np.cross(OA, ORS) OZCA", "time\"\"\" segs = u.segments segs = segs.segids ras_segids = []", "\"\"\"Uses the segments identified in get_segids to make a list", "the 'high-z' state ### if (OROT[j] < -45 or OROT[j]", "unsupported protein_x4 type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+'", "the RAS-ONLY and RAS-RAF simulations ######################### # if protein_type ==", "OF THE PROTEIN GROUP - NEEDED FOR PBC REMOVAL ##############", "== 'rasraf': zshifting = -1 elif protein_x4 == 'ras4araf': zshifting", "for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info protein_info", "RAF LOOP RESIDUES BELOW #################### ############### TODO: TSC, zshifting is", "OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp = (OA - OZPACBCRS)**2", "simulations ######################### # --------------------------------------- # TODO: TSC, I changed the", "PAPS SAPI CHL1') coords = ref0 RotMat = [] OS", "atoms for a KRAS protein starting at 'kras_start'.\"\"\" # return", "name BB') # # else: # # krases0_BB = u.select_atoms('resid", "OFORSIGN[i] < 0.25: OROT[i] = -(OROT[i]) ###### Below introduces new", "# # if k == len(kras_indices)-1: # # krases0_BB =", "range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein", "####### # ########## HAS BEEN REDONE WITH A 'HARD-CODED' NUMBER", "OF THE RAF LOOP RESIDUES BELOW #################### ############### TODO: TSC,", "REMOVAL ############## # # ########## Below hard codes the number", "'tag', i.e. RAS-ONLY or RAS-RAF ##### # OUTPUT = np.zeros([len(OROT),", "this was commented out - please check. #make_whole(krases0_BB) j, rmsd_junk", "in the protein 'tag', i.e. RAS-ONLY or RAS-RAF ##### #", "'+rasraf_segids[0]+' and '+str(tag)) else: RAF = [] protein_info = []#np.empty([len(RAS)+len(RAF),2])", "(two_states) from the output, deleting this four_states will shift that", "in the RAS-ONLY and RAS-RAF simulations ######################### # --------------------------------------- #", "krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') # # else:", "i.e. 'resname ACE1 and name BB'.\\ Only needs to be", "\"\"\"Gets all atoms for a KRAS protein starting at 'kras_start'.\"\"\"", "# TODO: CS, replacing this comment section with the above,", "protein, and whether it is 'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag'", "= segs.segids ras_segids = [] rasraf_segids = [] for i", "OROT[i] > 0: OROT[i] = OROT[i]-180 ###### Above introduces new", "RAS-ONLY OR RAS-RAF) ####### # ########## HAS BEEN REDONE WITH", "+\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or name BB)' mobile0 =", "proteins in path.\"\"\" # res_shift = 8 # all_glycine =", "0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:, None] ORS_tp = np.concatenate((OC,", "OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i] ###### above: old output details....", "ref0 = mobile0 # TSC removed this R, RMSD_junk =", "'+str(tag)) else: RAS = [] if len(rasraf_segids) > 0: RAF", "is taken out of the function so it is only", "r65_74 = krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or name BB)')", "RAS_RAF_num_res = 320 ######### Above hard codes the number of", "u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else: RAS = [] if len(rasraf_segids)", "for i in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i],", "adding in the requirements for the 'high-z' state ### diff0", "BB') ####### HAS TO BE FIXED FOR BACKBONE ATOMS FOR", "the make_whole... # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA", "rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type ==", "protein types # --------------------------------------- # ALLOUT = [] # for", "defines what is used to identify the first residue of", "2]**2)) OC = OA*t[:, None] ORS_tp = np.concatenate((OC, OS), axis=1)", "- NEEDED FOR PBC REMOVAL ############## # ########## POTENTIALLY REDO", "OS = [] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA", "('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT = [] for k", "= np.zeros(len(OROT)) # for j in range(len(OROT)): # diff0 =", "# OUTPUT = np.zeros([len(OROT), 6]) # for i in range(len(OROT)):", "OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)])", "This can be removed # def get_kras(syst, kras_start): # \"\"\"Gets", "in the RAS-ONLY and RAS-RAF simulations ######################### # if protein_type", "None] OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp = np.concatenate((OA, OS),", "diff0.sort() states[j] = diff0[0][1] elif protein_type == 'RAS-RAF': states =", "range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ########## Below is taken out", "NEEDED FOR PBC REMOVAL ############## # # ########## Below hard", "TO CONFIRM THE SELECTION OF THE RAF LOOP RESIDUES ABOVE", "hard codes the number of residues/beads in the RAS-ONLY and", "and (name CA or name BB)' mobile0 = u.select_atoms(str(u_selection)).positions -", "what is used to identify the first residue of the", "have these on import make them as an init mummi_core.init()", "RAS_only_num_res # elif protein_type == 'RAS-RAF': # num_res = RAS_RAF_num_res", "= mobile0 to test for now # ref0 = mobile0", "if (OROT[j] < -45 or OROT[j] > 140) and z_pos[j]", "CA or name BB)') ############### NEED TO CONFIRM THE SELECTION", "- u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something wrong with ref0 from", "# TODO: CS, my edits to test # TODO: TSC,", "= np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :])))", "diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1] elif protein_type == 'RAS-RAF':", "OROT[i], 'n/a', int(states[i]) elif protein_type == 'RAS-RAF': OUTPUT = np.zeros([len(OROT),", "THE RAF LOOP RESIDUES BELOW #################### ############### TODO: TSC, zshifting", "The 'tag' input defines what is used to identify the", "# RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above", "Adjusted for AA lipid names ######## # lipids = u.select_atoms('resname", "requirements for the 'high-z' state ### if (OROT[j] < -45", "i in range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ########## Below is", "RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above section", "the first thing in the script from logging import getLogger", "math ############## Below section needs to be uncommented ############ import", "for now # ref0 = mobile0 # TSC removed this", "TODO: TSC, The reference structure has to currently be set", "Only needs to be called x1 time\"\"\" ras_segids, rasraf_segids =", "The reference structure has to currently be set as the", "= 0 else: zshifting = 0 LOGGER.error('Found unsupported protein_x4 type')", "segs = segs.segids ras_segids = [] rasraf_segids = [] for", "#make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if", "# num_res = RAS_RAF_num_res # ########## Above hard codes the", "z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP = np.array(RotMat) OS = np.array(OS)", "str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name CA or name BB)' r2_26r40_56r69_166_ref", "macrostate4[i,6]]) # diff0.sort() # four_states[j] = diff0[0][1]+1 ###### below: old", "krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or name BB)') timeframes =", "PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ######## # # if", "1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS - OC)/ORS_norm[:, None] OACRS", "for AA, need to bring that back on once all", "ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp =", "= Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)]) for", "mummi_ras from mummi_core.utils import Naming # # Logger has to", "# TSC removed this R, RMSD_junk = align.rotation_matrix(mobile0, ref0) ########", "= mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF':", "two_states[i] ###### above: old output details.... ###################################### ###### below: NEW", "account for upper vs. lower leaflet ##### ###### Below might", "+\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA or", "###### Assume we want to remove this? Where is the", "#################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0: diff =", "# num_res = RAS_only_num_res # elif protein_type == 'RAS-RAF': #", "x4 cases: # [{protein_x4: (protein_type, num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY',", "Below hard codes the number of residues within RAS-only and", "mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type == 'RAS-RAF': z_pos", "have to be updated to take into account the periodic", "i in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i],", "u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or name BB)') krases0_BB =", "states[j] = 3 else: ### above: adding in the requirements", "the periodic nature of the rotation ###### ###### Assume we", "(WHETHER RAS-ONLY OR RAS-RAF) ######## # # if len(kras_indices) ==", "positive for i in range(len(OROT)): if OROT[i] < 0: OROT[i]", "in range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try: protein_type", "= 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' ' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' '", "<NAME>. this was commented out - please check. #make_whole(krases0_BB) j,", "OR RAS-RAF) ####### # ########## HAS BEEN REDONE WITH A", "diff0 = [] for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5,", "Innitilize MuMMI if it has not been done before #", "OC)/ORS_norm[:, None] OACRS = np.cross(OA, ORS) OZCA = OA *", "# for j in range(len(OROT)): # diff0 = [] #", "Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate", "= [] for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]])", "OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp = np.concatenate((OA, OS), axis=1)", "dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate =", "# # if len(kras_indices) == 1: # # krases0_BB =", "if diff < 0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos =", "= [] if len(rasraf_segids) > 0: RAF = u.select_atoms('segid '+rasraf_segids[0]+'", "if segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i])", "range(len(OROT)): if OROT[i] < 0: OROT[i] = -(OROT[i]) for i", "5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:, None] ORS_tp =", "CHOL') lipids = u.select_atoms('resname POPC PAPC POPE DIPE SSM PAPS", "kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not using these for", "SELECTION OF THE RAF LOOP RESIDUES ABOVE #################### diff =", "OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT) #np.savetxt(str(tpr)+\"_tilt_rot_z_state.KRAS_\"+str(k+1)+\".txt\", OUTPUT, fmt=['%i','%10.3f','%10.3f','%10.3f','%i','%i'],", "k in range(len(kras_indices)): start_of_g = kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try:", "str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return np.asarray(ALLOUT) #np.savetxt(str(tpr)+\"_tilt_rot_z_state.KRAS_\"+str(k+1)+\".txt\",", "1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB')", "of the function so it is only done once #########", "NEEDED FOR PBC REMOVAL ############## # ########## POTENTIALLY REDO WITH", "len(ras_segids) > 0: RAS = u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else:", "POPE DIPE DPSM PAPS PAP6 CHOL') lipids = u.select_atoms('resname POPC", "needs to be called x1 time\"\"\" segs = u.segments segs", "+\\ ' and (name CA or name BB)') ############### NEED", "range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() # four_states[j] = diff0[0][1]+1", "############## above section needs to be uncommented ############ # TODO:", "A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY", "Where is the code that reads this information? i.e. will", "RAS = u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else: RAS = []", "or name BB)') u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' '", "= [] rasraf_segids = [] for i in range(len(segs)): #", "LOGGER = getLogger(__name__) # # Innitilize MuMMI if it has", "# diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() # four_states[j] = diff0[0][1]+1 ######", "= u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\", "are ACE caps that are separate residues in AA #zshifting=-1", "# krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') ####### HAS", "' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA", "# TODO: TSC, path to the reference structure is: mummi_resources/structures/", "mummi.init(True) # This is needed so the Naming works below", "range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i]) elif", "for i in range(len(OROT)): if OROT[i] < 0: OROT[i] =", "# # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') #######", "'+ras_segids[0]+' and '+str(tag)) else: RAS = [] if len(rasraf_segids) >", "for i in range(len(segs)): # print(segs[i]) if segs[i][-3:] == 'RAS':", "RAS-only and RAS-RAF ########## ####### This can be removed #", "the output, deleting this four_states will shift that to index", "i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]]) # diff0.sort() # four_states[j]", "1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)]) for i in range(len(ORS)):", "os import numpy as np import math ############## Below section", "PAPC POPE DIPE SSM PAPS SAPI CHL1') coords = ref0", "protein_systems = [{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY',", "needs index 5 (two_states) from the output, deleting this four_states", "@todo add Pilot2-splash-app disclaimer ############################################################################### \"\"\" Get's KRAS states \"\"\"", "np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates,", "OA*t[:, None] ORS_tp = np.concatenate((OC, OS), axis=1) ORS_norm = (((ORS_tp[:,", "np.array([0, 0, 1]) Z_unit = Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB", "# diff0 = [] # for i in range(len(macrostate4)): #", "HAVE the Z-distance ###################### ###### Updated - Added in the", "# Innitilize MuMMI if it has not been done before", "MDAnalysis.lib.mdamath import make_whole import os import numpy as np import", "ref0 = get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states for all KRAS", "= mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe =", "needed so the Naming works below #@TODO fix this so", "set num_res ######### Below hard codes the number of residues", "in path.\"\"\" # res_shift = 8 # all_glycine = u.select_atoms(\"resname", "REDONE WITH A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN GROUP", "for j in range(len(OROT)): diff0 = [] for i in", "this information? i.e. will there be knock-on effects? ###### ######", "len(rasraf_segids) > 0: RAF = u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else:", "z_pos = [] ############### NEED TO CONFIRM THE SELECTION OF", "\"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\"))", "Naming # # Logger has to be initialized the first", "'ras4araf': zshifting = 0 else: zshifting = 0 LOGGER.error('Found unsupported", "and '+str(tag)) else: RAS = [] if len(rasraf_segids) > 0:", "np.zeros(len(OROT)) for j in range(len(OROT)): diff0 = [] for i", "struct. Only called x1 time when class is loaded\"\"\" start_of_g_ref", "# # elif len(kras_indices) > 1: # # if k", "identify the first residue of the protein. i.e. 'resname ACE1", "''' # @Tim and <NAME>. this was commented out -", "#################### ############### TODO: TSC, zshifting is set to -1 (instead", "PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ####### # ########## HAS", "2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi", "i in range(len(OROT)): if OROT[i] < 0: OROT[i] = OROT[i]+180", "from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath import make_whole import os", "OUTPUT = np.zeros([len(OROT), 6]) # for i in range(len(OROT)): #", "# [{protein_x4: (protein_type, num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY', 185), 'ras4araf':", "using these for x4 proteins; instead using protein_systems below to", "= np.zeros(len(OROT)) for j in range(len(OROT)): ### below: adding in", "range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT)", "else: ### above: adding in the requirements for the 'high-z'", "if len(kras_indices) == 1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+'", "in protein_systems][0][1] except: LOGGER.error('Check KRas naming between modules') raise Exception('Error:", "1]) Z_unit = Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:,", "########## RAS_only_num_res = 184 RAS_RAF_num_res = 320 ######### Above hard", "THE PROTEIN GROUP - NEEDED FOR PBC REMOVAL ############## #", "' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA or name BB)')", "old output details.... ###################################### ###### below: NEW output details.... ######################################", "CA or name BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166", "def get_kras(syst, kras_start): # \"\"\"Gets all atoms for a KRAS", "deleting this four_states will shift that to index 4 #######", "= u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else: RAF = [] protein_info", "segs.segids ras_segids = [] rasraf_segids = [] for i in", "NEED TO CONFIRM THE SELECTION OF THE RAF LOOP RESIDUES", "been done before # MUMMI_ROOT = mummi.init(True) # This is", "dirKRASStates = Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates,", "OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i,", "PBC REMOVAL ############## # ########## POTENTIALLY REDO WITH A 'HARD-CODED'", "TODO: TSC, path to the reference structure is: mummi_resources/structures/ kras_ref_universe", "of residues within RAS-only and RAS-RAF ########## ####### This can", "###### If feedback code needs index 5 (two_states) from the", "details.... ###################################### ###### Updated - RAS-only to NOT HAVE the", "RotMat = [] OS = [] r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+'", "above: old output details.... ###################################### ###### below: NEW output details....", "output details.... ###################################### if protein_type == 'RAS-ONLY': OUTPUT = np.zeros([len(OROT),", "for k in range(len(kras_indices)): # start_of_g = kras_indices[k][0] # protein_type", "CS, turn off for now to test beyond this point", "LOOP RESIDUES ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff <", "for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j]", "CHL1') coords = ref0 RotMat = [] OS = []", "u.segments segs = segs.segids ras_segids = [] rasraf_segids = []", "if OFORSIGN[i] < 0.25: OROT[i] = -(OROT[i]) ###### Below introduces", "so we don't have these on import make them as", "+\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name CA", "###### below: NEW output details.... ###################################### if protein_type == 'RAS-ONLY':", "OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp = (OA", "need to do this once) ref0 = get_ref_kras() def getKRASstates(u,kras_indices):", "--------------------------------------- # TODO: TSC, I changed the selection below, which", "def getKRASstates(u,kras_indices): \"\"\"Gets states for all KRAS proteins in path.\"\"\"", "= sorted(protein_info) ######## sort protein info return protein_info def get_ref_kras():", "kras_indices.append(all_glycine[i].index) ########## Below is taken out of the function so", "RAS-RAF ##### # OUTPUT = np.zeros([len(OROT), 6]) # for i", "import math ############## Below section needs to be uncommented ############", "PAPC POPE DIPE DPSM PAPS PAP6 CHOL') lipids = u.select_atoms('resname", "function so it is only done once ######### # CS,", "residues/beads in the RAS-ONLY and RAS-RAF simulations ######################### # if", "Note diffrent number of columns so index change below #", "######## sort protein info protein_info = sorted(protein_info) ######## sort protein", "raise Exception('Error: unknown KRas name') # TODO: CS, replacing this", "###### Above introduces new shift to account for upper vs.", "def get_segids(u): \"\"\"Identifies the list of segments within the system.", "uncommented ############ import mummi_core import mummi_ras from mummi_core.utils import Naming", "np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent number", "in get_segids to make a list of all proteins in", "BB'.\\ Only needs to be called x1 time\"\"\" ras_segids, rasraf_segids", "= np.array(RotMat) OS = np.array(OS) OA = RotMatNP[:, 2, :]/(((RotMatNP[:,", "RAS-RAF simulations ######################### # if protein_type == 'RAS-ONLY': # num_res", "periodic nature of the rotation ###### ###### Assume we want", "OROT[i] < 0: OROT[i] = -(OROT[i]) for i in range(len(OROT)):", "return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref frames (only", "PROTEIN GROUP - NEEDED FOR PBC REMOVAL ############## # #", "zshifting = 0 LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection = u.select_atoms('resid", "u.select_atoms(\"resname GLY\") # kras_indices = [] # for i in", "name BB') # ########## ABOVE SECTION TO DETERMINE WHICH RESIDUES", "else: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB')", "KRAS states \"\"\" import MDAnalysis as mda from MDAnalysis.analysis import", "needs to be uncommented ############ # TODO: CS, my edits", "Outputs a list of the first residue number of the", "system. Only needs to be called x1 time\"\"\" segs =", "to take into account the periodic nature of the rotation", "krases0_BB.guess_bonds() # TODO: CS, turn off for now to test", "2])*180/math.pi OC_temp = np.concatenate((OA, OS), axis=1) t = ((OC_temp[:, 0]*OC_temp[:,", "or name BB)') ############### NEED TO CONFIRM THE SELECTION OF", "np.zeros([len(ORS)]) for i in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i,", "and '+str(tag)) else: RAF = [] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for", "else: RAS = [] if len(rasraf_segids) > 0: RAF =", "' and (name CA or name BB)') u_selection = \\", "be removed def get_segids(u): \"\"\"Identifies the list of segments within", "+\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name CA or name BB)'", "leaflet ##### ###### Below might have to be updated to", "= kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital ref", "'+str(tag)) else: RAF = [] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i", "# start_of_g = kras_indices[k][0] # protein_type = str(kras_indices[k][1]) # ##########", "# elif protein_type == 'RAS-RAF': # num_res = RAS_RAF_num_res #", "OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:,", "knock-on effects? ###### ###### If feedback code needs index 5", "########## Above hard codes the number of residues/beads in the", "RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1] elif protein_type ==", "done once ######### # kras_indices = get_protein_info(u,'resname ACE1 and name", "3 else: ### above: adding in the requirements for the", "< 0: OROT[i] = OROT[i]+180 elif OROT[i] > 0: OROT[i]", "mummi_core import mummi_ras from mummi_core.utils import Naming # # Logger", "init mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate", "number of columns so index change below # TODO: CS,", "0 else: zshifting = 0 LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection", "POPX POPC PAPC POPE DIPE DPSM PAPS PAP6 CHOL') lipids", "np.concatenate((OA, OS), axis=1) t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4])", "to handle x4 protein types # --------------------------------------- # ALLOUT =", "2])**2))**0.5 ORS = (OS - OC)/ORS_norm[:, None] OACRS = np.cross(OA,", "the number of residues/beads in the RAS-ONLY and RAS-RAF simulations", "this comment section with the above, to handle x4 protein", "be set as the 'RAS-ONLY-reference-structure.gro' # TODO: TSC, path to", "###################################### if protein_type == 'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for", "# # Logger has to be initialized the first thing", "requirements for the 'high-z' state ### diff0 = [] for", "np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent number of columns so index", "BB') # ########## ABOVE SECTION TO DETERMINE WHICH RESIDUES ARE", "to the reference structure is: mummi_resources/structures/ kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\"))", "######### Above hard codes the number of residues within RAS-only", "the 'high-z' state ### diff0 = [] for i in", "[item[protein_x4] for item in protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF' num_res", "first residue number of the protein, and whether it is", "'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR", "ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def", "== len(kras_indices)-1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name", "# TODO: CS, turn off for now to test beyond", "ref0 from get_kras_ref() # just making ref0 = mobile0 to", "changed the selection below, which can be used for the", "RMSD_junk = align.rotation_matrix(mobile0, ref0) ######## TODO: TSC, Adjusted for AA", "new shift to account for upper vs. lower leaflet #####", "# print(segs[i]) if segs[i][-3:] == 'RAS': ras_segids.append(segs[i]) if segs[i][-3:] ==", "= krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or name BB)') r65_74", "TSC, I changed the selection below, which can be used", ":]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:,", "= kras_indices[k][0] # protein_type = str(kras_indices[k][1]) # ########## BELOW SECTION", "TODO: CS, something wrong with ref0 from get_kras_ref() # just", "[] rasraf_segids = [] for i in range(len(segs)): # print(segs[i])", "for j in range(len(OROT)): # diff0 = [] # for", "lipids = u.select_atoms('resname POPX POPC PAPC POPE DIPE DPSM PAPS", "Below is taken out of the function so it is", "OACRS = np.cross(OA, ORS) OZCA = OA * OA[:, 2][:,", "FOR BACKBONE ATOMS FOR SPECIFIC PROTEIN # # elif len(kras_indices)", "< -45 or OROT[j] > 140) and z_pos[j] > 4.8:", "systems.\\ Outputs a list of the first residue number of", "a list of all proteins in the systems.\\ Outputs a", "timeframes[i], OWAS[i], OROT[i], z_pos[i], four_states[i], two_states[i] ###### above: old output", "0: RAS = u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else: RAS =", "beyond this point ''' *** for AA, need to bring", "' +\\ 'and (name CA or name BB)' r2_26r40_56r69_166_ref =", "and name BB') ########## Above is taken out of the", "i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ########", "'RAS-ONLY-reference-structure.gro' # TODO: TSC, path to the reference structure is:", "is used to identify the first residue of the protein.", ":], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i,", "######### # CS, for x4 cases: # [{protein_x4: (protein_type, num_res)}]", "('RAS-RAF', 320)}] ALLOUT = [] for k in range(len(kras_indices)): start_of_g", "getLogger(__name__) # # Innitilize MuMMI if it has not been", "name BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid", "= mobile0 # TSC removed this R, RMSD_junk = align.rotation_matrix(mobile0,", "= [] for i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]])", "turn off for now to test beyond this point '''", "need to bring that back on once all else runs", "disclaimer ############################################################################### \"\"\" Get's KRAS states \"\"\" import MDAnalysis as", "= 184 RAS_RAF_num_res = 320 ######### Above hard codes the", "num_res = RAS_RAF_num_res # ########## Above hard codes the number", "number of residues within RAS-only and RAS-RAF ########## RAS_only_num_res =", "= get_protein_info(u,'resname ACE1 and name BB') ########## Above is taken", "PAPS PAP6 CHOL') lipids = u.select_atoms('resname POPC PAPC POPE DIPE", "TODO: TSC, I changed the selection below, which can be", "list of the first residue number of the protein, and", "##### ###### Below might have to be updated to take", "as there are ACE caps that are separate residues in", "name') # TODO: CS, replacing this comment section with the", "OROT[i] < 0: OROT[i] = OROT[i]+180 elif OROT[i] > 0:", "= Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates,", "first thing in the script from logging import getLogger LOGGER", "############ import mummi_core import mummi_ras from mummi_core.utils import Naming #", "currently be set as the 'RAS-ONLY-reference-structure.gro' # TODO: TSC, path", "item in protein_systems][0][1] except: LOGGER.error('Check KRas naming between modules') raise", "'+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or name BB)'", "instead using protein_systems below to set num_res ######### Below hard", "u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and", "u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') ####### HAS TO BE FIXED", "321), 'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT = []", "- NEEDED FOR PBC REMOVAL ############## # # ########## Below", "four_states[j] = diff0[0][1]+1 ###### below: old output details.... ###################################### ######", "OZCA = OA * OA[:, 2][:, None] Z_unit = np.full([len(OZCA),", "/ (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi", "RAS-only and RAS-RAF ########## RAS_only_num_res = 184 RAS_RAF_num_res = 320", "the protein, and whether it is 'RAS-ONLY', or 'RAS-RAF'.\\ The", "TODO: TSC, Adjusted for AA lipid names ######## # lipids", "# Note diffrent number of columns so index change below", "OS), axis=1) t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) +", "RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1] ###### Above might", "all atoms for a KRAS protein starting at 'kras_start'.\"\"\" #", "TSC removed this R, RMSD_junk = align.rotation_matrix(mobile0, ref0) ######## TODO:", "protein_systems below to set num_res ######### Below hard codes the", "that to index 4 ####### # four_states = np.zeros(len(OROT)) #", "= 0 LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+'", "[item[protein_x4] for item in protein_systems][0][1] except: LOGGER.error('Check KRas naming between", "of the rotation ###### if protein_type == 'RAS-ONLY': states =", "Above hard codes the number of residues within RAS-only and", "OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i]) ALLOUT.append(OUTPUT) return", "off for now to test beyond this point ''' ***", "0.25: OROT[i] = -(OROT[i]) ###### Below introduces new shift to", "names ######## # lipids = u.select_atoms('resname POPX POPC PAPC POPE", "this an absolute value so that the tilt remains positive", "2]**2)**0.5)[:, None] OFORSIGN_temp = (OA - OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:,", "naming between modules') raise Exception('Error: unknown KRas name') # TODO:", "ras_segids = [] rasraf_segids = [] for i in range(len(segs)):", "input defines what is used to identify the first residue", "protein_type == 'RAS-RAF': states = np.zeros(len(OROT)) for j in range(len(OROT)):", "below: NEW output details.... ###################################### if protein_type == 'RAS-ONLY': OUTPUT", "# This is needed so the Naming works below #@TODO", "made this an absolute value so that the tilt remains", "# Logger has to be initialized the first thing in", "PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ####### # ##########", "in the requirements for the 'high-z' state ### diff0 =", "[]#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)):", "these for x4 proteins; instead using protein_systems below to set", "= getLogger(__name__) # # Innitilize MuMMI if it has not", "import align from MDAnalysis.lib.mdamath import make_whole import os import numpy", "krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') # ########## ABOVE", "This can be removed def get_segids(u): \"\"\"Identifies the list of", "PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) ######## # #", "index 5 (two_states) from the output, deleting this four_states will", "shift that to index 4 ####### # four_states = np.zeros(len(OROT))", "Z_adjust = np.array([0, 0, 1]) Z_unit = Z_unit*Z_adjust Z_OZCA =", "make_whole... # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or", "list of segments within the system. Only needs to be", "section with the above, to handle x4 protein types #", "name BB'.\\ Only needs to be called x1 time\"\"\" ras_segids,", "PROTEIN # # elif len(kras_indices) > 1: # # if", "else: RAF = [] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i in", "Updated - Added in the protein 'tag', i.e. RAS-ONLY or", "NUMBER OF RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF)", "RESIDUES ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0:", "states[j] = diff0[0][1] ###### Above might have to be updated", "separate residues in AA #zshifting=-1 if protein_x4 == 'rasraf': zshifting", "kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try: protein_type = [item[protein_x4] for item", "-(OROT[i]) for i in range(len(OROT)): if OFORSIGN[i] < 0.25: OROT[i]", "into account the periodic nature of the rotation ###### ######", "all_glycine = u.select_atoms(\"resname GLY\") # kras_indices = [] # for", "run make_whole() # krases0_BB.guess_bonds() # TODO: CS, turn off for", "'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT", "CONFIRM THE SELECTION OF THE RAF LOOP RESIDUES BELOW ####################", "########## Below hard codes the number of residues/beads in the", "' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or name BB)' mobile0", "OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB,", "i.e. will there be knock-on effects? ###### ###### If feedback", "for item in protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF' num_res =", "to -1 (instead of -2), as there are ACE caps", "name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() #", "the number of residues within RAS-only and RAS-RAF ########## #######", "works below #@TODO fix this so we don't have these", "using protein_systems below to set num_res ######### Below hard codes", "DETERMINE WHICH RESIDUES ARE PART OF THE PROTEIN GROUP -", "protein_info def get_ref_kras(): \"\"\"Gets the reference KRAS struct. Only called", "# kras_indices = get_protein_info(u,'resname ACE1 and name BB') ########## Above", "RAS-RAF simulations ######################### # --------------------------------------- # TODO: TSC, I changed", "has to currently be set as the 'RAS-ONLY-reference-structure.gro' # TODO:", "lipids = u.select_atoms('resname POPC PAPC POPE DIPE SSM PAPS SAPI", "protein_type == 'RAS-RAF': # num_res = RAS_RAF_num_res # ########## Above", "else runs *** ''' # @Tim and <NAME>. this was", "protein info return protein_info def get_ref_kras(): \"\"\"Gets the reference KRAS", "i in range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] =", "frames (only need to do this once) ref0 = get_ref_kras()", "FIXED FOR BACKBONE ATOMS FOR SPECIFIC PROTEIN # # elif", "= np.concatenate((OA, OS), axis=1) t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:,", "in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]]) diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1]", "THE SELECTION OF THE RAF LOOP RESIDUES BELOW #################### ###############", "r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass() # Load inital", "'+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or name BB)') krases0_BB = u.select_atoms('resid", "in range(len(kras_indices)): # start_of_g = kras_indices[k][0] # protein_type = str(kras_indices[k][1])", "= ref0 RotMat = [] OS = [] r152_165 =", "= ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:,", "None] ORS_tp = np.concatenate((OC, OS), axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:,", "elif len(kras_indices) > 1: # # if k == len(kras_indices)-1:", "[] ############### NEED TO CONFIRM THE SELECTION OF THE RAF", "will shift that to index 4 ####### # four_states =", "# ########## POTENTIALLY REDO WITH A 'HARD-CODED' NUMBER OF RESIDUES", "######## # lipids = u.select_atoms('resname POPX POPC PAPC POPE DIPE", "number of the protein, and whether it is 'RAS-ONLY', or", "TODO: CS, my edits to test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt')", "not using these for x4 proteins; instead using protein_systems below", "OS = np.array(OS) OA = RotMatNP[:, 2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:,", "type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\", "RAS-only to NOT HAVE the Z-distance ###################### ###### Updated -", "############################################################################### # @todo add Pilot2-splash-app disclaimer ############################################################################### \"\"\" Get's KRAS", "OC = OA*t[:, None] ORS_tp = np.concatenate((OC, OS), axis=1) ORS_norm", "this four_states will shift that to index 4 ####### #", "test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ##############", "OROT = OROTNOTSIGNED for i in range(len(OROT)): if OROT[i] <", "\"ras-raf-states.txt\"),comments='#') # Note diffrent number of columns so index change", "OS), axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:,", "#RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note", "'RAS-RAF'.\\ The 'tag' input defines what is used to identify", "code needs index 5 (two_states) from the output, deleting this", "'+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or name BB)') r65_74 = krases0_BB.select_atoms('resid", "mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not using", "name BB)') u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\", "protein_type == 'RAS-ONLY': states = np.zeros(len(OROT)) for j in range(len(OROT)):", "except: LOGGER.error('Check KRas naming between modules') raise Exception('Error: unknown KRas", "*** ''' # @Tim and <NAME>. this was commented out", "4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS - OC)/ORS_norm[:, None]", "proteins; instead using protein_systems below to set num_res ######### Below", "> 0: OROT[i] = OROT[i]-180 ###### Above introduces new shift", "= [{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184),", "# @Tim and <NAME>. this was commented out - please", "it has not been done before # MUMMI_ROOT = mummi.init(True)", "# krases0_BB.guess_bonds() # TODO: CS, turn off for now to", "# # ########## Below hard codes the number of residues/beads", "= [] for i in range(len(segs)): # print(segs[i]) if segs[i][-3:]", "for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF'))", "in the systems.\\ Outputs a list of the first residue", "2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:, None] ORS_tp", "= u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else: RAS = [] if", "[{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184), 'rasraf':", "= u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name CA or name BB)') krases0_BB", "SELECTION OF THE RAF LOOP RESIDUES BELOW #################### ############### TODO:", "1) Z_adjust = np.array([0, 0, 1]) Z_unit = Z_unit*Z_adjust Z_OZCA", "be called x1 time\"\"\" segs = u.segments segs = segs.segids", "###### ###### Assume we want to remove this? Where is", "the tilt remains positive for i in range(len(OROT)): if OROT[i]", "edits to test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate =", "None] OROTNOTSIGNED = np.zeros([len(ORS)]) for i in range(len(ORS)): OROTNOTSIGNED[i] =", "'resname ACE1 and name BB'.\\ Only needs to be called", "kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS,", "= OROT[i]+180 elif OROT[i] > 0: OROT[i] = OROT[i]-180 ######", "### if (OROT[j] < -45 or OROT[j] > 140) and", "i in range(len(OWAS)): OWAS[i] = abs(-(OWAS[i])+180) # made this an", "be knock-on effects? ###### ###### If feedback code needs index", "ref0) ######## TODO: TSC, Adjusted for AA lipid names ########", "of residues/beads in the RAS-ONLY and RAS-RAF simulations ######################### #", "RAF = [] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)):", "reference KRAS struct. Only called x1 time when class is", "as the 'RAS-ONLY-reference-structure.gro' # TODO: TSC, path to the reference", "start_of_g = kras_indices[k][0] protein_x4 = str(kras_indices[k][1]) try: protein_type = [item[protein_x4]", "OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED", "= krases0_BB.select_atoms('resid '+str(start_of_g+63)+':'+str(start_of_g+72)+' and (name CA or name BB)') timeframes", "###################################### ###### below: NEW output details.... ###################################### if protein_type ==", "CS, my edits to test # TODO: TSC, The reference", "adding in the requirements for the 'high-z' state ### if", "\"\"\"Identifies the list of segments within the system. Only needs", "needs to be uncommented ############ import mummi_core import mummi_ras from", "(np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross", "str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i]) elif protein_type == 'RAS-RAF':", "> 0: RAS = u.select_atoms('segid '+ras_segids[0]+' and '+str(tag)) else: RAS", "MDAnalysis as mda from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath import", "RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1] elif protein_type == 'RAS-RAF': states", "= RAS_only_num_res # elif protein_type == 'RAS-RAF': # num_res =", "320 ######### Above hard codes the number of residues within", "= np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate =", "the periodic nature of the rotation ###### if protein_type ==", "Assume we want to remove this? Where is the code", "0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED for i in range(len(OROT)):", "the first residue number of the protein, and whether it", "be called x1 time\"\"\" ras_segids, rasraf_segids = get_segids(u) if len(ras_segids)", "all KRAS proteins in path.\"\"\" # res_shift = 8 #", "< 0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP", "= str(kras_indices[k][1]) try: protein_type = [item[protein_x4] for item in protein_systems][0][0]", "name BB') ########## Above is taken out of the function", "TSC, Adjusted for AA lipid names ######## # lipids =", "FOR SPECIFIC PROTEIN # # elif len(kras_indices) > 1: #", "ALLOUT = [] for k in range(len(kras_indices)): start_of_g = kras_indices[k][0]", "TSC, zshifting is set to -1 (instead of -2), as", "called x1 time when class is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid", "= [] # for k in range(len(kras_indices)): # start_of_g =", "to do this once) ref0 = get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets", "Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:,", "get_segids(u): \"\"\"Identifies the list of segments within the system. Only", "the number of residues within RAS-only and RAS-RAF ########## RAS_only_num_res", "#@TODO fix this so we don't have these on import", "set as the 'RAS-ONLY-reference-structure.gro' # TODO: TSC, path to the", "upper vs. lower leaflet ##### for i in range(len(OWAS)): OWAS[i]", "and RAS-RAF simulations ######################### # if protein_type == 'RAS-ONLY': #", "zshifting is set to -1 (instead of -2), as there", "start_of_g = kras_indices[k][0] # protein_type = str(kras_indices[k][1]) # ########## BELOW", "ORS = (OS - OC)/ORS_norm[:, None] OACRS = np.cross(OA, ORS)", "< 0.25: OROT[i] = -(OROT[i]) ###### Below introduces new shift", "so it is only done once ######### # CS, for", "my edits to test # TODO: TSC, The reference structure", "it is only done once ######### # kras_indices = get_protein_info(u,'resname", "u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something wrong with ref0", "diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0: diff = diff+(u.dimensions[2]/10)", "bring that back on once all else runs *** '''", "np.loadtxt('ras-states.txt') # RAS_RAF_macrostate = np.loadtxt('ras-raf-states.txt') ############## above section needs to", "axis=1) t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:, 1]*OC_temp[:, 4]) + (OC_temp[:,", "protein starting at 'kras_start'.\"\"\" # return syst.atoms[kras_start:kras_start+428] ####### This can", "residue number of the protein, and whether it is 'RAS-ONLY',", "or RAS-RAF ##### # OUTPUT = np.zeros([len(OROT), 6]) # for", "# all_glycine = u.select_atoms(\"resname GLY\") # kras_indices = [] #", "to NOT HAVE the Z-distance ###################### ###### Updated - Added", "##### # OUTPUT = np.zeros([len(OROT), 6]) # for i in", "MuMMI if it has not been done before # MUMMI_ROOT", "(name CA or name BB)') ############### NEED TO CONFIRM THE", "ABOVE SECTION TO DETERMINE WHICH RESIDUES ARE PART OF THE", "an init mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') #", "# diff0.sort() # four_states[j] = diff0[0][1]+1 ###### below: old output", "import getLogger LOGGER = getLogger(__name__) # # Innitilize MuMMI if", "timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i]) elif protein_type == 'RAS-RAF': OUTPUT", "protein_x4 == 'rasraf': zshifting = -1 elif protein_x4 == 'ras4araf':", "to be called x1 time\"\"\" segs = u.segments segs =", "WHICH RESIDUES ARE PART OF THE PROTEIN GROUP - NEEDED", ":], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i, :]))))*180/math.pi OZPACBCRS_cross =", "Naming works below #@TODO fix this so we don't have", "for all KRAS proteins in path.\"\"\" # res_shift = 8", "str(start_of_g+38)+':'+str(start_of_g+54)+' ' +\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA or name", "segments identified in get_segids to make a list of all", "getLogger LOGGER = getLogger(__name__) # # Innitilize MuMMI if it", "add Pilot2-splash-app disclaimer ############################################################################### \"\"\" Get's KRAS states \"\"\" import", "'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag' input defines what is used", "> 140) and z_pos[j] > 4.8: states[j] = 3 else:", "account the periodic nature of the rotation ###### ###### Assume", "np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates,", "test beyond this point ''' *** for AA, need to", "########## HAS BEEN REDONE WITH A 'HARD-CODED' NUMBER OF RESIDUES", "range(len(RAS_ONLY_macrostate)): #diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1] elif", "SSM PAPS SAPI CHL1') coords = ref0 RotMat = []", "feedback code needs index 5 (two_states) from the output, deleting", "'high-z' state ### diff0 = [] for i in range(len(RAS_RAF_macrostate)):", "x1 time when class is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection", "and RAS-RAF simulations ######################### # --------------------------------------- # TODO: TSC, I", "+\\ str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA or name BB)') u_selection", "2, :]/(((RotMatNP[:, 2, 0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS", "i.e. RAS-ONLY or RAS-RAF ##### # OUTPUT = np.zeros([len(OROT), 6])", "OA * OA[:, 2][:, None] Z_unit = np.full([len(OZCA), 3], 1)", "ACE1 and name BB') ########## Above is taken out of", "not been done before # MUMMI_ROOT = mummi.init(True) # This", "OC_temp = np.concatenate((OA, OS), axis=1) t = ((OC_temp[:, 0]*OC_temp[:, 3])+(OC_temp[:,", "RAS-RAF ########## ####### This can be removed # def get_kras(syst,", "np.zeros(len(OROT)) # for j in range(len(OROT)): # diff0 = []", "OF RESIDUES PER PROTEIN GROUP (WHETHER RAS-ONLY OR RAS-RAF) #######", "output details.... ###################################### ###### Updated - RAS-only to NOT HAVE", "return ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the segments identified in", "# # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name BB') #", "###### Updated - Added in the protein 'tag', i.e. RAS-ONLY", "######################### # if protein_type == 'RAS-ONLY': # num_res = RAS_only_num_res", "BB') # # else: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+'", ":]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) * (np.sqrt(np.dot(ORS[i, :], ORS[i,", "# made this an absolute value so that the tilt", "####### This can be removed def get_segids(u): \"\"\"Identifies the list", "so the Naming works below #@TODO fix this so we", "code that reads this information? i.e. will there be knock-on", "protein 'tag', i.e. RAS-ONLY or RAS-RAF ##### # OUTPUT =", "(name CA or name BB)' mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass()", "krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or name BB)') r65_74 =", "in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i in range(len(RAF)): protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort", "numpy as np import math ############## Below section needs to", "'RAS-ONLY': # num_res = RAS_only_num_res # elif protein_type == 'RAS-RAF':", "############## # ########## POTENTIALLY REDO WITH A 'HARD-CODED' NUMBER OF", "introduces new shift to account for upper vs. lower leaflet", "# TODO: CS, my edits to test # RAS_ONLY_macrostate =", "Above might have to be updated to take into account", "POPC PAPC POPE DIPE SSM PAPS SAPI CHL1') coords =", "-1 elif protein_x4 == 'ras4araf': zshifting = 0 else: zshifting", "str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name CA or", "CA or name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions -", "2, 2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:, 2, 2])*180/math.pi OC_temp =", "np.zeros([len(OROT), 6]) # for i in range(len(OROT)): # OUTPUT[i] =", "j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time) if protein_type", "lower leaflet ##### ###### Below might have to be updated", "########## POTENTIALLY REDO WITH A 'HARD-CODED' NUMBER OF RESIDUES PER", "# TODO: TSC, I changed the selection below, which can", "(name CA or name BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds()", "= [item[protein_x4] for item in protein_systems][0][0] # 'RAS-ONLY' OR 'RAS-RAF'", "(((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS = (OS", "(instead of -2), as there are ACE caps that are", "rasraf_segids = [] for i in range(len(segs)): # print(segs[i]) if", "on import make them as an init mummi_core.init() dirKRASStates =", "####### # four_states = np.zeros(len(OROT)) # for j in range(len(OROT)):", "and name BB') # # else: # # krases0_BB =", "SPECIFIC PROTEIN # # elif len(kras_indices) > 1: # #", "import make them as an init mummi_core.init() dirKRASStates = Naming.dir_res('states')", "u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else: RAF = [] protein_info =", "number of residues/beads in the RAS-ONLY and RAS-RAF simulations #########################", "int(states[i]) elif protein_type == 'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for", "RAS-ONLY and RAS-RAF simulations ######################### # --------------------------------------- # TODO: TSC,", "initialized the first thing in the script from logging import", "= np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent", "get_ref_kras(): \"\"\"Gets the reference KRAS struct. Only called x1 time", "elif protein_type == 'RAS-RAF': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i", "'rasraf': zshifting = -1 elif protein_x4 == 'ras4araf': zshifting =", "= np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate =", "= diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP = np.array(RotMat) OS", "(OC_temp[:, 2]*OC_temp[:, 5]))/((OC_temp[:, 0]**2)+(OC_temp[:, 1]**2)+(OC_temp[:, 2]**2)) OC = OA*t[:, None]", "'RAS': ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids", "# TODO: CS, something wrong with ref0 from get_kras_ref() #", "and (name CA or name BB)') u_selection = \\ 'resid", "this point ''' *** for AA, need to bring that", "= u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and", "OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], 'n/a', int(states[i]) elif protein_type", "back on once all else runs *** ''' # @Tim", "# # Innitilize MuMMI if it has not been done", "segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses", "to be called x1 time\"\"\" ras_segids, rasraf_segids = get_segids(u) if", "and name BB') ####### HAS TO BE FIXED FOR BACKBONE", "we don't have these on import make them as an", "- OC)/ORS_norm[:, None] OACRS = np.cross(OA, ORS) OZCA = OA", "a list of the first residue number of the protein,", "or name BB)' r2_26r40_56r69_166_ref = kras_ref_universe.select_atoms(str(ref_selection)) return kras_ref_universe.select_atoms(str(ref_selection)).positions - kras_ref_universe.select_atoms(str(ref_selection)).center_of_mass()", "(protein_type, num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321),", "the script from logging import getLogger LOGGER = getLogger(__name__) #", "# if protein_type == 'RAS-ONLY': # num_res = RAS_only_num_res #", "str(start_of_g+67)+':'+str(start_of_g+164)+' and (name CA or name BB)' mobile0 = u.select_atoms(str(u_selection)).positions", "KRas naming between modules') raise Exception('Error: unknown KRas name') #", "== 'RAS-ONLY': # num_res = RAS_only_num_res # elif protein_type ==", "CS, my edits to test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') #", "import mummi_core import mummi_ras from mummi_core.utils import Naming # #", "CA or name BB)') u_selection = \\ 'resid '+str(start_of_g)+':'+str(start_of_g+24)+' '+str(start_of_g+38)+':'+str(start_of_g+54)+'", "-(OROT[i]) ###### Below introduces new shift to account for upper", "np.concatenate((OC, OS), axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:,", "structure has to currently be set as the 'RAS-ONLY-reference-structure.gro' #", "elif OROT[i] > 0: OROT[i] = OROT[i]-180 ###### Above introduces", "ORS[i, :]))))*180/math.pi OZPACBCRS_cross = np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:,", "= np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)): OUTPUT[i] = str(protein_type),", "0 LOGGER.error('Found unsupported protein_x4 type') raf_loops_selection = u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' '", "= OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT = OROTNOTSIGNED for i", "str(start_of_g+67)+':'+str(start_of_g+164)+\\ ' and (name CA or name BB)') u_selection =", "can be used for the make_whole... # krases0_BB = u.select_atoms('resid", "diff0[0][1] ###### Above might have to be updated to take", "# TODO: TSC, The reference structure has to currently be", "num_res)}] protein_systems = [{'ras4a': ('RAS-ONLY', 185), 'ras4araf': ('RAS-RAF', 321), 'ras':", "= np.zeros([len(OROT), 6]) # for i in range(len(OROT)): # OUTPUT[i]", "== 'RAS-ONLY': OUTPUT = np.zeros([len(OROT), 6]).astype(object) for i in range(len(OROT)):", "get_protein_info(u,tag): \"\"\"Uses the segments identified in get_segids to make a", "is set to -1 (instead of -2), as there are", "= Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\"))", "diff0.sort() states[j] = diff0[0][1] ###### Above might have to be", "rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def get_protein_info(u,tag): \"\"\"Uses the segments identified", "### diff0 = [] for i in range(len(RAS_RAF_macrostate)): #diff0.append([((RAS_RAF_macrostate[i,0]-OWAS[j])**2+(RAS_RAF_macrostate[i,1]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,6]])", "kras_start): # \"\"\"Gets all atoms for a KRAS protein starting", "GROUP - NEEDED FOR PBC REMOVAL ############## # # ##########", "make_whole import os import numpy as np import math ##############", "types # --------------------------------------- # ALLOUT = [] # for k", "###################################### ###### Updated - RAS-only to NOT HAVE the Z-distance", "if len(rasraf_segids) > 0: RAF = u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag))", "is loaded\"\"\" start_of_g_ref = kras_ref_universe.residues[0].resid ref_selection = 'resid '+str(start_of_g_ref)+':'+str(start_of_g_ref+24)+' '", "be used for the make_whole... # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+'", "get_kras_ref() # just making ref0 = mobile0 to test for", "# krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') # ##########", "for item in protein_systems][0][1] except: LOGGER.error('Check KRas naming between modules')", "nature of the rotation ###### if protein_type == 'RAS-ONLY': states", "= [] # for i in range(len(macrostate4)): # diff0.append([((macrostate4[i,0]-OWAS[j])**2+(macrostate4[i,1]-OROT[j])**2)**0.5, macrostate4[i,6]])", "# TODO: CS, not using these for x4 proteins; instead", "simulations ######################### # if protein_type == 'RAS-ONLY': # num_res =", "diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos = np.array(z_pos) RotMatNP = np.array(RotMat) OS =", "= np.zeros(len(OROT)) for j in range(len(OROT)): diff0 = [] for", "in range(0, len(all_glycine), 26): # kras_indices.append(all_glycine[i].index) ########## Below is taken", "'+str(start_of_g)+':'+str(len(u.residues))+' and name BB') # # else: # # krases0_BB", "= get_segids(u) if len(ras_segids) > 0: RAS = u.select_atoms('segid '+ras_segids[0]+'", "4.8: states[j] = 3 else: ### above: adding in the", "value so that the tilt remains positive for i in", "will there be knock-on effects? ###### ###### If feedback code", "Below section needs to be uncommented ############ import mummi_core import", "before # MUMMI_ROOT = mummi.init(True) # This is needed so", "i in range(len(OROT)): if OFORSIGN[i] < 0.25: OROT[i] = -(OROT[i])", "== 'RAS-RAF': states = np.zeros(len(OROT)) for j in range(len(OROT)): ###", "reference structure has to currently be set as the 'RAS-ONLY-reference-structure.gro'", "Below might have to be updated to take into account", "section needs to be uncommented ############ import mummi_core import mummi_ras", "np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) / (np.sqrt(np.dot(OZPACB[i, :], OZPACB[i, :]))) *", "elif protein_type == 'RAS-RAF': states = np.zeros(len(OROT)) for j in", "# ########## ABOVE SECTION TO DETERMINE WHICH RESIDUES ARE PART", "Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED = np.zeros([len(ORS)]) for i", "ras_segids, rasraf_segids = get_segids(u) if len(ras_segids) > 0: RAS =", "185), 'ras4araf': ('RAS-RAF', 321), 'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}]", "protein_type = str(kras_indices[k][1]) # ########## BELOW SECTION TO DETERMINE WHICH", "def get_ref_kras(): \"\"\"Gets the reference KRAS struct. Only called x1", "Z_OZCA = Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None]", "############## # # ########## Below hard codes the number of", "ref0 = mobile0 to test for now # ref0 =", "if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return ras_segids, rasraf_segids def get_protein_info(u,tag):", "HAS BEEN REDONE WITH A 'HARD-CODED' NUMBER OF RESIDUES PER", "== 1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and name", "r152_165 = krases0_BB.select_atoms('resid '+str(start_of_g+150)+':'+str(start_of_g+163)+' and (name CA or name BB)')", "GLY\") # kras_indices = [] # for i in range(0,", "coords = ref0 RotMat = [] OS = [] r152_165", "# if len(kras_indices) == 1: # # krases0_BB = u.select_atoms('resid", "so that the tilt remains positive for i in range(len(OROT)):", "= [] # for i in range(0, len(all_glycine), 26): #", "needs to be called x1 time\"\"\" ras_segids, rasraf_segids = get_segids(u)", "POPC PAPC POPE DIPE DPSM PAPS PAP6 CHOL') lipids =", "below # TODO: CS, my edits to test # RAS_ONLY_macrostate", "the protein. i.e. 'resname ACE1 and name BB'.\\ Only needs", "in range(len(OROT)): if OFORSIGN[i] < 0.25: OROT[i] = -(OROT[i]) ######", "k == len(kras_indices)-1: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(len(u.residues))+' and", "z_pos = np.array(z_pos) RotMatNP = np.array(RotMat) OS = np.array(OS) OA", "the segments identified in get_segids to make a list of", "[] protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for", "info return protein_info def get_ref_kras(): \"\"\"Gets the reference KRAS struct.", "that back on once all else runs *** ''' #", "path.\"\"\" # res_shift = 8 # all_glycine = u.select_atoms(\"resname GLY\")", "# kras_indices = [] # for i in range(0, len(all_glycine),", "POTENTIALLY REDO WITH A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN", "rasraf_segids = get_segids(u) if len(ras_segids) > 0: RAS = u.select_atoms('segid", "be uncommented ############ # TODO: CS, my edits to test", "(name CA or name BB)') timeframes = [] # TODO:", "return syst.atoms[kras_start:kras_start+428] ####### This can be removed def get_segids(u): \"\"\"Identifies", "sort protein info return protein_info def get_ref_kras(): \"\"\"Gets the reference", "' +\\ str(start_of_g_ref+38)+':'+str(start_of_g_ref+54)+' ' +\\ str(start_of_g_ref+67)+':'+str(start_of_g_ref+164)+' ' +\\ 'and (name", "np.cross(OZPACB, ORS) OZPACBCRS = OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp", "vs. lower leaflet ##### for i in range(len(OWAS)): OWAS[i] =", "# ########## Below hard codes the number of residues/beads in", "3], 1) Z_adjust = np.array([0, 0, 1]) Z_unit = Z_unit*Z_adjust", "# @todo add Pilot2-splash-app disclaimer ############################################################################### \"\"\" Get's KRAS states", "- OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT =", "name BB)') ############### NEED TO CONFIRM THE SELECTION OF THE", "import Naming # # Logger has to be initialized the", "sort protein info protein_info = sorted(protein_info) ######## sort protein info", "'RAS-RAF': states = np.zeros(len(OROT)) for j in range(len(OROT)): ### below:", "removed # def get_kras(syst, kras_start): # \"\"\"Gets all atoms for", "8 # all_glycine = u.select_atoms(\"resname GLY\") # kras_indices = []", "within the system. Only needs to be called x1 time\"\"\"", "protein_type == 'RAS-RAF': z_pos = [] ############### NEED TO CONFIRM", "= u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO: CS, something wrong with", "ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5 ORS", "protein_info = []#np.empty([len(RAS)+len(RAF),2]) for i in range(len(RAS)): protein_info.append((RAS[i].resid,'RAS-ONLY')) for i", "0: RAF = u.select_atoms('segid '+rasraf_segids[0]+' and '+str(tag)) else: RAF =", "mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures = Naming.dir_res('structures') # #RAS_ONLY_macrostate =", "RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#') # #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate", "THE SELECTION OF THE RAF LOOP RESIDUES ABOVE #################### diff", "OR RAS-RAF) ######## # # if len(kras_indices) == 1: #", "once ######### # CS, for x4 cases: # [{protein_x4: (protein_type,", "my edits to test # RAS_ONLY_macrostate = np.loadtxt('ras-states.txt') # RAS_RAF_macrostate", "from logging import getLogger LOGGER = getLogger(__name__) # # Innitilize", "and whether it is 'RAS-ONLY', or 'RAS-RAF'.\\ The 'tag' input", "# else: # # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name", "u.select_atoms('resname POPC PAPC POPE DIPE SSM PAPS SAPI CHL1') coords", "and (name CA or name BB)') ############### NEED TO CONFIRM", "#diff0.append([((RAS_ONLY_macrostate[i,0]-OWAS[j])**2+(RAS_ONLY_macrostate[i,1]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,6]]) diff0.append([((RAS_ONLY_macrostate[i,1]-OWAS[j])**2+(RAS_ONLY_macrostate[i,0]-OROT[j])**2)**0.5, RAS_ONLY_macrostate[i,5]]) diff0.sort() states[j] = diff0[0][1] elif protein_type", "BB)') krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+'", "Naming.dir_res('structures') # #RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-ONLY.microstates.txt\")) RAS_ONLY_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-states.txt\"),comments='#')", "########## Below is taken out of the function so it", "'ras': ('RAS-ONLY', 184), 'rasraf': ('RAS-RAF', 320)}] ALLOUT = [] for", "axis=1) ORS_norm = (((ORS_tp[:, 3]-ORS_tp[:, 0])**2)+((ORS_tp[:, 4]-ORS_tp[:, 1])**2)+((ORS_tp[:, 5]-ORS_tp[:, 2])**2))**0.5", "kras_ref_universe = mda.Universe(os.path.join(dirKRASStructures, \"RAS-ONLY-reference-structure.gro\")) # kras_ref_universe = mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe", "u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)) krases0_BB.guess_bonds() r2_26r40_56r69_166 = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+24)+' ' +\\ str(start_of_g+38)+':'+str(start_of_g+54)+'", "# def get_kras(syst, kras_start): # \"\"\"Gets all atoms for a", "u.select_atoms('resid '+str(start_of_g+zshifting+291)+':'+str(start_of_g+zshifting+294)+' ' +\\ str(start_of_g+zshifting+278)+':'+str(start_of_g+zshifting+281)+' ' +\\ ' and (name", "== 'RAS': ras_segids.append(segs[i]) if segs[i][-3:] == 'RAF': rasraf_segids.append(segs[i]) return ras_segids,", "out of the function so it is only done once", "0]**2)+(RotMatNP[:, 2, 1]**2)+(RotMatNP[:, 2, 2]**2))**0.5)[:, None] OWAS = np.arccos(RotMatNP[:, 2,", "elif protein_type == 'RAS-RAF': # num_res = RAS_RAF_num_res # ##########", "and RAS-RAF ########## ####### This can be removed # def", "= u.select_atoms('resid '+str(start_of_g)+':'+str(kras_indices[k+1][0])+' and name BB') # ########## ABOVE SECTION", "for j in range(len(OROT)): ### below: adding in the requirements", "'RAS-RAF': z_pos = [] ############### NEED TO CONFIRM THE SELECTION", "output, deleting this four_states will shift that to index 4", "in range(len(OROT)): OUTPUT[i] = str(protein_type), timeframes[i], OWAS[i], OROT[i], z_pos[i], int(states[i])", "only done once ######### # kras_indices = get_protein_info(u,'resname ACE1 and", "KRAS struct. Only called x1 time when class is loaded\"\"\"", "AA lipid names ######## # lipids = u.select_atoms('resname POPX POPC", "< 0: OROT[i] = -(OROT[i]) for i in range(len(OROT)): if", "= (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff)", "handle x4 protein types # --------------------------------------- # ALLOUT = []", "= -1 elif protein_x4 == 'ras4araf': zshifting = 0 else:", "removed def get_segids(u): \"\"\"Identifies the list of segments within the", "i in range(len(ORS)): OROTNOTSIGNED[i] = np.arccos(np.dot(OZPACB[i, :], ORS[i, :]) /", "Z_unit-OZCA OZPACB = Z_OZCA/((Z_OZCA[:, 0]**2+Z_OZCA[:, 1]**2+Z_OZCA[:, 2]**2)**0.5)[:, None] OROTNOTSIGNED =", "0, 1]) Z_unit = Z_unit*Z_adjust Z_OZCA = Z_unit-OZCA OZPACB =", "if protein_type == 'RAS-ONLY': states = np.zeros(len(OROT)) for j in", "the selection below, which can be used for the make_whole...", "align.rotation_matrix(mobile0, ref0) ######## TODO: TSC, Adjusted for AA lipid names", "NEW output details.... ###################################### if protein_type == 'RAS-ONLY': OUTPUT =", "or name BB)' mobile0 = u.select_atoms(str(u_selection)).positions - u.select_atoms(str(u_selection)).center_of_mass() # TODO:", "tilt remains positive for i in range(len(OROT)): if OROT[i] <", "once) ref0 = get_ref_kras() def getKRASstates(u,kras_indices): \"\"\"Gets states for all", "(lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0: diff = diff+(u.dimensions[2]/10) z_pos.append(diff) z_pos", "remains positive for i in range(len(OROT)): if OROT[i] < 0:", "PBC REMOVAL ############## # # ########## Below hard codes the", "\"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') # Note diffrent number of", "BB)') timeframes = [] # TODO: CS, for AA need", "###### Above might have to be updated to take into", "''' *** for AA, need to bring that back on", "(OA - OZPACBCRS)**2 OFORSIGN = OFORSIGN_temp[:, 0]+OFORSIGN_temp[:, 1]+OFORSIGN_temp[:, 2] OROT", "make them as an init mummi_core.init() dirKRASStates = Naming.dir_res('states') dirKRASStructures", "mobile0 # TSC removed this R, RMSD_junk = align.rotation_matrix(mobile0, ref0)", "mda from MDAnalysis.analysis import align from MDAnalysis.lib.mdamath import make_whole import", "time\"\"\" ras_segids, rasraf_segids = get_segids(u) if len(ras_segids) > 0: RAS", "= OZPACBCRS_cross/((OZPACBCRS_cross[:, 0]**2+OZPACBCRS_cross[:, 1]**2+OZPACBCRS_cross[:, 2]**2)**0.5)[:, None] OFORSIGN_temp = (OA -", "= u.segments segs = segs.segids ras_segids = [] rasraf_segids =", "'RAS-ONLY': states = np.zeros(len(OROT)) for j in range(len(OROT)): diff0 =", "ABOVE #################### diff = (lipids.center_of_mass()[2]-raf_loops_selection.center_of_mass(unwrap=True)[2])/10 if diff < 0: diff", "###################### ###### Updated - Added in the protein 'tag', i.e.", "change below # TODO: CS, my edits to test #", "check. #make_whole(krases0_BB) j, rmsd_junk = mda.analysis.align.rotation_matrix((r2_26r40_56r69_166.positions-r2_26r40_56r69_166.center_of_mass()), coords) RotMat.append(j) OS.append(r65_74.center_of_mass()-r152_165.center_of_mass()) timeframes.append(u.trajectory.time)", "it is only done once ######### # CS, for x4", "== 'RAS-RAF': # num_res = RAS_RAF_num_res # ########## Above hard", "for the make_whole... # krases0_BB = u.select_atoms('resid '+str(start_of_g)+':'+str(start_of_g+num_res)+' and (name", "diff0.append([((RAS_RAF_macrostate[i,1]-OWAS[j])**2+(RAS_RAF_macrostate[i,0]-OROT[j])**2)**0.5, RAS_RAF_macrostate[i,4]]) diff0.sort() states[j] = diff0[0][1] ###### Above might have", "###### Below might have to be updated to take into", "get_kras(syst, kras_start): # \"\"\"Gets all atoms for a KRAS protein", "2][:, None] Z_unit = np.full([len(OZCA), 3], 1) Z_adjust = np.array([0,", "index 4 ####### # four_states = np.zeros(len(OROT)) # for j", "and name BB'.\\ Only needs to be called x1 time\"\"\"", "# #RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"RAS-RAF.microstates.txt\")) RAS_RAF_macrostate = np.loadtxt(os.path.join(dirKRASStates, \"ras-raf-states.txt\"),comments='#') #", "REDO WITH A 'HARD-CODED' NUMBER OF RESIDUES PER PROTEIN GROUP", "######### # kras_indices = get_protein_info(u,'resname ACE1 and name BB') ##########", "and <NAME>. this was commented out - please check. #make_whole(krases0_BB)", "= mda.Universe(\"RAS-ONLY-reference-structure.gro\") # kras_ref_universe = mda.Universe('AA_pfpatch_000000004641_RAS_RAF2_411.gro') # TODO: CS, not", "the RAS-ONLY and RAS-RAF simulations ######################### # --------------------------------------- # TODO:", "> 4.8: states[j] = 3 else: ### above: adding in", "protein_info.append((RAF[i].resid,'RAS-RAF')) ######## sort protein info protein_info = sorted(protein_info) ######## sort", "= np.cross(OA, ORS) OZCA = OA * OA[:, 2][:, None]" ]
[ "to your config/configuration.yaml switch: platform: hikvisioncam name: Hikvision Cam 1", "switch you will need to add something like the following", "self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update Motion Detection state \"\"\" enabled", "def should_poll(self): \"\"\" Poll for status regularly. \"\"\" return True", "the name of the device if any. \"\"\" return self._name", "def is_on(self): \"\"\" True if device is on. \"\"\" return", "host *Required This is the IP address of your Hikvision", "Returns the name of the device if any. \"\"\" return", "on Hikvision cameras. Note: Currently works using default https port", "config.get('name', \"Hikvision Camera Motion Detection\") username = config.get(CONF_USERNAME, \"admin\") password", "dependency?\")) return False try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username,", "= config.get('name', \"Hikvision Camera Motion Detection\") username = config.get(CONF_USERNAME, \"admin\")", "the following to your config/configuration.yaml switch: platform: hikvisioncam name: Hikvision", "import HikvisionError, MissingParamError except ImportError: hikvision.api = None _LOGGING =", "= config.get(CONF_HOST, None) port = config.get('port', \"80\") name = config.get('name',", "return False except HikvisionError as conn_err: _LOGGING.error(\"Unable to connect: %s\",", "password: <PASSWORD> Variables: host *Required This is the IP address", "REQUIREMENTS = ['hikvision==0.4'] # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def", "name, hikvision_cam): self._name = name self._hikvision_cam = hikvision_cam self._state =", "*Required This is the IP address of your Hikvision camera.", "CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion", "= config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is", "def turn_off(self, **kwargs): \"\"\" Turn the device off. \"\"\" _LOGGING.info(\"Turning", "\"\"\" Provides a switch to toggle on/off motion detection. \"\"\"", "name = config.get('name', \"Hikvision Camera Motion Detection\") username = config.get(CONF_USERNAME,", "\"\"\" return self._state == STATE_ON def turn_on(self, **kwargs): \"\"\" Turn", "to toggle on/off motion detection. \"\"\" def __init__(self, name, hikvision_cam):", "Detection state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state", "from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.const import CONF_HOST, CONF_USERNAME,", "device on. \"\"\" _LOGGING.info(\"Turning on Motion Detection \") self._hikvision_cam.enable_motion_detection() def", "CONF_USERNAME, CONF_PASSWORD import logging try: import hikvision.api from hikvision.error import", "turning on/off motion detection on Hikvision cameras. Note: Currently works", "return self._state == STATE_ON def turn_on(self, **kwargs): \"\"\" Turn the", "Hikvision motion detection switch you will need to add something", "\"\"\" Setup Hikvision Camera config. \"\"\" host = config.get(CONF_HOST, None)", "self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state = STATE_ON if enabled else", "homeassistant.components.switch.hikvision ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support turning on/off motion detection on Hikvision cameras.", "port=port, username=username, password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error(\"Missing required", "try: import hikvision.api from hikvision.error import HikvisionError, MissingParamError except ImportError:", "Cam 1 Motion Detection host: 192.168.1.32 username: YOUR_USERNAME password: <PASSWORD>", "conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\"", "the state of the device if any. \"\"\" return self._state", "works using default https port only. CGI API Guide: http://bit.ly/1RuyUuF", "if any. \"\"\" return self._name @property def state(self): \"\"\" Returns", "not install the \" \"'hikvision' dependency?\")) return False try: hikvision_cam", "username: YOUR_USERNAME password: <PASSWORD> Variables: host *Required This is the", "status regularly. \"\"\" return True @property def name(self): \"\"\" Returns", "STATE_ON def turn_on(self, **kwargs): \"\"\" Turn the device on. \"\"\"", "config/configuration.yaml switch: platform: hikvisioncam name: Hikvision Cam 1 Motion Detection", "install the \" \"'hikvision' dependency?\")) return False try: hikvision_cam =", "http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion detection switch you", "except HikvisionError as conn_err: _LOGGING.error(\"Unable to connect: %s\", conn_err) return", "add something like the following to your config/configuration.yaml switch: platform:", "motion detection. \"\"\" def __init__(self, name, hikvision_cam): self._name = name", "name *Optional The name to use when displaying this switch", "config.get('port', \"80\") name = config.get('name', \"Hikvision Camera Motion Detection\") username", "\"\"\" return True @property def name(self): \"\"\" Returns the name", "camera username. password *<PASSWORD> <PASSWORD>. name *Optional The name to", "https port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use", "following to your config/configuration.yaml switch: platform: hikvisioncam name: Hikvision Cam", "@property def name(self): \"\"\" Returns the name of the device", "CONF_PASSWORD import logging try: import hikvision.api from hikvision.error import HikvisionError,", "Detection \") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update Motion Detection state", "to connect: %s\", conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ])", "%s\", param_err) return False except HikvisionError as conn_err: _LOGGING.error(\"Unable to", "_LOGGING.error(\"Unable to connect: %s\", conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam)", "False try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False)", "_LOGGING = logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] # pylint: disable=too-many-arguments #", "port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use the", "STATE_OFF from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging try:", "homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging try: import hikvision.api", "turn_on(self, **kwargs): \"\"\" Turn the device on. \"\"\" _LOGGING.info(\"Turning on", "]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch to toggle on/off", "as param_err: _LOGGING.error(\"Missing required param: %s\", param_err) return False except", "\"\"\" homeassistant.components.switch.hikvision ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support turning on/off motion detection on Hikvision", "your Hikvision camera. Example: 192.168.1.32 username *Required Your Hikvision camera", "to use when displaying this switch instance. \"\"\" from homeassistant.helpers.entity", "API Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion detection", "Turn the device off. \"\"\" _LOGGING.info(\"Turning off Motion Detection \")", "Motion Detection state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled)", "Hikvision camera. Example: 192.168.1.32 username *Required Your Hikvision camera username.", "Did you maybe not install the \" \"'hikvision' dependency?\")) return", "detection switch you will need to add something like the", "True @property def name(self): \"\"\" Returns the name of the", "you will need to add something like the following to", "\"\"\" Turn the device on. \"\"\" _LOGGING.info(\"Turning on Motion Detection", "on Motion Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\" Turn", "using default https port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration:", "if device is on. \"\"\" return self._state == STATE_ON def", "_LOGGING.info(\"Turning on Motion Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\"", "Motion Detection host: 192.168.1.32 username: YOUR_USERNAME password: <PASSWORD> Variables: host", "detection on Hikvision cameras. Note: Currently works using default https", "discovery_info=None): \"\"\" Setup Hikvision Camera config. \"\"\" host = config.get(CONF_HOST,", "192.168.1.32 username *Required Your Hikvision camera username. password *<PASSWORD> <PASSWORD>.", "to add something like the following to your config/configuration.yaml switch:", "param_err) return False except HikvisionError as conn_err: _LOGGING.error(\"Unable to connect:", "name of the device if any. \"\"\" return self._name @property", "config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is None:", "regularly. \"\"\" return True @property def name(self): \"\"\" Returns the", "switch: platform: hikvisioncam name: Hikvision Cam 1 Motion Detection host:", "return self._state @property def is_on(self): \"\"\" True if device is", "to import hikvision. Did you maybe not install the \"", "Returns the state of the device if any. \"\"\" return", "**kwargs): \"\"\" Turn the device off. \"\"\" _LOGGING.info(\"Turning off Motion", "the \" \"'hikvision' dependency?\")) return False try: hikvision_cam = hikvision.api.CreateDevice(", "ImportError: hikvision.api = None _LOGGING = logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4']", "# pylint: disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\" Setup", "device if any. \"\"\" return self._name @property def state(self): \"\"\"", "config.get(CONF_HOST, None) port = config.get('port', \"80\") name = config.get('name', \"Hikvision", "\") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\" Turn the device off.", "_LOGGING.error(\"Missing required param: %s\", param_err) return False except HikvisionError as", "@property def state(self): \"\"\" Returns the state of the device", "the device if any. \"\"\" return self._state @property def is_on(self):", "STATE_ON, STATE_OFF from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging", "pylint: disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision", "hikvision_cam): self._name = name self._hikvision_cam = hikvision_cam self._state = STATE_OFF", "connect: %s\", conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class", "self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property def should_poll(self): \"\"\"", "disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision Camera", "HikvisionError as conn_err: _LOGGING.error(\"Unable to connect: %s\", conn_err) return False", "host = config.get(CONF_HOST, None) port = config.get('port', \"80\") name =", "Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision motion detection switch", "Poll for status regularly. \"\"\" return True @property def name(self):", "motion detection on Hikvision cameras. Note: Currently works using default", "password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is None: _LOGGING.error(( \"Failed", "homeassistant.const import STATE_ON, STATE_OFF from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD", "HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch to", "host, port=port, username=username, password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error(\"Missing", "username = config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api", "except ImportError: hikvision.api = None _LOGGING = logging.getLogger(__name__) REQUIREMENTS =", "HikvisionError, MissingParamError except ImportError: hikvision.api = None _LOGGING = logging.getLogger(__name__)", "Hikvision camera username. password *<PASSWORD> <PASSWORD>. name *Optional The name", "def update(self): \"\"\" Update Motion Detection state \"\"\" enabled =", "logging try: import hikvision.api from hikvision.error import HikvisionError, MissingParamError except", "state of the device if any. \"\"\" return self._state @property", "return True @property def name(self): \"\"\" Returns the name of", "\"\"\" Turn the device off. \"\"\" _LOGGING.info(\"Turning off Motion Detection", "only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To use the Hikvision", "from hikvision.error import HikvisionError, MissingParamError except ImportError: hikvision.api = None", "\"'hikvision' dependency?\")) return False try: hikvision_cam = hikvision.api.CreateDevice( host, port=port,", "use when displaying this switch instance. \"\"\" from homeassistant.helpers.entity import", "homeassistant.helpers.entity import ToggleEntity from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.const", "motion detection switch you will need to add something like", "off. \"\"\" _LOGGING.info(\"Turning off Motion Detection \") self._hikvision_cam.disable_motion_detection() def update(self):", "any. \"\"\" return self._state @property def is_on(self): \"\"\" True if", "*Optional The name to use when displaying this switch instance.", "on. \"\"\" return self._state == STATE_ON def turn_on(self, **kwargs): \"\"\"", "\"Failed to import hikvision. Did you maybe not install the", "is on. \"\"\" return self._state == STATE_ON def turn_on(self, **kwargs):", "\"\"\" return self._name @property def state(self): \"\"\" Returns the state", "disable=too-many-arguments # pylint: disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\"", "config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is None: _LOGGING.error(( \"Failed to import", "= name self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property def", "like the following to your config/configuration.yaml switch: platform: hikvisioncam name:", "the device off. \"\"\" _LOGGING.info(\"Turning off Motion Detection \") self._hikvision_cam.disable_motion_detection()", "\"\"\" Poll for status regularly. \"\"\" return True @property def", "1 Motion Detection host: 192.168.1.32 username: YOUR_USERNAME password: <PASSWORD> Variables:", "__init__(self, name, hikvision_cam): self._name = name self._hikvision_cam = hikvision_cam self._state", "Hikvision Camera config. \"\"\" host = config.get(CONF_HOST, None) port =", "is None: _LOGGING.error(( \"Failed to import hikvision. Did you maybe", "Note: Currently works using default https port only. CGI API", "name to use when displaying this switch instance. \"\"\" from", "\"\"\" Update Motion Detection state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled:", "hikvisioncam name: Hikvision Cam 1 Motion Detection host: 192.168.1.32 username:", "maybe not install the \" \"'hikvision' dependency?\")) return False try:", "hikvision_cam self._state = STATE_OFF @property def should_poll(self): \"\"\" Poll for", "_LOGGING.error(( \"Failed to import hikvision. Did you maybe not install", "config. \"\"\" host = config.get(CONF_HOST, None) port = config.get('port', \"80\")", "host: 192.168.1.32 username: YOUR_USERNAME password: <PASSWORD> Variables: host *Required This", "import hikvision.api from hikvision.error import HikvisionError, MissingParamError except ImportError: hikvision.api", "\"\"\" return self._state @property def is_on(self): \"\"\" True if device", "This is the IP address of your Hikvision camera. Example:", "\"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state = STATE_ON", "\"\"\" from homeassistant.helpers.entity import ToggleEntity from homeassistant.const import STATE_ON, STATE_OFF", "is_https=False) except MissingParamError as param_err: _LOGGING.error(\"Missing required param: %s\", param_err)", "Camera config. \"\"\" host = config.get(CONF_HOST, None) port = config.get('port',", "logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes", "device is on. \"\"\" return self._state == STATE_ON def turn_on(self,", "password *<PASSWORD> <PASSWORD>. name *Optional The name to use when", "platform: hikvisioncam name: Hikvision Cam 1 Motion Detection host: 192.168.1.32", "will need to add something like the following to your", "config, add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision Camera config. \"\"\" host", "on/off motion detection on Hikvision cameras. Note: Currently works using", "state(self): \"\"\" Returns the state of the device if any.", "STATE_OFF @property def should_poll(self): \"\"\" Poll for status regularly. \"\"\"", "off Motion Detection \") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update Motion", "= self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state = STATE_ON if enabled", "\"\"\" def __init__(self, name, hikvision_cam): self._name = name self._hikvision_cam =", "default https port only. CGI API Guide: http://bit.ly/1RuyUuF Configuration: To", "Motion Detection\") username = config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\")", "add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch", "\"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is None: _LOGGING.error((", "hikvision.api is None: _LOGGING.error(( \"Failed to import hikvision. Did you", "you maybe not install the \" \"'hikvision' dependency?\")) return False", "def __init__(self, name, hikvision_cam): self._name = name self._hikvision_cam = hikvision_cam", "conn_err: _LOGGING.error(\"Unable to connect: %s\", conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name,", "*<PASSWORD> <PASSWORD>. name *Optional The name to use when displaying", "return self._name @property def state(self): \"\"\" Returns the state of", "MissingParamError except ImportError: hikvision.api = None _LOGGING = logging.getLogger(__name__) REQUIREMENTS", "*Required Your Hikvision camera username. password *<PASSWORD> <PASSWORD>. name *Optional", "device off. \"\"\" _LOGGING.info(\"Turning off Motion Detection \") self._hikvision_cam.disable_motion_detection() def", "self._state == STATE_ON def turn_on(self, **kwargs): \"\"\" Turn the device", "on/off motion detection. \"\"\" def __init__(self, name, hikvision_cam): self._name =", "['hikvision==0.4'] # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def setup_platform(hass, config,", "_LOGGING.info('enabled: %s', enabled) self._state = STATE_ON if enabled else STATE_OFF", "port = config.get('port', \"80\") name = config.get('name', \"Hikvision Camera Motion", "None: _LOGGING.error(( \"Failed to import hikvision. Did you maybe not", "Update Motion Detection state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s',", "enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state = STATE_ON if", "camera. Example: 192.168.1.32 username *Required Your Hikvision camera username. password", "username *Required Your Hikvision camera username. password *<PASSWORD> <PASSWORD>. name", "import STATE_ON, STATE_OFF from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import", "Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\" Turn the device", "displaying this switch instance. \"\"\" from homeassistant.helpers.entity import ToggleEntity from", "required param: %s\", param_err) return False except HikvisionError as conn_err:", "switch to toggle on/off motion detection. \"\"\" def __init__(self, name,", "<PASSWORD>. name *Optional The name to use when displaying this", "import hikvision. Did you maybe not install the \" \"'hikvision'", "except MissingParamError as param_err: _LOGGING.error(\"Missing required param: %s\", param_err) return", "= logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] # pylint: disable=too-many-arguments # pylint:", "name(self): \"\"\" Returns the name of the device if any.", "Camera Motion Detection\") username = config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD,", "device if any. \"\"\" return self._state @property def is_on(self): \"\"\"", "if hikvision.api is None: _LOGGING.error(( \"Failed to import hikvision. Did", "hikvision. Did you maybe not install the \" \"'hikvision' dependency?\"))", "192.168.1.32 username: YOUR_USERNAME password: <PASSWORD> Variables: host *Required This is", "None) port = config.get('port', \"80\") name = config.get('name', \"Hikvision Camera", "To use the Hikvision motion detection switch you will need", "IP address of your Hikvision camera. Example: 192.168.1.32 username *Required", "self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\" Turn the device off. \"\"\"", "param: %s\", param_err) return False except HikvisionError as conn_err: _LOGGING.error(\"Unable", "= config.get('port', \"80\") name = config.get('name', \"Hikvision Camera Motion Detection\")", "def setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision Camera config.", "toggle on/off motion detection. \"\"\" def __init__(self, name, hikvision_cam): self._name", "turn_off(self, **kwargs): \"\"\" Turn the device off. \"\"\" _LOGGING.info(\"Turning off", "Detection host: 192.168.1.32 username: YOUR_USERNAME password: <PASSWORD> Variables: host *Required", "use the Hikvision motion detection switch you will need to", "hikvision.error import HikvisionError, MissingParamError except ImportError: hikvision.api = None _LOGGING", "hikvision.api = None _LOGGING = logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] #", "def turn_on(self, **kwargs): \"\"\" Turn the device on. \"\"\" _LOGGING.info(\"Turning", "False except HikvisionError as conn_err: _LOGGING.error(\"Unable to connect: %s\", conn_err)", "from homeassistant.helpers.entity import ToggleEntity from homeassistant.const import STATE_ON, STATE_OFF from", "state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info('enabled: %s', enabled) self._state =", "Currently works using default https port only. CGI API Guide:", "setup_platform(hass, config, add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision Camera config. \"\"\"", "import ToggleEntity from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.const import", "import logging try: import hikvision.api from hikvision.error import HikvisionError, MissingParamError", "hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch to toggle", "Configuration: To use the Hikvision motion detection switch you will", "need to add something like the following to your config/configuration.yaml", "as conn_err: _LOGGING.error(\"Unable to connect: %s\", conn_err) return False add_devices_callback([", "self._name = name self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property", "= STATE_OFF @property def should_poll(self): \"\"\" Poll for status regularly.", "Hikvision Cam 1 Motion Detection host: 192.168.1.32 username: YOUR_USERNAME password:", "\"<PASSWORD>\") if hikvision.api is None: _LOGGING.error(( \"Failed to import hikvision.", "<PASSWORD> Variables: host *Required This is the IP address of", "def name(self): \"\"\" Returns the name of the device if", "when displaying this switch instance. \"\"\" from homeassistant.helpers.entity import ToggleEntity", "True if device is on. \"\"\" return self._state == STATE_ON", "\"\"\" host = config.get(CONF_HOST, None) port = config.get('port', \"80\") name", "the device if any. \"\"\" return self._name @property def state(self):", "add_devices_callback, discovery_info=None): \"\"\" Setup Hikvision Camera config. \"\"\" host =", "Your Hikvision camera username. password *<PASSWORD> <PASSWORD>. name *Optional The", "Example: 192.168.1.32 username *Required Your Hikvision camera username. password *<PASSWORD>", "ToggleEntity from homeassistant.const import STATE_ON, STATE_OFF from homeassistant.const import CONF_HOST,", "a switch to toggle on/off motion detection. \"\"\" def __init__(self,", "None _LOGGING = logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] # pylint: disable=too-many-arguments", "= ['hikvision==0.4'] # pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def setup_platform(hass,", "detection. \"\"\" def __init__(self, name, hikvision_cam): self._name = name self._hikvision_cam", "# pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback,", "\"80\") name = config.get('name', \"Hikvision Camera Motion Detection\") username =", "Variables: host *Required This is the IP address of your", "\"\"\" _LOGGING.info(\"Turning off Motion Detection \") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\"", "for status regularly. \"\"\" return True @property def name(self): \"\"\"", "any. \"\"\" return self._name @property def state(self): \"\"\" Returns the", "= None _LOGGING = logging.getLogger(__name__) REQUIREMENTS = ['hikvision==0.4'] # pylint:", "of the device if any. \"\"\" return self._state @property def", "= config.get(CONF_PASSWORD, \"<PASSWORD>\") if hikvision.api is None: _LOGGING.error(( \"Failed to", "\"\"\" Returns the state of the device if any. \"\"\"", "HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch to toggle on/off motion detection.", "\"\"\" _LOGGING.info(\"Turning on Motion Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs):", "username=username, password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error(\"Missing required param:", "return False try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password,", "Motion Detection \") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update Motion Detection", "your config/configuration.yaml switch: platform: hikvisioncam name: Hikvision Cam 1 Motion", "address of your Hikvision camera. Example: 192.168.1.32 username *Required Your", "Hikvision cameras. Note: Currently works using default https port only.", "param_err: _LOGGING.error(\"Missing required param: %s\", param_err) return False except HikvisionError", "instance. \"\"\" from homeassistant.helpers.entity import ToggleEntity from homeassistant.const import STATE_ON,", "Provides a switch to toggle on/off motion detection. \"\"\" def", "self._state @property def is_on(self): \"\"\" True if device is on.", "if any. \"\"\" return self._state @property def is_on(self): \"\"\" True", "\"\"\" Returns the name of the device if any. \"\"\"", "Support turning on/off motion detection on Hikvision cameras. Note: Currently", "Detection\") username = config.get(CONF_USERNAME, \"admin\") password = config.get(CONF_PASSWORD, \"<PASSWORD>\") if", "try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except", "username. password *<PASSWORD> <PASSWORD>. name *Optional The name to use", "class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a switch to toggle on/off motion", "is_on(self): \"\"\" True if device is on. \"\"\" return self._state", "should_poll(self): \"\"\" Poll for status regularly. \"\"\" return True @property", "Turn the device on. \"\"\" _LOGGING.info(\"Turning on Motion Detection \")", "import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging try: import hikvision.api from", "_LOGGING.info(\"Turning off Motion Detection \") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update", "update(self): \"\"\" Update Motion Detection state \"\"\" enabled = self._hikvision_cam.is_motion_detection_enabled()", "self._state = STATE_OFF @property def should_poll(self): \"\"\" Poll for status", "on. \"\"\" _LOGGING.info(\"Turning on Motion Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self,", "def state(self): \"\"\" Returns the state of the device if", "Setup Hikvision Camera config. \"\"\" host = config.get(CONF_HOST, None) port", "self._name @property def state(self): \"\"\" Returns the state of the", "CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging try: import hikvision.api from hikvision.error", "of the device if any. \"\"\" return self._name @property def", "the Hikvision motion detection switch you will need to add", "of your Hikvision camera. Example: 192.168.1.32 username *Required Your Hikvision", "False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides a", "name self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property def should_poll(self):", "this switch instance. \"\"\" from homeassistant.helpers.entity import ToggleEntity from homeassistant.const", "something like the following to your config/configuration.yaml switch: platform: hikvisioncam", "return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity): \"\"\" Provides", "%s\", conn_err) return False add_devices_callback([ HikvisionMotionSwitch(name, hikvision_cam) ]) class HikvisionMotionSwitch(ToggleEntity):", "Motion Detection \") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): \"\"\" Turn the", "from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD import logging try: import", "hikvision.api from hikvision.error import HikvisionError, MissingParamError except ImportError: hikvision.api =", "is the IP address of your Hikvision camera. Example: 192.168.1.32", "switch instance. \"\"\" from homeassistant.helpers.entity import ToggleEntity from homeassistant.const import", "= hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except MissingParamError as", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support turning on/off motion detection on Hikvision cameras. Note:", "hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except MissingParamError", "password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error(\"Missing required param: %s\",", "the device on. \"\"\" _LOGGING.info(\"Turning on Motion Detection \") self._hikvision_cam.enable_motion_detection()", "MissingParamError as param_err: _LOGGING.error(\"Missing required param: %s\", param_err) return False", "hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except MissingParamError as param_err:", "\"Hikvision Camera Motion Detection\") username = config.get(CONF_USERNAME, \"admin\") password =", "name: Hikvision Cam 1 Motion Detection host: 192.168.1.32 username: YOUR_USERNAME", "@property def should_poll(self): \"\"\" Poll for status regularly. \"\"\" return", "\" \"'hikvision' dependency?\")) return False try: hikvision_cam = hikvision.api.CreateDevice( host,", "= hikvision_cam self._state = STATE_OFF @property def should_poll(self): \"\"\" Poll", "cameras. Note: Currently works using default https port only. CGI", "YOUR_USERNAME password: <PASSWORD> Variables: host *Required This is the IP", "\"\"\" True if device is on. \"\"\" return self._state ==", "== STATE_ON def turn_on(self, **kwargs): \"\"\" Turn the device on.", "pylint: disable=too-many-arguments # pylint: disable=too-many-instance-attributes def setup_platform(hass, config, add_devices_callback, discovery_info=None):", "The name to use when displaying this switch instance. \"\"\"", "**kwargs): \"\"\" Turn the device on. \"\"\" _LOGGING.info(\"Turning on Motion", "@property def is_on(self): \"\"\" True if device is on. \"\"\"", "the IP address of your Hikvision camera. Example: 192.168.1.32 username", "\") self._hikvision_cam.disable_motion_detection() def update(self): \"\"\" Update Motion Detection state \"\"\"" ]
[ "\"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] } }, } } }", "that need to apply term queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build", "FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin for filter definitions that", "[]) ] class ChoicesAggsMixin: \"\"\"A mixin for filter definitions that", "fr\"]}}, ] } }, } } } In this example,", "facet count for the French filter, is done with the", "one that # is relevant to the current choice. \"must\":", "{\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ]", "on English and German so we only count French): {", "return ( [{\"key\": self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}] if value_list", "and German so we only count French): { \"query\": {", "[ {\"key\": self.name, \"fragment\": fragment_map[value]} for value in data.get(self.name, [])", "[\"fr\"]}}, ] } }, } } } This can only", "current field # only the current choice. \"must\": [ clause", "current choice {**data, self.name: [choice_key]} ) ) for clause in", "a simple terms fragment return ( [{\"key\": self.name, \"fragment\": [{\"terms\":", "the parent NestingWrapper with customized filter data. \"\"\" return {", "mixins to easily compose custom FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A", "\"\"\" return { # Create a custom aggregation for each", "the field. \"\"\" return { # Create a custom aggregation", "[{\"key\": self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}] if value_list else []", "the current choice {**data, self.name: [choice_key]} ) ) for clause", "the parent because it should group all queries of fields", "{ \"bool\": { \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\":", "making sure to apply on the current field # only", "queries, *args, **kwargs): \"\"\" Build the aggregations as a set", "path. For example combined filters on availability and languages would", "self.name: [choice_key]} ) ) for clause in kf_pair[\"fragment\"] ] }", "\"must\": [ clause for kf_pair in ( queries + parent.get_query_fragment(", "we only count French): { \"query\": { \"nested\": { \"path\":", "the French filter, is done with the following filter (excluding", "not self.name ] } } } for choice_key, choice_fragment in", "definitions that need to apply term queries.\"\"\" def get_query_fragment(self, data):", "{ # Create a custom aggregation for each possible choice", "parent.get_query_fragment( # override data with only the current choice {**data,", "\"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\",", "}, } } } In this example, computing the facet", "count French): { \"query\": { \"nested\": { \"path\": \"course_runs\", \"query\":", "in kf_pair[\"fragment\"] if kf_pair[\"key\"] is not self.name ] } }", "for value in data.get(self.name, []) ] class ChoicesAggsMixin: \"\"\"A mixin", "\"en\", fr\"]}}, ] } }, } } } In this", "`availability@coming_soon` & `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": {", "self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\" A mixin for filter definitions", "and languages would lead to a query like: { \"query\":", "hardcoded query fragment for each selected value.\"\"\" fragment_map = self.get_fragment_map()", "custom FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin for filter definitions", "kf_pair in queries for clause in kf_pair[\"fragment\"] if kf_pair[\"key\"] is", "The aggregation filter can only be recomputed at the level", "For example combined filters on availability and languages would lead", "the name implies, it's a simple terms fragment return (", "[choice_key]} ) ) for clause in kf_pair[\"fragment\"] ] } }", "French filter, is done with the following filter (excluding the", "on the current filter: we manually add back the only", "by calling the parent NestingWrapper with customized filter data. \"\"\"", "aggregations for a nested field is DIFFICULT because query fragments", "manually add back the only one that # is relevant", "filter on the current filter: we manually add back the", "{\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] } }, }", "to manually add them, making sure to apply on the", "query fragments as term queries for each selected value.\"\"\" value_list", "nested field. The aggregation filter can only be recomputed at", "only be built by calling the parent NestingWrapper with customized", "like: { \"query\": { \"nested\": { \"path\": \"course_runs\", \"query\": {", "the only one that # is relevant to the current", "German so we only count French): { \"query\": { \"nested\":", "queries for clause in kf_pair[\"fragment\"] if kf_pair[\"key\"] is not self.name", "# only the current choice. \"must\": [ clause for kf_pair", "\"\"\"A mixin for filter definitions that need to apply term", "pylint: disable=unused-argument def get_aggs_fragment(self, queries, data, parent, *args, **kwargs): \"\"\"", "we # have to manually add them, making sure to", "can only be built by calling the parent NestingWrapper with", "self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}] if value_list else [] )", "{ \"path\": \"course_runs\", \"query\": { \"bool\": { \"must\": [ {\"range\":", "for clause in kf_pair[\"fragment\"] if kf_pair[\"key\"] is not self.name ]", "\"query\": { \"nested\": { \"path\": \"course_runs\", \"query\": { \"bool\": {", "the current choice. \"must\": choice_fragment + [ clause for kf_pair", "with only the current choice {**data, self.name: [choice_key]} ) )", "] class ChoicesAggsMixin: \"\"\"A mixin for filter definitions that need", "as the name implies, it's a simple terms fragment return", "value in data.get(self.name, []) ] class ChoicesAggsMixin: \"\"\"A mixin for", "choice_key): { \"filter\": { \"bool\": { # Use all the", "one for each possible value of the field. \"\"\" return", "each possible choice for this filter # eg `availability@coming_soon` &", "a nested field is DIFFICULT because query fragments related to", "for choice_key, choice_fragment in self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\" A", "\"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": { \"bool\": { # Use all", "choice_key, choice_fragment in self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\" A mixin", "} }, } } } In this example, computing the", "choice {**data, self.name: [choice_key]} ) ) for clause in kf_pair[\"fragment\"]", "{\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ] } }, } }", "we manually add back the only one that # is", "a nested field. The aggregation filter can only be recomputed", "in self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\" A mixin for filter", "{ \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\",", "parent because it should group all queries of fields nested", "selected value.\"\"\" fragment_map = self.get_fragment_map() return [ {\"key\": self.name, \"fragment\":", "them, making sure to apply on the current field #", "current filter: we manually add back the only one that", "} } In this example, computing the facet count for", "example combined filters on availability and languages would lead to", "parent, *args, **kwargs): \"\"\" Computing aggregations for a nested field", "related to a nested field. The aggregation filter can only", "} }, } } } This can only be built", "compose custom FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin for filter", "get_query_fragment(self, data): \"\"\"Build the query fragments as term queries for", "} This can only be built by calling the parent", "queries (the nesting parent is # responsible for excluding the", "the queries related to nested fields so we # have", "clause for kf_pair in queries for clause in kf_pair[\"fragment\"] if", "filter: we manually add back the only one that #", "else [] ) class ChoicesQueryMixin: \"\"\"A mixin for filter definitions", "a custom aggregation for each possible choice for this filter", "name implies, it's a simple terms fragment return ( [{\"key\":", "it should group all queries of fields nested below the", "relevant to the current choice. \"must\": choice_fragment + [ clause", "value_list = data.get(self.name) # For terms filters, as the name", "def get_query_fragment(self, data): \"\"\"Pick the hardcoded query fragment for each", "choices.\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, *args, **kwargs): \"\"\"", "apply aggregations for predefined choices.\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self,", "with the following filter (excluding the filter on English and", "the queries (the nesting parent is # responsible for excluding", "a query like: { \"query\": { \"nested\": { \"path\": \"course_runs\",", "queries related to nested fields so we # have to", "\"\"\"Build the query fragments as term queries for each selected", "kf_pair[\"fragment\"] ] } } } for choice_key, choice_fragment in self.get_fragment_map().items()", "apply on the current field # only the current choice.", "\"bool\": { \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\":", "is # responsible for excluding the queries related to nested", "{\"key\": self.name, \"fragment\": fragment_map[value]} for value in data.get(self.name, []) ]", "# filter on the current filter: we manually add back", "value of the field. \"\"\" return { # Create a", "} } } for choice_key, choice_fragment in self.get_fragment_map().items() } class", "at the level of the parent because it should group", "as a set of filters, one for each possible value", "# Use all the query fragments from the queries (the", "terms fragment return ( [{\"key\": self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}]", "excluding the queries related to nested fields so we #", "languages would lead to a query like: { \"query\": {", "a set of filters, one for each possible value of", "as term queries for each selected value.\"\"\" value_list = data.get(self.name)", "ChoicesAggsMixin: \"\"\"A mixin for filter definitions that need to apply", "self.name ] } } } for choice_key, choice_fragment in self.get_fragment_map().items()", "# override data with only the current choice {**data, self.name:", "parent is # responsible for excluding the queries related to", "[ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] }", "apply term queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build the query fragments", "of the field. \"\"\" return { # Create a custom", "to apply term queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build the query", "built by calling the parent NestingWrapper with customized filter data.", "terms filters, as the name implies, it's a simple terms", "query like: { \"query\": { \"nested\": { \"path\": \"course_runs\", \"query\":", "for kf_pair in queries for clause in kf_pair[\"fragment\"] if kf_pair[\"key\"]", "possible value of the field. \"\"\" return { # Create", "definitions that are related to a nested field. The aggregation", "can only be recomputed at the level of the parent", "for filter definitions that are related to a nested field.", "for clause in kf_pair[\"fragment\"] ] } } } for choice_key,", "{\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ] } }, } } }", "{\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ] } },", "so we only count French): { \"query\": { \"nested\": {", "need to apply aggregations for predefined choices.\"\"\" # pylint: disable=unused-argument", "choice. \"must\": choice_fragment + [ clause for kf_pair in queries", "(the nesting parent is # responsible for excluding the queries", "be built by calling the parent NestingWrapper with customized filter", "nested below the parent. \"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self,", "all queries of fields nested below the parent. \"\"\" #", "only one that # is relevant to the current choice.", "to apply on the current field # only the current", "to nested fields are grouped under their common path. For", "easily compose custom FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin for", "field. The aggregation filter can only be recomputed at the", "queries *but* the one(s) that # filter on the current", "filter definitions that need to apply aggregations for predefined choices.\"\"\"", "in data.get(self.name, []) ] class ChoicesAggsMixin: \"\"\"A mixin for filter", "the aggregations as a set of filters, one for each", "class NestedChoicesAggsMixin: \"\"\" A mixin for filter definitions that are", "( queries + parent.get_query_fragment( # override data with only the", "value_list}}]}] if value_list else [] ) class ChoicesQueryMixin: \"\"\"A mixin", "only the current choice. \"must\": [ clause for kf_pair in", "Build the aggregations as a set of filters, one for", "implies, it's a simple terms fragment return ( [{\"key\": self.name,", "\"path\": \"course_runs\", \"query\": { \"bool\": { \"must\": [ {\"range\": {\"course_runs.end\":", "customized filter data. \"\"\" return { # Create a custom", "have to manually add them, making sure to apply on", "disable=unused-argument def get_aggs_fragment(self, queries, data, parent, *args, **kwargs): \"\"\" Computing", "is relevant to the current choice. \"must\": choice_fragment + [", "nested fields so we # have to manually add them,", "} } } In this example, computing the facet count", "\"must\": choice_fragment + [ clause for kf_pair in queries for", "for predefined choices.\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, *args,", "to apply aggregations for predefined choices.\"\"\" # pylint: disable=unused-argument def", "] } }, } } } In this example, computing", "be recomputed at the level of the parent because it", "for this filter # eg `availability@coming_soon` & `availability@current` & `availability@open`", "French): { \"query\": { \"nested\": { \"path\": \"course_runs\", \"query\": {", "data, parent, *args, **kwargs): \"\"\" Computing aggregations for a nested", "term queries for each selected value.\"\"\" value_list = data.get(self.name) #", "[ clause for kf_pair in queries for clause in kf_pair[\"fragment\"]", "data with only the current choice {**data, self.name: [choice_key]} )", "related to nested fields so we # have to manually", "filters on availability and languages would lead to a query", "class ChoicesQueryMixin: \"\"\"A mixin for filter definitions that need to", "fragment for each selected value.\"\"\" fragment_map = self.get_fragment_map() return [", "pylint: disable=unused-argument def get_aggs_fragment(self, queries, *args, **kwargs): \"\"\" Build the", "\"\"\"A mixin for filter definitions that need to apply aggregations", "data. \"\"\" return { # Create a custom aggregation for", "fragment_map = self.get_fragment_map() return [ {\"key\": self.name, \"fragment\": fragment_map[value]} for", "aggregations as a set of filters, one for each possible", "def get_query_fragment(self, data): \"\"\"Build the query fragments as term queries", "get_query_fragment(self, data): \"\"\"Pick the hardcoded query fragment for each selected", "level of the parent because it should group all queries", "mixin for filter definitions that are related to a nested", "& `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": { \"bool\":", "queries, data, parent, *args, **kwargs): \"\"\" Computing aggregations for a", "{ # Use all the query fragments from the queries", "aggregations for predefined choices.\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries,", "grouped under their common path. For example combined filters on", "\"\"\" Build the aggregations as a set of filters, one", "to easily compose custom FilterDefinition classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin", "are grouped under their common path. For example combined filters", "count for the French filter, is done with the following", "\"bool\": { # Use all the query fragments from the", "fragments related to nested fields are grouped under their common", "*args, **kwargs): \"\"\" Build the aggregations as a set of", "simple terms fragment return ( [{\"key\": self.name, \"fragment\": [{\"terms\": {self.term:", "value.\"\"\" fragment_map = self.get_fragment_map() return [ {\"key\": self.name, \"fragment\": fragment_map[value]}", "\"filter\": { \"bool\": { # Use all the query fragments", "done with the following filter (excluding the filter on English", "disable=unused-argument def get_aggs_fragment(self, queries, *args, **kwargs): \"\"\" Build the aggregations", "set of filters, one for each possible value of the", "only be recomputed at the level of the parent because", ") for clause in kf_pair[\"fragment\"] ] } } } for", "recomputed at the level of the parent because it should", "mixin for filter definitions that need to apply aggregations for", "manually add them, making sure to apply on the current", "for each selected value.\"\"\" fragment_map = self.get_fragment_map() return [ {\"key\":", "queries for each selected value.\"\"\" value_list = data.get(self.name) # For", "\"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ] } }, }", "class TermsQueryMixin: \"\"\"A mixin for filter definitions that need to", "each selected value.\"\"\" value_list = data.get(self.name) # For terms filters,", "# pylint: disable=unused-argument def get_aggs_fragment(self, queries, data, parent, *args, **kwargs):", "filters, one for each possible value of the field. \"\"\"", "definitions that need to apply predefined queries.\"\"\" def get_query_fragment(self, data):", "that # is relevant to the current choice. \"must\": choice_fragment", "{\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] } }, } }", "override data with only the current choice {**data, self.name: [choice_key]}", "{\"course_runs.languages\": [\"fr\"]}}, ] } }, } } } This can", "fragment_map[value]} for value in data.get(self.name, []) ] class ChoicesAggsMixin: \"\"\"A", "\"\"\"Define mixins to easily compose custom FilterDefinition classes.\"\"\" class TermsQueryMixin:", "fields so we # have to manually add them, making", "}, } } } This can only be built by", "# eg `availability@coming_soon` & `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): {", "with customized filter data. \"\"\" return { # Create a", "# have to manually add them, making sure to apply", "In this example, computing the facet count for the French", "Create a custom aggregation for each possible choice for this", "below the parent. \"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries,", "combined filters on availability and languages would lead to a", "mixin for filter definitions that need to apply predefined queries.\"\"\"", "of filters, one for each possible value of the field.", "nested fields are grouped under their common path. For example", "the level of the parent because it should group all", "filter data. \"\"\" return { # Create a custom aggregation", "] } }, } } } This can only be", "[] ) class ChoicesQueryMixin: \"\"\"A mixin for filter definitions that", "the queries *but* the one(s) that # filter on the", "the current field # only the current choice. \"must\": [", "\"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ]", "availability and languages would lead to a query like: {", "clause for kf_pair in ( queries + parent.get_query_fragment( # override", "Computing aggregations for a nested field is DIFFICULT because query", "because it should group all queries of fields nested below", "need to apply term queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build the", "this example, computing the facet count for the French filter,", "} } This can only be built by calling the", "in ( queries + parent.get_query_fragment( # override data with only", "query fragments related to nested fields are grouped under their", "that need to apply aggregations for predefined choices.\"\"\" # pylint:", "for each possible choice for this filter # eg `availability@coming_soon`", "\"\"\" Computing aggregations for a nested field is DIFFICULT because", "} In this example, computing the facet count for the", "to nested fields so we # have to manually add", "[\"de\", \"en\", fr\"]}}, ] } }, } } } In", "\"fragment\": fragment_map[value]} for value in data.get(self.name, []) ] class ChoicesAggsMixin:", "def get_aggs_fragment(self, queries, data, parent, *args, **kwargs): \"\"\" Computing aggregations", "that are related to a nested field. The aggregation filter", "only the current choice {**data, self.name: [choice_key]} ) ) for", ") ) for clause in kf_pair[\"fragment\"] ] } } }", "is done with the following filter (excluding the filter on", "so we # have to manually add them, making sure", "filter (excluding the filter on English and German so we", "choice_fragment + [ clause for kf_pair in queries for clause", "class ChoicesAggsMixin: \"\"\"A mixin for filter definitions that need to", "filters, as the name implies, it's a simple terms fragment", "# pylint: disable=unused-argument def get_aggs_fragment(self, queries, *args, **kwargs): \"\"\" Build", "} } for choice_key, choice_fragment in self.get_fragment_map().items() } class NestedChoicesAggsMixin:", "are related to a nested field. The aggregation filter can", "lead to a query like: { \"query\": { \"nested\": {", "calling the parent NestingWrapper with customized filter data. \"\"\" return", "clause in kf_pair[\"fragment\"] if kf_pair[\"key\"] is not self.name ] }", "term queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build the query fragments as", "DIFFICULT because query fragments related to nested fields are grouped", "= self.get_fragment_map() return [ {\"key\": self.name, \"fragment\": fragment_map[value]} for value", "{\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}}, ] }", "for filter definitions that need to apply term queries.\"\"\" def", "need to apply predefined queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick the", "get_aggs_fragment(self, queries, *args, **kwargs): \"\"\" Build the aggregations as a", "TermsQueryMixin: \"\"\"A mixin for filter definitions that need to apply", "fragments as term queries for each selected value.\"\"\" value_list =", "queries of fields nested below the parent. \"\"\" # pylint:", "definitions that need to apply aggregations for predefined choices.\"\"\" #", "fields nested below the parent. \"\"\" # pylint: disable=unused-argument def", "the hardcoded query fragment for each selected value.\"\"\" fragment_map =", "the facet count for the French filter, is done with", "apply predefined queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick the hardcoded query", "**kwargs): \"\"\" Computing aggregations for a nested field is DIFFICULT", "all the query fragments from the queries (the nesting parent", "field. \"\"\" return { # Create a custom aggregation for", "it's a simple terms fragment return ( [{\"key\": self.name, \"fragment\":", "eg `availability@coming_soon` & `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\":", "data.get(self.name, []) ] class ChoicesAggsMixin: \"\"\"A mixin for filter definitions", "{ \"query\": { \"nested\": { \"path\": \"course_runs\", \"query\": { \"bool\":", "back the only one that # is relevant to the", "} } } This can only be built by calling", "from the queries *but* the one(s) that # filter on", "current choice. \"must\": choice_fragment + [ clause for kf_pair in", "self.get_fragment_map() return [ {\"key\": self.name, \"fragment\": fragment_map[value]} for value in", "on availability and languages would lead to a query like:", "\"\"\" A mixin for filter definitions that are related to", "[{\"terms\": {self.term: value_list}}]}] if value_list else [] ) class ChoicesQueryMixin:", "+ parent.get_query_fragment( # override data with only the current choice", "for each possible value of the field. \"\"\" return {", "sure to apply on the current field # only the", "filter definitions that need to apply term queries.\"\"\" def get_query_fragment(self,", "\"\"\"A mixin for filter definitions that need to apply predefined", "for the French filter, is done with the following filter", "def get_aggs_fragment(self, queries, *args, **kwargs): \"\"\" Build the aggregations as", "fragments from the queries *but* the one(s) that # filter", "**kwargs): \"\"\" Build the aggregations as a set of filters,", "fragment return ( [{\"key\": self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}] if", "queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick the hardcoded query fragment for", "the parent. \"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, data,", "value.\"\"\" value_list = data.get(self.name) # For terms filters, as the", "return { # Create a custom aggregation for each possible", "to the current choice. \"must\": choice_fragment + [ clause for", "filter can only be recomputed at the level of the", "responsible for excluding the queries related to nested fields so", "kf_pair[\"key\"] is not self.name ] } } } for choice_key,", "A mixin for filter definitions that are related to a", "for filter definitions that need to apply predefined queries.\"\"\" def", "for excluding the queries related to nested fields so we", "if kf_pair[\"key\"] is not self.name ] } } } for", "\"\"\"Pick the hardcoded query fragment for each selected value.\"\"\" fragment_map", "{**data, self.name: [choice_key]} ) ) for clause in kf_pair[\"fragment\"] ]", "filter definitions that need to apply predefined queries.\"\"\" def get_query_fragment(self,", "possible choice for this filter # eg `availability@coming_soon` & `availability@current`", "\"query\": { \"bool\": { \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}},", "queries + parent.get_query_fragment( # override data with only the current", "filter # eg `availability@coming_soon` & `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key):", "choice for this filter # eg `availability@coming_soon` & `availability@current` &", "filter on English and German so we only count French):", "current choice. \"must\": [ clause for kf_pair in ( queries", "For terms filters, as the name implies, it's a simple", "{ \"filter\": { \"bool\": { # Use all the query", "query fragments from the queries (the nesting parent is #", "data.get(self.name) # For terms filters, as the name implies, it's", "self.name, \"fragment\": fragment_map[value]} for value in data.get(self.name, []) ] class", "common path. For example combined filters on availability and languages", "custom aggregation for each possible choice for this filter #", "computing the facet count for the French filter, is done", "NestedChoicesAggsMixin: \"\"\" A mixin for filter definitions that are related", "`availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": { \"bool\": {", "\"fragment\": [{\"terms\": {self.term: value_list}}]}] if value_list else [] ) class", "aggregation filter can only be recomputed at the level of", "add them, making sure to apply on the current field", "to apply predefined queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick the hardcoded", "this filter # eg `availability@coming_soon` & `availability@current` & `availability@open` \"{:s}@{:s}\".format(self.name,", "{\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] } },", "from the queries (the nesting parent is # responsible for", "return [ {\"key\": self.name, \"fragment\": fragment_map[value]} for value in data.get(self.name,", "{ \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"fr\"]}},", "filter definitions that are related to a nested field. The", "} class NestedChoicesAggsMixin: \"\"\" A mixin for filter definitions that", "predefined queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick the hardcoded query fragment", "kf_pair[\"fragment\"] if kf_pair[\"key\"] is not self.name ] } } }", "the current choice. \"must\": [ clause for kf_pair in (", "because query fragments related to nested fields are grouped under", "aggregation for each possible choice for this filter # eg", "kf_pair in ( queries + parent.get_query_fragment( # override data with", "in kf_pair[\"fragment\"] ] } } } for choice_key, choice_fragment in", "get_aggs_fragment(self, queries, data, parent, *args, **kwargs): \"\"\" Computing aggregations for", "selected value.\"\"\" value_list = data.get(self.name) # For terms filters, as", "if value_list else [] ) class ChoicesQueryMixin: \"\"\"A mixin for", "& `availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": { \"bool\": { #", "# responsible for excluding the queries related to nested fields", ") class ChoicesQueryMixin: \"\"\"A mixin for filter definitions that need", "predefined choices.\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, *args, **kwargs):", "[ {\"range\": {\"course_runs.end\": {\"lte\": \"01-01-2019\"}}}, {\"terms\": {\"course_runs.languages\": [\"de\", \"en\", fr\"]}},", "related to nested fields are grouped under their common path.", "of fields nested below the parent. \"\"\" # pylint: disable=unused-argument", "nesting parent is # responsible for excluding the queries related", "is not self.name ] } } } for choice_key, choice_fragment", "(excluding the filter on English and German so we only", "{\"terms\": {\"course_runs.languages\": [\"fr\"]}}, ] } }, } } } This", "group all queries of fields nested below the parent. \"\"\"", "for filter definitions that need to apply aggregations for predefined", "parent. \"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, data, parent,", "*but* the one(s) that # filter on the current filter:", "field # only the current choice. \"must\": [ clause for", "+ [ clause for kf_pair in queries for clause in", "following filter (excluding the filter on English and German so", "{self.term: value_list}}]}] if value_list else [] ) class ChoicesQueryMixin: \"\"\"A", "only count French): { \"query\": { \"nested\": { \"path\": \"course_runs\",", "choice. \"must\": [ clause for kf_pair in ( queries +", "would lead to a query like: { \"query\": { \"nested\":", "to a nested field. The aggregation filter can only be", "} for choice_key, choice_fragment in self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\"", "for each selected value.\"\"\" value_list = data.get(self.name) # For terms", "= data.get(self.name) # For terms filters, as the name implies,", "their common path. For example combined filters on availability and", "choice_fragment in self.get_fragment_map().items() } class NestedChoicesAggsMixin: \"\"\" A mixin for", "# Create a custom aggregation for each possible choice for", "the filter on English and German so we only count", "query fragment for each selected value.\"\"\" fragment_map = self.get_fragment_map() return", "This can only be built by calling the parent NestingWrapper", "\"nested\": { \"path\": \"course_runs\", \"query\": { \"bool\": { \"must\": [", "\"\"\" # pylint: disable=unused-argument def get_aggs_fragment(self, queries, data, parent, *args,", "to a query like: { \"query\": { \"nested\": { \"path\":", "data): \"\"\"Build the query fragments as term queries for each", "of the parent because it should group all queries of", "( [{\"key\": self.name, \"fragment\": [{\"terms\": {self.term: value_list}}]}] if value_list else", "in queries for clause in kf_pair[\"fragment\"] if kf_pair[\"key\"] is not", "the query fragments from the queries *but* the one(s) that", "on the current field # only the current choice. \"must\":", "each selected value.\"\"\" fragment_map = self.get_fragment_map() return [ {\"key\": self.name,", "{ \"nested\": { \"path\": \"course_runs\", \"query\": { \"bool\": { \"must\":", "{ \"bool\": { # Use all the query fragments from", "that need to apply predefined queries.\"\"\" def get_query_fragment(self, data): \"\"\"Pick", "NestingWrapper with customized filter data. \"\"\" return { # Create", "# is relevant to the current choice. \"must\": choice_fragment +", "# For terms filters, as the name implies, it's a", "ChoicesQueryMixin: \"\"\"A mixin for filter definitions that need to apply", "all the query fragments from the queries *but* the one(s)", "is DIFFICULT because query fragments related to nested fields are", "] } } } for choice_key, choice_fragment in self.get_fragment_map().items() }", "data): \"\"\"Pick the hardcoded query fragment for each selected value.\"\"\"", "the one(s) that # filter on the current filter: we", "fragments from the queries (the nesting parent is # responsible", "*args, **kwargs): \"\"\" Computing aggregations for a nested field is", "mixin for filter definitions that need to apply term queries.\"\"\"", "fields are grouped under their common path. For example combined", "filter, is done with the following filter (excluding the filter", "clause in kf_pair[\"fragment\"] ] } } } for choice_key, choice_fragment", "add back the only one that # is relevant to", "parent NestingWrapper with customized filter data. \"\"\" return { #", "nested field is DIFFICULT because query fragments related to nested", "query fragments from the queries *but* the one(s) that #", "the following filter (excluding the filter on English and German", "one(s) that # filter on the current filter: we manually", "the current filter: we manually add back the only one", "Use all the query fragments from the queries *but* the", "[ clause for kf_pair in ( queries + parent.get_query_fragment( #", "each possible value of the field. \"\"\" return { #", "for a nested field is DIFFICULT because query fragments related", "for kf_pair in ( queries + parent.get_query_fragment( # override data", "value_list else [] ) class ChoicesQueryMixin: \"\"\"A mixin for filter", "# Use all the query fragments from the queries *but*", "field is DIFFICULT because query fragments related to nested fields", "example, computing the facet count for the French filter, is", "English and German so we only count French): { \"query\":", "Use all the query fragments from the queries (the nesting", "\"course_runs\", \"query\": { \"bool\": { \"must\": [ {\"range\": {\"course_runs.end\": {\"lte\":", "classes.\"\"\" class TermsQueryMixin: \"\"\"A mixin for filter definitions that need", "that # filter on the current filter: we manually add", "queries.\"\"\" def get_query_fragment(self, data): \"\"\"Build the query fragments as term", "under their common path. For example combined filters on availability", "the query fragments from the queries (the nesting parent is", "`availability@open` \"{:s}@{:s}\".format(self.name, choice_key): { \"filter\": { \"bool\": { # Use", "should group all queries of fields nested below the parent.", "the query fragments as term queries for each selected value.\"\"\"" ]
[ "else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to text fields in `_create_receive_form_layout`.", "message) self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri)", "amount')) return def callback(exc_value: Optional[Exception]=None) -> None: if exc_value is", "None: if self._account_id is not None: edit = (self._fiat_receive_e if", "set_form_contents(self, address_text: str, value: int, description: Optional[str]=None, expires_description: str=\"\") ->", "PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import _ from electrumsv.logs import logs", "buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1,", "= QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self) ->", "payment destination.') receive_address_label = HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label,", "if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to text fields", "bool) -> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]: return [", "key_id: int) -> None: self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab()", "self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def _toggle_qr_window(self, event:", "self._receive_key_id is None: return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text()", "set_receive_key_id(self, key_id: int) -> None: self._receive_key_id = key_id def set_receive_key(self,", "request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout)", "request_box.setLayout(layout) return request_box def update_widgets(self) -> None: self._request_list.update() def update_destination(self)", "HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0,", "_toggle_qr_window(self, event: QEvent) -> None: if self._receive_key_id is None: self.show_message(_(\"No", "_('You are using a non-deterministic account, which ' 'cannot create", "self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]: return self._receive_key_id # Only called", "them ' 'a signed payment request.'), _('Expired requests have to", "self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances): if not self._account.is_deterministic(): msg =", "= self.create_form_layout() self._request_list = RequestList(self, main_window) request_container = self.create_request_list_container() vbox", "= QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout) return", "Optional[int]: return self._receive_key_id # Only called from key list menu.", "payment destination where the payment should be received. ' 'Note", "None: self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id:", "else '') if not app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e,", "list, ' 'in order to free the corresponding Bitcoin SV", "_('Expiration date of your request.'), _('This information is seen by", "the recipient if you send them ' 'a signed payment", "import logs from electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv import web", "be a receive QR code object created yet. if self._receive_qr", "set_fiat_ccy_enabled(self, flag: bool) -> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]:", "import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from", "None: super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id = account_id self._account =", "script_template is not None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self)", "amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None)", "self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx else '') if not", "self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button)", "If there are no accounts there won't be a receive", "Bitcoin SV addresses.'), _('The Bitcoin SV address never expires and", "# Only called from key list menu. def receive_at_id(self, key_id:", "Only called from key list menu. def receive_at_id(self, key_id: int)", "addresses.'), _('The Bitcoin SV address never expires and will always", "self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to text fields in `_create_receive_form_layout`. def", "if you send them ' 'a signed payment request.'), _('Expired", "app_state from electrumsv.bitcoin import script_template_to_string from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH", "ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None def", "= EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout()", "(message != \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri", "KeyInstanceRow) -> None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def", "from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import _ from", "self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool) -> None: self._new_request_button.setEnabled(flag) def", "information is seen by the recipient if you send them", "ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None def __init__(self, main_window: 'ElectrumWindow', account_id:", "won't be a receive QR code object created yet. if", "yet. if self._receive_qr is not None: self._receive_qr.clean_up() if self._qr_window is", "import QR_Window from .request_list import RequestList from .table_widgets import TableTopButtonLayout", "if self._qr_window is not None: self._qr_window.close() def create_form_layout(self) -> QHBoxLayout:", "i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([ _('Expiration", "BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e", "layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0,", "if script_template is not None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def", "= AmountEdit(app_state.fx.get_currency if app_state.fx else '') if not app_state.fx or", "different Bitcoin SV payment destination.') receive_address_label = HelpLabel(_('Receiving destination'), msg)", "self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your wallet is broken and could", "ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV payment destination where", "vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self) -> None: # If", "be received. ' 'Note that each payment request uses a", "_('No more payment destinations in your wallet.'), _('You are using", "'in order to free the corresponding Bitcoin SV addresses.'), _('The", "Bitcoin SV address never expires and will always be part", "= QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else: if not self._qr_window.isVisible():", "int, description: Optional[str]=None, expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or", "0, 0) grid.addWidget(self._receive_destination_e, 0, 1, 1, -1) self._receive_message_e = QLineEdit()", "= self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances): if not self._account.is_deterministic(): msg", "None: text = \"\" if self._receive_key_id is not None: script_template", "_update_receive_qr(self) -> None: if self._receive_key_id is None: return amount =", "self._qr_window.close() def create_form_layout(self) -> QHBoxLayout: # A 4-column grid layout.", "_('Expired requests have to be deleted manually from your list,", "-> None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self,", "import web from .amountedit import AmountEdit, BTCAmountEdit from .constants import", "msg = _('Bitcoin SV payment destination where the payment should", "self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2,", "is not None: edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e)", "expiration, message, callback) else: # Expiration is just a label,", "def __init__(self, main_window: 'ElectrumWindow', account_id: int) -> None: super().__init__(main_window) self._main_window", "to text fields in `_create_receive_form_layout`. def _update_receive_qr(self) -> None: if", "get_bsv_edits(self) -> List[BTCAmountEdit]: return [ self._receive_amount_e ] def _save_form_as_request(self) ->", "set_receive_key(self, keyinstance: KeyInstanceRow) -> None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None)", ".constants import expiration_values if TYPE_CHECKING: from .main_window import ElectrumWindow from", "0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter)", "SV payment destination where the payment should be received. '", "vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr)", "if app_state.fx else '') if not app_state.fx or not app_state.fx.is_enabled():", "buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1, 2) vbox_g = QVBoxLayout()", "All the stretch is in the last column. # The", "you want to create new payment destinations, ' 'use a", "is in the last column. # The exchange rate plugin", "from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout,", "1, -1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1,", "logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display)", ".amountedit import AmountEdit, BTCAmountEdit from .constants import expiration_values if TYPE_CHECKING:", "in the last column. # The exchange rate plugin adds", "None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template is not None: text", "Expiration is just a label, so we don't use the", "grid.addWidget(self._expires_combo, 3, 1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label,", "[] if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances):", "is broken and could not allocate a new payment destination.'))", "bool) -> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self, text: str) -> None:", "grid layout. All the stretch is in the last column.", "self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri = web.create_URI(address_text, amount, message) self._receive_qr.setData(uri)", "self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1, 1, 1,", "!= \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri =", "a fiat widget in column 2 grid = QGridLayout() grid.setSpacing(8)", "import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import _ from electrumsv.logs import", "and not amount: self._main_window.show_error(_('No message or amount')) return def callback(exc_value:", "electrumsv.logs import logs from electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv import", "non-deterministic account, which ' 'cannot create new payment destinations.'), _('If", "-> None: self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self,", "class ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None def __init__(self, main_window: 'ElectrumWindow',", "self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons", "Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for i in", "int) -> None: self._receive_key_id = key_id def set_receive_key(self, keyinstance: KeyInstanceRow)", "electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import _ from electrumsv.logs", "and will always be part ' 'of this ElectrumSV wallet.'),", "from .util import ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window]", "from key list menu. def receive_at_id(self, key_id: int) -> None:", "1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx else '') if", "not None: self._qr_window.close() def create_form_layout(self) -> QHBoxLayout: # A 4-column", "row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None: row = self._account.requests.create_request(self._receive_key_id,", "1) self.setLayout(vbox) def clean_up(self) -> None: # If there are", "return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is not", "-1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1, 1,", "not len(keyinstances): if not self._account.is_deterministic(): msg = [ _('No more", "to be deleted manually from your list, ' 'in order", "self._receive_destination_e.setText(text) def update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key", "list menu. def receive_at_id(self, key_id: int) -> None: self._receive_key_id =", "= QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons,", "in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None: row", "key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int) -> None:", "will always be part ' 'of this ElectrumSV wallet.'), ])", "payment destinations, ' 'use a deterministic account instead.') ] self._main_window.show_message('", "None: # If there are no accounts there won't be", "grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e", "The exchange rate plugin adds a fiat widget in column", "not amount: self._main_window.show_error(_('No message or amount')) return def callback(exc_value: Optional[Exception]=None)", "Bitcoin SV payment destination.') receive_address_label = HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr)", "flag: bool) -> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self, text: str) ->", ".qrcodewidget import QRCodeWidget from .qrwindow import QR_Window from .request_list import", "corresponding Bitcoin SV addresses.'), _('The Bitcoin SV address never expires", "super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id = account_id self._account = main_window._wallet.get_account(account_id)", "self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool) -> None: self._new_request_button.setEnabled(flag)", "account_id: int) -> None: super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id =", "# Bound to text fields in `_create_receive_form_layout`. def _update_receive_qr(self) ->", "amount, expiration, message, callback) else: # Expiration is just a", "self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self,", "self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0, 1, 1, -1) self._receive_message_e", "= self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID,", "str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show()", "def update_for_fx_quotes(self) -> None: if self._account_id is not None: edit", "4, 1, 1, 2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox", "uri = web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible():", ".util import ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window] =", "last column. # The exchange rate plugin adds a fiat", "a different Bitcoin SV payment destination.') receive_address_label = HelpLabel(_('Receiving destination'),", "not None: raise exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit() i =", "from .amountedit import AmountEdit, BTCAmountEdit from .constants import expiration_values if", "self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool) ->", "amount, message) self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message,", "QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout) return request_box", "self._account.get_script_template_for_id(self._receive_key_id) if script_template is not None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text)", "def set_new_button_enabled(self, flag: bool) -> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self, text:", "by the recipient if you send them ' 'a signed", "is not None: self._receive_qr.clean_up() if self._qr_window is not None: self._qr_window.close()", "self._main_window = weakref.proxy(main_window) self._account_id = account_id self._account = main_window._wallet.get_account(account_id) self._logger", "requests have to be deleted manually from your list, '", "TYPE_CHECKING import weakref from PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets", "flag: bool) -> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]: return", "deleted manually from your list, ' 'in order to free", "destination where the payment should be received. ' 'Note that", "vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def", "= \"\" if self._receive_key_id is not None: script_template = self._account.get_script_template_for_id(self._receive_key_id)", "= key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int) ->", "address never expires and will always be part ' 'of", "plugin adds a fiat widget in column 2 grid =", "a receive QR code object created yet. if self._receive_qr is", "update_destination(self) -> None: text = \"\" if self._receive_key_id is not", "self.update_destination() def set_form_contents(self, address_text: str, value: int, description: Optional[str]=None, expires_description:", "]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label", "request_container = self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1)", "self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button = EnterButton(_('Save request'),", "import expiration_values if TYPE_CHECKING: from .main_window import ElectrumWindow from .qrcodewidget", "self._expires_combo.show() if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self)", "destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]: return self._receive_key_id", "= keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text: str, value:", "self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int) -> None: self._receive_key_id =", "None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) -> None: self._expires_label.hide()", "(QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state", "None: if self._receive_key_id is None: return amount = self._receive_amount_e.get_amount() message", "QEvent) -> None: if self._receive_key_id is None: self.show_message(_(\"No available receiving", "-> None: if self._receive_key_id is None: self.show_message(_(\"No available receiving destination.\"))", "recipient if you send them ' 'a signed payment request.'),", "= QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box", "self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry)", "-> None: text = \"\" if self._receive_key_id is not None:", "import AmountEdit, BTCAmountEdit from .constants import expiration_values if TYPE_CHECKING: from", "self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]: return self._receive_key_id #", "self._receive_amount_e ] def _save_form_as_request(self) -> None: if not self._receive_key_id: self._main_window.show_error(_('No", "None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key)", "from .main_window import ElectrumWindow from .qrcodewidget import QRCodeWidget from .qrwindow", "a deterministic account instead.') ] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your", "EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200)", "self._account.is_deterministic(): msg = [ _('No more payment destinations in your", "from .request_list import RequestList from .table_widgets import TableTopButtonLayout from .util", "-> None: if self._account_id is not None: edit = (self._fiat_receive_e", "self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool) -> None: self._fiat_receive_e.setVisible(flag)", "if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False)", "using a non-deterministic account, which ' 'cannot create new payment", "keyinstances: List[KeyInstanceRow] = [] if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)", "fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None: if", "is None: return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount", "self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for i in expiration_values])", "free the corresponding Bitcoin SV addresses.'), _('The Bitcoin SV address", "typing import List, Optional, TYPE_CHECKING import weakref from PyQt5.QtCore import", "0, 0) request_box.setLayout(layout) return request_box def update_widgets(self) -> None: self._request_list.update()", "self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag:", "QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4,", "def _save_form_as_request(self) -> None: if not self._receive_key_id: self._main_window.show_error(_('No receiving payment", "callback(exc_value: Optional[Exception]=None) -> None: if exc_value is not None: raise", "if not self._receive_key_id: self._main_window.show_error(_('No receiving payment destination')) return amount =", "code object created yet. if self._receive_qr is not None: self._receive_qr.clean_up()", "0) grid.addWidget(self._receive_destination_e, 0, 1, 1, -1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')),", "app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo =", "List[KeyInstanceRow] = [] if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if", "self._request_list.update() def update_destination(self) -> None: text = \"\" if self._receive_key_id", "return request_box def update_widgets(self) -> None: self._request_list.update() def update_destination(self) ->", "is not None: raise exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit() i", "we don't use the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message,", "self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def", "amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency", "grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app)", "logs from electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv import web from", "Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit,", "[ _('No more payment destinations in your wallet.'), _('You are", "to create new payment destinations, ' 'use a deterministic account", "not None: edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text())", "QWidget) from electrumsv.app_state import app_state from electrumsv.bitcoin import script_template_to_string from", "= _('Bitcoin SV payment destination where the payment should be", "else: # Expiration is just a label, so we don't", "stretch is in the last column. # The exchange rate", "= self._expires_combo.currentIndex() expiration = [x[1] for x in expiration_values][i] row", "= TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list =", "wallet.'), _('You are using a non-deterministic account, which ' 'cannot", "expires and will always be part ' 'of this ElectrumSV", "msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0, 1, 1,", "_('This information is seen by the recipient if you send", "self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button", "3, 1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3,", "QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr)", "1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0)", "self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None) or (message != \"\")) script_template", "import _ from electrumsv.logs import logs from electrumsv.wallet_database.tables import KeyInstanceRow", "from electrumsv.bitcoin import script_template_to_string from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from", "A 4-column grid layout. All the stretch is in the", "request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout) return request_box def update_widgets(self) ->", "-> None: keyinstances: List[KeyInstanceRow] = [] if self._account.is_deterministic(): keyinstances =", "msg), 3, 0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1)", "'.join(msg)) return self._main_window.show_message( _('Your wallet is broken and could not", "Optional, TYPE_CHECKING import weakref from PyQt5.QtCore import QEvent, Qt from", "EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None def __init__(self,", "text = \"\" if self._receive_key_id is not None: script_template =", "QVBoxLayout, QWidget) from electrumsv.app_state import app_state from electrumsv.bitcoin import script_template_to_string", "want to create new payment destinations, ' 'use a deterministic", "create new payment destinations, ' 'use a deterministic account instead.')", "hbox def create_request_list_container(self) -> QGroupBox: layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6,", "PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget)", "message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None) or (message !=", "def receive_at_id(self, key_id: int) -> None: self._receive_key_id = key_id self._new_request_button.setEnabled(True)", "_('The Bitcoin SV address never expires and will always be", "the last column. # The exchange rate plugin adds a", "QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import app_state from electrumsv.bitcoin import", "QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self) -> QGroupBox: layout", "message or amount')) return def callback(exc_value: Optional[Exception]=None) -> None: if", "request.'), _('Expired requests have to be deleted manually from your", "allocate a new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self)", "from electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv import web from .amountedit", "None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]: return [ self._receive_amount_e ]", "receiving payment destination')) return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text()", "payment request.'), _('Expired requests have to be deleted manually from", "-> None: if not self._receive_key_id: self._main_window.show_error(_('No receiving payment destination')) return", "self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx else '') if not app_state.fx", "\"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri = web.create_URI(address_text,", "import ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None", "form_layout = self.create_form_layout() self._request_list = RequestList(self, main_window) request_container = self.create_request_list_container()", "address_text = script_template_to_string(script_template) uri = web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if", "= web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(),", "self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2, 1)", "not self._account.is_deterministic(): msg = [ _('No more payment destinations in", "if not self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry()", "which ' 'cannot create new payment destinations.'), _('If you want", "text fields in `_create_receive_form_layout`. def _update_receive_qr(self) -> None: if self._receive_key_id", "QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import app_state", "self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button)", "edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound", "\"\" if self._receive_key_id is not None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if", "self._main_window.show_message( _('Your wallet is broken and could not allocate a", "0, 0, 0) request_box.setLayout(layout) return request_box def update_widgets(self) -> None:", "if not self._account.is_deterministic(): msg = [ _('No more payment destinations", "not app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft)", "'cannot create new payment destinations.'), _('If you want to create", "self._receive_key_id: self._main_window.show_error(_('No receiving payment destination')) return amount = self._receive_amount_e.get_amount() message", "RECEIVING_SUBPATH from electrumsv.i18n import _ from electrumsv.logs import logs from", "row.expiration, message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow]", "from electrumsv.i18n import _ from electrumsv.logs import logs from electrumsv.wallet_database.tables", "self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int) -> None: self._receive_key_id", "AmountEdit(app_state.fx.get_currency if app_state.fx else '') if not app_state.fx or not", "= QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e, 1, 1, 1, -1)", "grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0, 1, 1, -1) self._receive_message_e =", "not allocate a new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def", "if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) ->", "self._expires_combo.addItems([i[0] for i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = '", "def update_widgets(self) -> None: self._request_list.update() def update_destination(self) -> None: text", "message, callback) else: # Expiration is just a label, so", "# Expiration is just a label, so we don't use", "self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration = [x[1] for x in", "AmountEdit, BTCAmountEdit from .constants import expiration_values if TYPE_CHECKING: from .main_window", "_('Bitcoin SV payment destination where the payment should be received.", "0, 1, 1, -1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0)", "from PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout,", "request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout) return request_box def update_widgets(self)", "is not None) or (message != \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id)", "wallet is broken and could not allocate a new payment", "self._qr_window.geometry() else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry =", "Optional[Exception]=None) -> None: if exc_value is not None: raise exc_value", "Optional[int] = None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout", "import ElectrumWindow from .qrcodewidget import QRCodeWidget from .qrwindow import QR_Window", "request uses a different Bitcoin SV payment destination.') receive_address_label =", "1, 1, 2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox =", "self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None: if self._account_id is", "update_for_fx_quotes(self) -> None: if self._account_id is not None: edit =", "if not message and not amount: self._main_window.show_error(_('No message or amount'))", "destination.') receive_address_label = HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0,", "menu. def receive_at_id(self, key_id: int) -> None: self._receive_key_id = key_id", "available receiving destination.\")) return if not self._qr_window: self._qr_window = QR_Window(self)", ".table_widgets import TableTopButtonLayout from .util import ButtonsLineEdit, EnterButton, HelpLabel class", "-> None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0]", "hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self) -> QGroupBox: layout = QVBoxLayout()", "self._save_request_button.setEnabled((amount is not None) or (message != \"\")) script_template =", "expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([ _('Expiration date of", "script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template is not None: text =", "# The exchange rate plugin adds a fiat widget in", "grid.addLayout(buttons, 4, 1, 1, 2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch()", "not None: self._receive_qr.clean_up() if self._qr_window is not None: self._qr_window.close() def", "None: edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) #", "PaymentFlag.UNPAID, amount, expiration, message, callback) else: # Expiration is just", ".request_list import RequestList from .table_widgets import TableTopButtonLayout from .util import", "from electrumsv.app_state import app_state from electrumsv.bitcoin import script_template_to_string from electrumsv.constants", "' 'of this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3,", "key_id def set_receive_key(self, keyinstance: KeyInstanceRow) -> None: self._receive_key_id = keyinstance.keyinstance_id", "have to be deleted manually from your list, ' 'in", "KeyInstanceRow from electrumsv import web from .amountedit import AmountEdit, BTCAmountEdit", "if self._receive_qr is not None: self._receive_qr.clean_up() if self._qr_window is not", "the payment should be received. ' 'Note that each payment", "i = self._expires_combo.currentIndex() expiration = [x[1] for x in expiration_values][i]", "if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances): if", "if self._receive_key_id is None: return amount = self._receive_amount_e.get_amount() message =", "-> List[BTCAmountEdit]: return [ self._receive_amount_e ] def _save_form_as_request(self) -> None:", "expiration = [x[1] for x in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id)", "not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo", "msg = ' '.join([ _('Expiration date of your request.'), _('This", "QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import app_state from electrumsv.bitcoin", "self._expires_combo.currentIndex() expiration = [x[1] for x in expiration_values][i] row =", "column 2 grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e =", "layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests'))", "= QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1, 2)", "request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0) request_box.setLayout(layout) return request_box def", "QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import app_state from", "' 'use a deterministic account instead.') ] self._main_window.show_message(' '.join(msg)) return", "None: self._receive_key_id = key_id def set_receive_key(self, keyinstance: KeyInstanceRow) -> None:", "self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list = RequestList(self, main_window) request_container", "(self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to text", "self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons =", "expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None: row =", "edit.textEdited.emit(edit.text()) # Bound to text fields in `_create_receive_form_layout`. def _update_receive_qr(self)", "List[BTCAmountEdit]: return [ self._receive_amount_e ] def _save_form_as_request(self) -> None: if", "def get_receive_key_id(self) -> Optional[int]: return self._receive_key_id # Only called from", "Optional[str]=None, expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value)", "RequestList from .table_widgets import TableTopButtonLayout from .util import ButtonsLineEdit, EnterButton,", "column. # The exchange rate plugin adds a fiat widget", "QR_Window from .request_list import RequestList from .table_widgets import TableTopButtonLayout from", "def set_receive_key_id(self, key_id: int) -> None: self._receive_key_id = key_id def", "electrumsv.app_state import app_state from electrumsv.bitcoin import script_template_to_string from electrumsv.constants import", "'Note that each payment request uses a different Bitcoin SV", "amount, row.expiration, message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None: keyinstances:", "def set_form_contents(self, address_text: str, value: int, description: Optional[str]=None, expires_description: str=\"\")", "self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool) ->", "uses a different Bitcoin SV payment destination.') receive_address_label = HelpLabel(_('Receiving", "None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True)", "self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox()", "_qr_window: Optional[QR_Window] = None def __init__(self, main_window: 'ElectrumWindow', account_id: int)", "QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1, 2) vbox_g", "web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount,", "self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None) or (message", "in column 2 grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e", "3, 1) self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'),", "import KeyInstanceRow from electrumsv import web from .amountedit import AmountEdit,", "-> None: if exc_value is not None: raise exc_value #", "message = self._receive_message_e.text() if not message and not amount: self._main_window.show_error(_('No", "account instead.') ] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your wallet is", "description: Optional[str]=None, expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\")", "# If there are no accounts there won't be a", "destination.\")) return if not self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry", "update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH,", "keyinstance: KeyInstanceRow) -> None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination()", "not None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template is not None:", "in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([ _('Expiration date", "2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for i", "0) request_box.setLayout(layout) return request_box def update_widgets(self) -> None: self._request_list.update() def", "callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow] = []", "grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg =", "def callback(exc_value: Optional[Exception]=None) -> None: if exc_value is not None:", "QComboBox() self._expires_combo.addItems([i[0] for i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg =", "not self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else:", "PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox,", "def update_destination(self) -> None: text = \"\" if self._receive_key_id is", "be deleted manually from your list, ' 'in order to", "= QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button =", "def _new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow] = [] if self._account.is_deterministic():", "layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0, 0, 0)", "weakref from PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets import (QComboBox,", "None def __init__(self, main_window: 'ElectrumWindow', account_id: int) -> None: super().__init__(main_window)", "new payment destinations.'), _('If you want to create new payment", "= EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr =", "= None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout =", "import weakref from PyQt5.QtCore import QEvent, Qt from PyQt5.QtWidgets import", "self._main_window.show_error(_('No receiving payment destination')) return amount = self._receive_amount_e.get_amount() message =", "self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV payment", "SV payment destination.') receive_address_label = HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus)", "_('Your wallet is broken and could not allocate a new", "buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1, 2) vbox_g =", "1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2,", "your wallet.'), _('You are using a non-deterministic account, which '", "if row is None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration,", "grid.addWidget(self._receive_destination_e, 0, 1, 1, -1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1,", "len(keyinstances): if not self._account.is_deterministic(): msg = [ _('No more payment", "and could not allocate a new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False)", "you send them ' 'a signed payment request.'), _('Expired requests", "uri) def _toggle_qr_window(self, event: QEvent) -> None: if self._receive_key_id is", "self.show_message(_(\"No available receiving destination.\")) return if not self._qr_window: self._qr_window =", "= script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show() if", "msg = [ _('No more payment destinations in your wallet.'),", "self._account = main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None", "payment request uses a different Bitcoin SV payment destination.') receive_address_label", "don't use the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message, callback)", "not None) or (message != \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text", "self._receive_key_id # Only called from key list menu. def receive_at_id(self,", "self._receive_message_e.text() if not message and not amount: self._main_window.show_error(_('No message or", "= RequestList(self, main_window) request_container = self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout)", "script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic():", "a label, so we don't use the value. self._account.requests.update_request(row.paymentrequest_id, row.state,", "None: self._receive_qr.clean_up() if self._qr_window is not None: self._qr_window.close() def create_form_layout(self)", "exchange rate plugin adds a fiat widget in column 2", "receive_at_id(self, key_id: int) -> None: self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination()", "import TableTopButtonLayout from .util import ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget):", "receive_address_label = HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0)", "self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV payment destination where the", "never expires and will always be part ' 'of this", "self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message, callback) else: # Expiration is", "self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([ _('Expiration date of your request.'),", "def _toggle_qr_window(self, event: QEvent) -> None: if self._receive_key_id is None:", "exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration =", "new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]:", "self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV payment destination where the payment", "payment should be received. ' 'Note that each payment request", "x in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None:", "' 'cannot create new payment destinations.'), _('If you want to", "'of this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0)", "grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e =", "to free the corresponding Bitcoin SV addresses.'), _('The Bitcoin SV", "vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self)", "else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry()", "grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label =", "if self._receive_key_id is None: self.show_message(_(\"No available receiving destination.\")) return if", "# pylint: disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration = [x[1]", "accounts there won't be a receive QR code object created", "QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit, QVBoxLayout, QWidget) from electrumsv.app_state import", "self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout = TableTopButtonLayout()", "self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list = RequestList(self, main_window)", "self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([ _('Expiration date of your", "self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1) buttons.addWidget(self._save_request_button) buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1,", "= QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return", "QGroupBox: layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout)", "disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration = [x[1] for x", "is None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message, callback)", "HelpLabel class ReceiveView(QWidget): _qr_window: Optional[QR_Window] = None def __init__(self, main_window:", "= QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True)", "= self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None) or", "key_id: int) -> None: self._receive_key_id = key_id def set_receive_key(self, keyinstance:", "= logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect(", "= [ _('No more payment destinations in your wallet.'), _('You", "if self._account_id is not None: edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited", "in `_create_receive_form_layout`. def _update_receive_qr(self) -> None: if self._receive_key_id is None:", "buttons.addWidget(self._new_request_button) grid.addLayout(buttons, 4, 1, 1, 2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid)", "callback) else: # Expiration is just a label, so we", "from .constants import expiration_values if TYPE_CHECKING: from .main_window import ElectrumWindow", "[x[1] for x in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row", "row is None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message,", "_new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow] = [] if self._account.is_deterministic(): keyinstances", "return self._receive_key_id # Only called from key list menu. def", "send them ' 'a signed payment request.'), _('Expired requests have", "for i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg = ' '.join([", "that each payment request uses a different Bitcoin SV payment", "_save_form_as_request(self) -> None: if not self._receive_key_id: self._main_window.show_error(_('No receiving payment destination'))", "grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx else", "= self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox)", "TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list = RequestList(self,", "clean_up(self) -> None: # If there are no accounts there", "= self._qr_window.geometry() else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry", "not message and not amount: self._main_window.show_error(_('No message or amount')) return", "def clean_up(self) -> None: # If there are no accounts", "amount: self._main_window.show_error(_('No message or amount')) return def callback(exc_value: Optional[Exception]=None) ->", "= [x[1] for x in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if", "None: self._request_list.update() def update_destination(self) -> None: text = \"\" if", "from .qrcodewidget import QRCodeWidget from .qrwindow import QR_Window from .request_list", "for x in expiration_values][i] row = self._account.requests.get_request_for_key_id(self._receive_key_id) if row is", "= self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message, callback) else: # Expiration", "self._request_list = RequestList(self, main_window) request_container = self.create_request_list_container() vbox = QVBoxLayout(self)", "create_form_layout(self) -> QHBoxLayout: # A 4-column grid layout. All the", "-1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e,", "' 'in order to free the corresponding Bitcoin SV addresses.'),", "return hbox def create_request_list_container(self) -> QGroupBox: layout = QVBoxLayout() layout.setSpacing(0)", "self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text: str,", "self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool) -> None: self._fiat_receive_e.setVisible(flag) def", "is not None: self._qr_window.close() def create_form_layout(self) -> QHBoxLayout: # A", "the stretch is in the last column. # The exchange", "self._receive_qr.clean_up() if self._qr_window is not None: self._qr_window.close() def create_form_layout(self) ->", "electrumsv.i18n import _ from electrumsv.logs import logs from electrumsv.wallet_database.tables import", "self._receive_amount_e.get_amount() message = self._receive_message_e.text() if not message and not amount:", "' 'a signed payment request.'), _('Expired requests have to be", "None: self.show_message(_(\"No available receiving destination.\")) return if not self._qr_window: self._qr_window", "destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0, 1,", "your request.'), _('This information is seen by the recipient if", "self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int) -> None: self._receive_key_id = key_id", "0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide()", "2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g)", "'a signed payment request.'), _('Expired requests have to be deleted", "is just a label, so we don't use the value.", "1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None: if self._account_id is not", "web from .amountedit import AmountEdit, BTCAmountEdit from .constants import expiration_values", "destinations, ' 'use a deterministic account instead.') ] self._main_window.show_message(' '.join(msg))", "are no accounts there won't be a receive QR code", "= self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri = web.create_URI(address_text, amount, message)", "__init__(self, main_window: 'ElectrumWindow', account_id: int) -> None: super().__init__(main_window) self._main_window =", "import RequestList from .table_widgets import TableTopButtonLayout from .util import ButtonsLineEdit,", "self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to text fields in", "or (message != \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template)", "-> Optional[int]: return self._receive_key_id # Only called from key list", "request_box def update_widgets(self) -> None: self._request_list.update() def update_destination(self) -> None:", "of your request.'), _('This information is seen by the recipient", "account, which ' 'cannot create new payment destinations.'), _('If you", "widget in column 2 grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1)", "are using a non-deterministic account, which ' 'cannot create new", "def set_fiat_ccy_enabled(self, flag: bool) -> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) ->", "-> None: self._receive_key_id = key_id def set_receive_key(self, keyinstance: KeyInstanceRow) ->", "self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def _toggle_qr_window(self, event: QEvent) ->", "None: raise exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex()", "TableTopButtonLayout from .util import ButtonsLineEdit, EnterButton, HelpLabel class ReceiveView(QWidget): _qr_window:", "destinations in your wallet.'), _('You are using a non-deterministic account,", "1, 0) grid.addWidget(self._receive_message_e, 1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e =", "None: keyinstances: List[KeyInstanceRow] = [] if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH,", "self._qr_window_geometry = self._qr_window.geometry() else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else:", "value: int, description: Optional[str]=None, expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description", "self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list", "Bound to text fields in `_create_receive_form_layout`. def _update_receive_qr(self) -> None:", "# A 4-column grid layout. All the stretch is in", "BTCAmountEdit from .constants import expiration_values if TYPE_CHECKING: from .main_window import", "should be received. ' 'Note that each payment request uses", "signed payment request.'), _('Expired requests have to be deleted manually", "keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text: str, value: int,", "= script_template_to_string(script_template) uri = web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if self._qr_window", "1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1)", "self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for i in expiration_values]) self._expires_combo.setCurrentIndex(3)", "SV address never expires and will always be part '", "hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self) ->", "Optional[QR_Window] = None def __init__(self, main_window: 'ElectrumWindow', account_id: int) ->", "return [ self._receive_amount_e ] def _save_form_as_request(self) -> None: if not", "import script_template_to_string from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import", "= ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV payment destination", "the corresponding Bitcoin SV addresses.'), _('The Bitcoin SV address never", "get_receive_key_id(self) -> Optional[int]: return self._receive_key_id # Only called from key", "your list, ' 'in order to free the corresponding Bitcoin", "script_template_to_string from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n import _", "grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0]", "from electrumsv.logs import logs from electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv", "def set_receive_key(self, keyinstance: KeyInstanceRow) -> None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\")", "or amount')) return def callback(exc_value: Optional[Exception]=None) -> None: if exc_value", "adds a fiat widget in column 2 grid = QGridLayout()", "6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0, 0,", "grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin", "import QRCodeWidget from .qrwindow import QR_Window from .request_list import RequestList", "row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message, callback) else: #", "expires'), msg), 3, 0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label = QLineEdit('')", "rate plugin adds a fiat widget in column 2 grid", "request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window)", "1) if not len(keyinstances): if not self._account.is_deterministic(): msg = [", "_ from electrumsv.logs import logs from electrumsv.wallet_database.tables import KeyInstanceRow from", "return if not self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry =", "request.'), _('This information is seen by the recipient if you", "-> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]: return [ self._receive_amount_e", "and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def _toggle_qr_window(self, event: QEvent)", "ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0) grid.addWidget(self._expires_combo, 3,", "QRCodeWidget from .qrwindow import QR_Window from .request_list import RequestList from", "self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list)", "-> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self, text: str) -> None: self._request_list.filter(text)", "payment destinations.'), _('If you want to create new payment destinations,", "self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def set_receive_key_id(self, key_id: int)", "self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e, 0, 1, 1, -1)", "where the payment should be received. ' 'Note that each", "order to free the corresponding Bitcoin SV addresses.'), _('The Bitcoin", "' '.join([ _('Expiration date of your request.'), _('This information is", "self._receive_key_id = key_id def set_receive_key(self, keyinstance: KeyInstanceRow) -> None: self._receive_key_id", "2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx else '')", "= [] if self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not", "main_window) request_container = self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container,", "script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text = script_template_to_string(script_template) uri = web.create_URI(address_text, amount,", "destinations.'), _('If you want to create new payment destinations, '", "layout. All the stretch is in the last column. #", "if not app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2,", "label, so we don't use the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount,", "no accounts there won't be a receive QR code object", "not None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) -> None:", "ElectrumWindow from .qrcodewidget import QRCodeWidget from .qrwindow import QR_Window from", "object created yet. if self._receive_qr is not None: self._receive_qr.clean_up() if", "4-column grid layout. All the stretch is in the last", "could not allocate a new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1)", "-> None: if self._receive_key_id is None: return amount = self._receive_amount_e.get_amount()", "self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else: if not", "grid.addWidget(self._expires_label, 3, 1) self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button =", "= QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self) -> QGroupBox:", "self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else: if", "called from key list menu. def receive_at_id(self, key_id: int) ->", "address_text: str, value: int, description: Optional[str]=None, expires_description: str=\"\") -> None:", "broken and could not allocate a new payment destination.')) self.update_contents()", "import app_state from electrumsv.bitcoin import script_template_to_string from electrumsv.constants import PaymentFlag,", "= key_id def set_receive_key(self, keyinstance: KeyInstanceRow) -> None: self._receive_key_id =", "self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request) self._receive_qr", "= self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool) -> None:", "self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]: return self._receive_key_id # Only", "or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag:", "QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self) -> None:", "from .table_widgets import TableTopButtonLayout from .util import ButtonsLineEdit, EnterButton, HelpLabel", "receiving destination.\")) return if not self._qr_window: self._qr_window = QR_Window(self) self._qr_window.setVisible(True)", "self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def _toggle_qr_window(self, event: QEvent) -> None:", "always be part ' 'of this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request", "fiat widget in column 2 grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3,", "create_request_list_container(self) -> QGroupBox: layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6,", "self._account.is_deterministic(): fresh_key = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None:", "key list menu. def receive_at_id(self, key_id: int) -> None: self._receive_key_id", "def create_form_layout(self) -> QHBoxLayout: # A 4-column grid layout. All", "EnterButton(_('New'), self._new_payment_request) self._receive_qr = QRCodeWidget(fixedSize=200) self._receive_qr.link_to_window(self._toggle_qr_window) buttons = QHBoxLayout() buttons.addStretch(1)", "account_id self._account = main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] =", "grid.addWidget(self._receive_message_e, 1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested", "payment destination')) return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() if", "event: QEvent) -> None: if self._receive_key_id is None: self.show_message(_(\"No available", "electrumsv.wallet_database.tables import KeyInstanceRow from electrumsv import web from .amountedit import", "from electrumsv import web from .amountedit import AmountEdit, BTCAmountEdit from", "is not None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template is not", "new payment destinations, ' 'use a deterministic account instead.') ]", "1, 2) vbox_g = QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout()", "1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')),", "'.join([ _('Expiration date of your request.'), _('This information is seen", "-> None: # If there are no accounts there won't", "self._account.requests.get_request_for_key_id(self._receive_key_id) if row is None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount,", "self._account_id is not None: edit = (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else", "message and not amount: self._main_window.show_error(_('No message or amount')) return def", "self.create_form_layout() self._request_list = RequestList(self, main_window) request_container = self.create_request_list_container() vbox =", "QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg", "so we don't use the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration,", "if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def _toggle_qr_window(self,", "2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e) self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for", "is None: self.show_message(_(\"No available receiving destination.\")) return if not self._qr_window:", "import QEvent, Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout,", "value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self)", "-> QGroupBox: layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6)", "self._receive_qr is not None: self._receive_qr.clean_up() if self._qr_window is not None:", "[ self._receive_amount_e ] def _save_form_as_request(self) -> None: if not self._receive_key_id:", "expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide()", "electrumsv.bitcoin import script_template_to_string from electrumsv.constants import PaymentFlag, RECEIVING_SUBPATH from electrumsv.i18n", "'') if not app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2,", "each payment request uses a different Bitcoin SV payment destination.')", "-> None: self._request_list.update() def update_destination(self) -> None: text = \"\"", "2, 0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if", "self._receive_qr.setData(uri) if self._qr_window and self._qr_window.isVisible(): self._qr_window.set_content(self._receive_destination_e.text(), amount, message, uri) def", "self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text: str, value: int, description:", "TYPE_CHECKING: from .main_window import ElectrumWindow from .qrcodewidget import QRCodeWidget from", "1) self._receive_destination_e = ButtonsLineEdit() self._receive_destination_e.addCopyButton(app_state.app) self._receive_destination_e.setReadOnly(True) msg = _('Bitcoin SV", "not self._receive_key_id: self._main_window.show_error(_('No receiving payment destination')) return amount = self._receive_amount_e.get_amount()", "instead.') ] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your wallet is broken", "electrumsv import web from .amountedit import AmountEdit, BTCAmountEdit from .constants", "= self._receive_message_e.text() self._save_request_button.setEnabled((amount is not None) or (message != \"\"))", "self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout() self._request_list = RequestList(self, main_window) request_container =", "self._main_window.show_error(_('No message or amount')) return def callback(exc_value: Optional[Exception]=None) -> None:", "= main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout", "None: if self._receive_key_id is None: self.show_message(_(\"No available receiving destination.\")) return", "self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow] = [] if", "= self._account.get_fresh_keys(RECEIVING_SUBPATH, 1)[0] self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None: if self._account_id", "if TYPE_CHECKING: from .main_window import ElectrumWindow from .qrcodewidget import QRCodeWidget", "text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show()", "self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self) -> List[BTCAmountEdit]: return [ self._receive_amount_e ] def", "is not None: text = script_template_to_string(script_template) self._receive_destination_e.setText(text) def update_contents(self) ->", "if exc_value is not None: raise exc_value # pylint: disable=raising-bad-type", "is seen by the recipient if you send them '", "script_template_to_string(script_template) uri = web.create_URI(address_text, amount, message) self._receive_qr.setData(uri) if self._qr_window and", "vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self) -> None: #", "fields in `_create_receive_form_layout`. def _update_receive_qr(self) -> None: if self._receive_key_id is", "return def callback(exc_value: Optional[Exception]=None) -> None: if exc_value is not", "keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances): if not self._account.is_deterministic():", "0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr) self._fiat_receive_e = AmountEdit(app_state.fx.get_currency if app_state.fx", "= HelpLabel(_('Receiving destination'), msg) self._receive_destination_e.textChanged.connect(self._update_receive_qr) self._receive_destination_e.setFocusPolicy(Qt.NoFocus) grid.addWidget(receive_address_label, 0, 0) grid.addWidget(self._receive_destination_e,", "None: if exc_value is not None: raise exc_value # pylint:", "def create_request_list_container(self) -> QGroupBox: layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0,", "QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box =", "6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox() request_box.setTitle(_('Requests')) request_box.setAlignment(Qt.AlignCenter) request_box.setContentsMargins(0,", "payment destinations in your wallet.'), _('You are using a non-deterministic", "= None def __init__(self, main_window: 'ElectrumWindow', account_id: int) -> None:", "self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) ->", "= self._receive_message_e.text() if not message and not amount: self._main_window.show_error(_('No message", "None: return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() self._save_request_button.setEnabled((amount is", "None: row = self._account.requests.create_request(self._receive_key_id, PaymentFlag.UNPAID, amount, expiration, message, callback) else:", "= ' '.join([ _('Expiration date of your request.'), _('This information", "raise exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration", "QR_Window(self) self._qr_window.setVisible(True) self._qr_window_geometry = self._qr_window.geometry() else: if not self._qr_window.isVisible(): self._qr_window.setVisible(True)", "create new payment destinations.'), _('If you want to create new", "a non-deterministic account, which ' 'cannot create new payment destinations.'),", "self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self,", "message, uri) def _toggle_qr_window(self, event: QEvent) -> None: if self._receive_key_id", "this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0) grid.addWidget(self._expires_combo,", "QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button = EnterButton(_('Save", "self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool) -> None:", "int) -> None: self._receive_key_id = key_id self._new_request_button.setEnabled(True) self.update_destination() self._main_window.show_receive_tab() def", "receive QR code object created yet. if self._receive_qr is not", "amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() if not message and", "None: if not self._receive_key_id: self._main_window.show_error(_('No receiving payment destination')) return amount", "None) or (message != \"\")) script_template = self._account.get_script_template_for_id(self._receive_key_id) address_text =", "a new payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) ->", "self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def", "deterministic account instead.') ] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your wallet", "main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int] = None self._request_list_toolbar_layout =", "-> None: self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description)", "pylint: disable=raising-bad-type self._request_list.update_signal.emit() i = self._expires_combo.currentIndex() expiration = [x[1] for", "manually from your list, ' 'in order to free the", "self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button", "more payment destinations in your wallet.'), _('You are using a", "from .qrwindow import QR_Window from .request_list import RequestList from .table_widgets", "weakref.proxy(main_window) self._account_id = account_id self._account = main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\")", "] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message( _('Your wallet is broken and", "QHBoxLayout: # A 4-column grid layout. All the stretch is", "from typing import List, Optional, TYPE_CHECKING import weakref from PyQt5.QtCore", ".qrwindow import QR_Window from .request_list import RequestList from .table_widgets import", "self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text: str, value: int, description: Optional[str]=None,", "str, value: int, description: Optional[str]=None, expires_description: str=\"\") -> None: self._receive_destination_e.setText(address_text)", "vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self) -> None: # If there", "the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message, callback) self._save_request_button.setEnabled(False) def", "= self._account.get_script_template_for_id(self._receive_key_id) if script_template is not None: text = script_template_to_string(script_template)", "destination')) return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() if not", "2 grid = QGridLayout() grid.setSpacing(8) grid.setColumnStretch(3, 1) self._receive_destination_e = ButtonsLineEdit()", "= (self._fiat_receive_e if self._fiat_receive_e.is_last_edited else self._receive_amount_e) edit.textEdited.emit(edit.text()) # Bound to", "be part ' 'of this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'),", "layout = QVBoxLayout() layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list)", "if self._receive_key_id is not None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template", "or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e, self._fiat_receive_e)", "self._account_id = account_id self._account = main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id:", "part ' 'of this ElectrumSV wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg),", "wallet.'), ]) grid.addWidget(HelpLabel(_('Request expires'), msg), 3, 0) grid.addWidget(self._expires_combo, 3, 1)", "= weakref.proxy(main_window) self._account_id = account_id self._account = main_window._wallet.get_account(account_id) self._logger =", "= account_id self._account = main_window._wallet.get_account(account_id) self._logger = logs.get_logger(f\"receive-view[{self._account_id}]\") self._receive_key_id: Optional[int]", "= self._receive_amount_e.get_amount() message = self._receive_message_e.text() if not message and not", "message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None: keyinstances: List[KeyInstanceRow] =", "int) -> None: super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id = account_id", "self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool) -> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self,", "created yet. if self._receive_qr is not None: self._receive_qr.clean_up() if self._qr_window", "return self._main_window.show_message( _('Your wallet is broken and could not allocate", "if not len(keyinstances): if not self._account.is_deterministic(): msg = [ _('No", "self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool) -> None: self._fiat_receive_e.setVisible(flag) def get_bsv_edits(self)", "self._account.is_deterministic(): keyinstances = self._account.get_fresh_keys(RECEIVING_SUBPATH, 1) if not len(keyinstances): if not", "return amount = self._receive_amount_e.get_amount() message = self._receive_message_e.text() if not message", "in your wallet.'), _('You are using a non-deterministic account, which", "self._receive_key_id is not None: script_template = self._account.get_script_template_for_id(self._receive_key_id) if script_template is", "1) self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request) self._new_request_button = EnterButton(_('New'), self._new_payment_request)", "def _update_receive_qr(self) -> None: if self._receive_key_id is None: return amount", "main_window: 'ElectrumWindow', account_id: int) -> None: super().__init__(main_window) self._main_window = weakref.proxy(main_window)", "QVBoxLayout() vbox_g.addLayout(grid) vbox_g.addStretch() hbox = QHBoxLayout() hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox", "'use a deterministic account instead.') ] self._main_window.show_message(' '.join(msg)) return self._main_window.show_message(", "self._receive_key_id is None: self.show_message(_(\"No available receiving destination.\")) return if not", "app_state.fx else '') if not app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False)", "0) grid.addWidget(self._receive_message_e, 1, 1, 1, -1) self._receive_message_e.textChanged.connect(self._update_receive_qr) self._receive_amount_e = BTCAmountEdit()", "SV addresses.'), _('The Bitcoin SV address never expires and will", "self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def", "app_state.fx or not app_state.fx.is_enabled(): self._fiat_receive_e.setVisible(False) grid.addWidget(self._fiat_receive_e, 2, 2, Qt.AlignLeft) self._main_window.connect_fields(self._receive_amount_e,", "use the value. self._account.requests.update_request(row.paymentrequest_id, row.state, amount, row.expiration, message, callback) self._save_request_button.setEnabled(False)", "_('If you want to create new payment destinations, ' 'use", "self._qr_window is not None: self._qr_window.close() def create_form_layout(self) -> QHBoxLayout: #", "from your list, ' 'in order to free the corresponding", ".main_window import ElectrumWindow from .qrcodewidget import QRCodeWidget from .qrwindow import", "-> QHBoxLayout: # A 4-column grid layout. All the stretch", "RequestList(self, main_window) request_container = self.create_request_list_container() vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20)", "`_create_receive_form_layout`. def _update_receive_qr(self) -> None: if self._receive_key_id is None: return", "set_new_button_enabled(self, flag: bool) -> None: self._new_request_button.setEnabled(flag) def _filter_request_list(self, text: str)", "self.setLayout(vbox) def clean_up(self) -> None: # If there are no", "= QComboBox() self._expires_combo.addItems([i[0] for i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width()) msg", "payment destination.')) self.update_contents() self._new_request_button.setEnabled(False) self._receive_message_e.setFocus(1) def get_receive_key_id(self) -> Optional[int]: return", "def update_contents(self) -> None: self._expires_label.hide() self._expires_combo.show() if self._account.is_deterministic(): fresh_key =", "self._receive_destination_e.setText(address_text) self._receive_message_e.setText(description or \"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def", "expiration_values if TYPE_CHECKING: from .main_window import ElectrumWindow from .qrcodewidget import", "] def _save_form_as_request(self) -> None: if not self._receive_key_id: self._main_window.show_error(_('No receiving", "there are no accounts there won't be a receive QR", "None: self._qr_window.close() def create_form_layout(self) -> QHBoxLayout: # A 4-column grid", "self._expires_combo = QComboBox() self._expires_combo.addItems([i[0] for i in expiration_values]) self._expires_combo.setCurrentIndex(3) self._expires_combo.setFixedWidth(self._receive_amount_e.width())", "import List, Optional, TYPE_CHECKING import weakref from PyQt5.QtCore import QEvent,", "there won't be a receive QR code object created yet.", "QR code object created yet. if self._receive_qr is not None:", "hbox.addLayout(vbox_g) hbox.addWidget(self._receive_qr) return hbox def create_request_list_container(self) -> QGroupBox: layout =", "layout.setSpacing(0) layout.setContentsMargins(6, 0, 6, 6) layout.addLayout(self._request_list_toolbar_layout) layout.addWidget(self._request_list) request_box = QGroupBox()", "exc_value is not None: raise exc_value # pylint: disable=raising-bad-type self._request_list.update_signal.emit()", "self.set_receive_key(fresh_key) def update_for_fx_quotes(self) -> None: if self._account_id is not None:", "List, Optional, TYPE_CHECKING import weakref from PyQt5.QtCore import QEvent, Qt", "row.state, amount, row.expiration, message, callback) self._save_request_button.setEnabled(False) def _new_payment_request(self) -> None:", "None self._request_list_toolbar_layout = TableTopButtonLayout() self._request_list_toolbar_layout.refresh_signal.connect( self._main_window.refresh_wallet_display) self._request_list_toolbar_layout.filter_signal.connect(self._filter_request_list) form_layout = self.create_form_layout()", "else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr() def set_fiat_ccy_enabled(self, flag: bool)", "1, 1, -1) self._receive_message_e = QLineEdit() grid.addWidget(QLabel(_('Description')), 1, 0) grid.addWidget(self._receive_message_e,", "QEvent, Qt from PyQt5.QtWidgets import (QComboBox, QGridLayout, QGroupBox, QHBoxLayout, QLabel,", "3, 0) grid.addWidget(self._expires_combo, 3, 1) self._expires_label = QLineEdit('') self._expires_label.setReadOnly(1) self._expires_label.setFocusPolicy(Qt.NoFocus)", "just a label, so we don't use the value. self._account.requests.update_request(row.paymentrequest_id,", "\"\") self._receive_amount_e.setAmount(value) self._expires_combo.hide() self._expires_label.show() self._expires_label.setText(expires_description) self._new_request_button.setEnabled(True) def set_new_button_enabled(self, flag: bool)", "vbox = QVBoxLayout(self) vbox.addLayout(form_layout) vbox.addSpacing(20) vbox.addWidget(request_container, 1) self.setLayout(vbox) def clean_up(self)", "= BTCAmountEdit() grid.addWidget(QLabel(_('Requested amount')), 2, 0) grid.addWidget(self._receive_amount_e, 2, 1) self._receive_amount_e.textChanged.connect(self._update_receive_qr)", "update_widgets(self) -> None: self._request_list.update() def update_destination(self) -> None: text =", "self._expires_label.setFocusPolicy(Qt.NoFocus) self._expires_label.hide() grid.addWidget(self._expires_label, 3, 1) self._save_request_button = EnterButton(_('Save request'), self._save_form_as_request)", "amount, message, uri) def _toggle_qr_window(self, event: QEvent) -> None: if", "date of your request.'), _('This information is seen by the", "' 'Note that each payment request uses a different Bitcoin", "-> None: super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id = account_id self._account", "def get_bsv_edits(self) -> List[BTCAmountEdit]: return [ self._receive_amount_e ] def _save_form_as_request(self)", "'ElectrumWindow', account_id: int) -> None: super().__init__(main_window) self._main_window = weakref.proxy(main_window) self._account_id", "not self._qr_window.isVisible(): self._qr_window.setVisible(True) self._qr_window.setGeometry(self._qr_window_geometry) else: self._qr_window_geometry = self._qr_window.geometry() self._qr_window.setVisible(False) self._update_receive_qr()", "received. ' 'Note that each payment request uses a different", "seen by the recipient if you send them ' 'a", "None: self._receive_key_id = keyinstance.keyinstance_id self._receive_message_e.setText(\"\") self._receive_amount_e.setAmount(None) self.update_destination() def set_form_contents(self, address_text:" ]