repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
bokeh/bokeh
scripts/issues.py
closed_issues
def closed_issues(issues, after): """Yields closed issues (closed after a given datetime) given a list of issues.""" logging.info('finding closed issues after {}...'.format(after)) seen = set() for issue in issues: if closed_issue(issue, after) and issue['title'] not in seen: seen.add(issue['title']) yield issue
python
def closed_issues(issues, after): """Yields closed issues (closed after a given datetime) given a list of issues.""" logging.info('finding closed issues after {}...'.format(after)) seen = set() for issue in issues: if closed_issue(issue, after) and issue['title'] not in seen: seen.add(issue['title']) yield issue
[ "def", "closed_issues", "(", "issues", ",", "after", ")", ":", "logging", ".", "info", "(", "'finding closed issues after {}...'", ".", "format", "(", "after", ")", ")", "seen", "=", "set", "(", ")", "for", "issue", "in", "issues", ":", "if", "closed_issue", "(", "issue", ",", "after", ")", "and", "issue", "[", "'title'", "]", "not", "in", "seen", ":", "seen", ".", "add", "(", "issue", "[", "'title'", "]", ")", "yield", "issue" ]
Yields closed issues (closed after a given datetime) given a list of issues.
[ "Yields", "closed", "issues", "(", "closed", "after", "a", "given", "datetime", ")", "given", "a", "list", "of", "issues", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L140-L147
train
bokeh/bokeh
scripts/issues.py
all_issues
def all_issues(issues): """Yields unique set of issues given a list of issues.""" logging.info('finding issues...') seen = set() for issue in issues: if issue['title'] not in seen: seen.add(issue['title']) yield issue
python
def all_issues(issues): """Yields unique set of issues given a list of issues.""" logging.info('finding issues...') seen = set() for issue in issues: if issue['title'] not in seen: seen.add(issue['title']) yield issue
[ "def", "all_issues", "(", "issues", ")", ":", "logging", ".", "info", "(", "'finding issues...'", ")", "seen", "=", "set", "(", ")", "for", "issue", "in", "issues", ":", "if", "issue", "[", "'title'", "]", "not", "in", "seen", ":", "seen", ".", "add", "(", "issue", "[", "'title'", "]", ")", "yield", "issue" ]
Yields unique set of issues given a list of issues.
[ "Yields", "unique", "set", "of", "issues", "given", "a", "list", "of", "issues", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L150-L157
train
bokeh/bokeh
scripts/issues.py
get_issues_url
def get_issues_url(page, after): """Returns github API URL for querying tags.""" template = '{base_url}/{owner}/{repo}/issues?state=closed&per_page=100&page={page}&since={after}' return template.format(page=page, after=after.isoformat(), **API_PARAMS)
python
def get_issues_url(page, after): """Returns github API URL for querying tags.""" template = '{base_url}/{owner}/{repo}/issues?state=closed&per_page=100&page={page}&since={after}' return template.format(page=page, after=after.isoformat(), **API_PARAMS)
[ "def", "get_issues_url", "(", "page", ",", "after", ")", ":", "template", "=", "'{base_url}/{owner}/{repo}/issues?state=closed&per_page=100&page={page}&since={after}'", "return", "template", ".", "format", "(", "page", "=", "page", ",", "after", "=", "after", ".", "isoformat", "(", ")", ",", "*", "*", "API_PARAMS", ")" ]
Returns github API URL for querying tags.
[ "Returns", "github", "API", "URL", "for", "querying", "tags", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L168-L171
train
bokeh/bokeh
scripts/issues.py
parse_timestamp
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
python
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
[ "def", "parse_timestamp", "(", "timestamp", ")", ":", "dt", "=", "dateutil", ".", "parser", ".", "parse", "(", "timestamp", ")", "return", "dt", ".", "astimezone", "(", "dateutil", ".", "tz", ".", "tzutc", "(", ")", ")" ]
Parse ISO8601 timestamps given by github API.
[ "Parse", "ISO8601", "timestamps", "given", "by", "github", "API", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L179-L182
train
bokeh/bokeh
scripts/issues.py
read_url
def read_url(url): """Reads given URL as JSON and returns data as loaded python object.""" logging.debug('reading {url} ...'.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers['Authorization'] = 'token %s' % token request = Request(url, headers=headers) response = urlopen(request).read() return json.loads(response.decode("UTF-8"))
python
def read_url(url): """Reads given URL as JSON and returns data as loaded python object.""" logging.debug('reading {url} ...'.format(url=url)) token = os.environ.get("BOKEH_GITHUB_API_TOKEN") headers = {} if token: headers['Authorization'] = 'token %s' % token request = Request(url, headers=headers) response = urlopen(request).read() return json.loads(response.decode("UTF-8"))
[ "def", "read_url", "(", "url", ")", ":", "logging", ".", "debug", "(", "'reading {url} ...'", ".", "format", "(", "url", "=", "url", ")", ")", "token", "=", "os", ".", "environ", ".", "get", "(", "\"BOKEH_GITHUB_API_TOKEN\"", ")", "headers", "=", "{", "}", "if", "token", ":", "headers", "[", "'Authorization'", "]", "=", "'token %s'", "%", "token", "request", "=", "Request", "(", "url", ",", "headers", "=", "headers", ")", "response", "=", "urlopen", "(", "request", ")", ".", "read", "(", ")", "return", "json", ".", "loads", "(", "response", ".", "decode", "(", "\"UTF-8\"", ")", ")" ]
Reads given URL as JSON and returns data as loaded python object.
[ "Reads", "given", "URL", "as", "JSON", "and", "returns", "data", "as", "loaded", "python", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L185-L194
train
bokeh/bokeh
scripts/issues.py
query_all_issues
def query_all_issues(after): """Hits the github API for all closed issues after the given date, returns the data.""" page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not page_data: break data.extend(page_data) return data
python
def query_all_issues(after): """Hits the github API for all closed issues after the given date, returns the data.""" page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not page_data: break data.extend(page_data) return data
[ "def", "query_all_issues", "(", "after", ")", ":", "page", "=", "count", "(", "1", ")", "data", "=", "[", "]", "while", "True", ":", "page_data", "=", "query_issues", "(", "next", "(", "page", ")", ",", "after", ")", "if", "not", "page_data", ":", "break", "data", ".", "extend", "(", "page_data", ")", "return", "data" ]
Hits the github API for all closed issues after the given date, returns the data.
[ "Hits", "the", "github", "API", "for", "all", "closed", "issues", "after", "the", "given", "date", "returns", "the", "data", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L207-L216
train
bokeh/bokeh
scripts/issues.py
dateof
def dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.""" for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit']['url']) return parse_timestamp(commit['commit']['committer']['date']) return None
python
def dateof(tag_name, tags): """Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.""" for tag in tags: if tag['name'] == tag_name: commit = read_url(tag['commit']['url']) return parse_timestamp(commit['commit']['committer']['date']) return None
[ "def", "dateof", "(", "tag_name", ",", "tags", ")", ":", "for", "tag", "in", "tags", ":", "if", "tag", "[", "'name'", "]", "==", "tag_name", ":", "commit", "=", "read_url", "(", "tag", "[", "'commit'", "]", "[", "'url'", "]", ")", "return", "parse_timestamp", "(", "commit", "[", "'commit'", "]", "[", "'committer'", "]", "[", "'date'", "]", ")", "return", "None" ]
Given a list of tags, returns the datetime of the tag with the given name; Otherwise None.
[ "Given", "a", "list", "of", "tags", "returns", "the", "datetime", "of", "the", "tag", "with", "the", "given", "name", ";", "Otherwise", "None", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L219-L225
train
bokeh/bokeh
scripts/issues.py
get_data
def get_data(query_func, load_data=False, save_data=False): """Gets data from query_func, optionally saving that data to a file; or loads data from a file.""" if hasattr(query_func, '__name__'): func_name = query_func.__name__ elif hasattr(query_func, 'func'): func_name = query_func.func.__name__ pickle_file = '{}.pickle'.format(func_name) if load_data: data = load_object(pickle_file) else: data = query_func() if save_data: save_object(pickle_file, data) return data
python
def get_data(query_func, load_data=False, save_data=False): """Gets data from query_func, optionally saving that data to a file; or loads data from a file.""" if hasattr(query_func, '__name__'): func_name = query_func.__name__ elif hasattr(query_func, 'func'): func_name = query_func.func.__name__ pickle_file = '{}.pickle'.format(func_name) if load_data: data = load_object(pickle_file) else: data = query_func() if save_data: save_object(pickle_file, data) return data
[ "def", "get_data", "(", "query_func", ",", "load_data", "=", "False", ",", "save_data", "=", "False", ")", ":", "if", "hasattr", "(", "query_func", ",", "'__name__'", ")", ":", "func_name", "=", "query_func", ".", "__name__", "elif", "hasattr", "(", "query_func", ",", "'func'", ")", ":", "func_name", "=", "query_func", ".", "func", ".", "__name__", "pickle_file", "=", "'{}.pickle'", ".", "format", "(", "func_name", ")", "if", "load_data", ":", "data", "=", "load_object", "(", "pickle_file", ")", "else", ":", "data", "=", "query_func", "(", ")", "if", "save_data", ":", "save_object", "(", "pickle_file", ",", "data", ")", "return", "data" ]
Gets data from query_func, optionally saving that data to a file; or loads data from a file.
[ "Gets", "data", "from", "query_func", "optionally", "saving", "that", "data", "to", "a", "file", ";", "or", "loads", "data", "from", "a", "file", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L228-L243
train
bokeh/bokeh
scripts/issues.py
check_issues
def check_issues(issues, after=None): """Checks issues for BEP 1 compliance.""" issues = closed_issues(issues, after) if after else all_issues(issues) issues = sorted(issues, key=ISSUES_SORT_KEY) have_warnings = False for section, issue_group in groupby(issues, key=ISSUES_BY_SECTION): for issue in issue_group: have_warnings |= check_issue(issue, after) return have_warnings
python
def check_issues(issues, after=None): """Checks issues for BEP 1 compliance.""" issues = closed_issues(issues, after) if after else all_issues(issues) issues = sorted(issues, key=ISSUES_SORT_KEY) have_warnings = False for section, issue_group in groupby(issues, key=ISSUES_BY_SECTION): for issue in issue_group: have_warnings |= check_issue(issue, after) return have_warnings
[ "def", "check_issues", "(", "issues", ",", "after", "=", "None", ")", ":", "issues", "=", "closed_issues", "(", "issues", ",", "after", ")", "if", "after", "else", "all_issues", "(", "issues", ")", "issues", "=", "sorted", "(", "issues", ",", "key", "=", "ISSUES_SORT_KEY", ")", "have_warnings", "=", "False", "for", "section", ",", "issue_group", "in", "groupby", "(", "issues", ",", "key", "=", "ISSUES_BY_SECTION", ")", ":", "for", "issue", "in", "issue_group", ":", "have_warnings", "|=", "check_issue", "(", "issue", ",", "after", ")", "return", "have_warnings" ]
Checks issues for BEP 1 compliance.
[ "Checks", "issues", "for", "BEP", "1", "compliance", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L270-L281
train
bokeh/bokeh
scripts/issues.py
issue_line
def issue_line(issue): """Returns log line for given issue.""" template = '#{number} {tags}{title}' tags = issue_tags(issue) params = { 'title': issue['title'].capitalize().rstrip('.'), 'number': issue['number'], 'tags': ' '.join('[{}]'.format(tag) for tag in tags) + (' ' if tags else '') } return template.format(**params)
python
def issue_line(issue): """Returns log line for given issue.""" template = '#{number} {tags}{title}' tags = issue_tags(issue) params = { 'title': issue['title'].capitalize().rstrip('.'), 'number': issue['number'], 'tags': ' '.join('[{}]'.format(tag) for tag in tags) + (' ' if tags else '') } return template.format(**params)
[ "def", "issue_line", "(", "issue", ")", ":", "template", "=", "'#{number} {tags}{title}'", "tags", "=", "issue_tags", "(", "issue", ")", "params", "=", "{", "'title'", ":", "issue", "[", "'title'", "]", ".", "capitalize", "(", ")", ".", "rstrip", "(", "'.'", ")", ",", "'number'", ":", "issue", "[", "'number'", "]", ",", "'tags'", ":", "' '", ".", "join", "(", "'[{}]'", ".", "format", "(", "tag", ")", "for", "tag", "in", "tags", ")", "+", "(", "' '", "if", "tags", "else", "''", ")", "}", "return", "template", ".", "format", "(", "*", "*", "params", ")" ]
Returns log line for given issue.
[ "Returns", "log", "line", "for", "given", "issue", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L286-L295
train
bokeh/bokeh
scripts/issues.py
generate_changelog
def generate_changelog(issues, after, heading, rtag=False): """Prints out changelog.""" relevent = relevant_issues(issues, after) relevent = sorted(relevent, key=ISSUES_BY_SECTION) def write(func, endofline="", append=""): func(heading + '\n' + '-' * 20 + endofline) for section, issue_group in groupby(relevent, key=ISSUES_BY_SECTION): func(' * {}:'.format(section) + endofline) for issue in reversed(list(issue_group)): func(' - {}'.format(issue_line(issue)) + endofline) func(endofline + append) if rtag is not False: with open("../CHANGELOG", "r+") as f: content = f.read() f.seek(0) write(f.write, '\n', content) else: write(print)
python
def generate_changelog(issues, after, heading, rtag=False): """Prints out changelog.""" relevent = relevant_issues(issues, after) relevent = sorted(relevent, key=ISSUES_BY_SECTION) def write(func, endofline="", append=""): func(heading + '\n' + '-' * 20 + endofline) for section, issue_group in groupby(relevent, key=ISSUES_BY_SECTION): func(' * {}:'.format(section) + endofline) for issue in reversed(list(issue_group)): func(' - {}'.format(issue_line(issue)) + endofline) func(endofline + append) if rtag is not False: with open("../CHANGELOG", "r+") as f: content = f.read() f.seek(0) write(f.write, '\n', content) else: write(print)
[ "def", "generate_changelog", "(", "issues", ",", "after", ",", "heading", ",", "rtag", "=", "False", ")", ":", "relevent", "=", "relevant_issues", "(", "issues", ",", "after", ")", "relevent", "=", "sorted", "(", "relevent", ",", "key", "=", "ISSUES_BY_SECTION", ")", "def", "write", "(", "func", ",", "endofline", "=", "\"\"", ",", "append", "=", "\"\"", ")", ":", "func", "(", "heading", "+", "'\\n'", "+", "'-'", "*", "20", "+", "endofline", ")", "for", "section", ",", "issue_group", "in", "groupby", "(", "relevent", ",", "key", "=", "ISSUES_BY_SECTION", ")", ":", "func", "(", "' * {}:'", ".", "format", "(", "section", ")", "+", "endofline", ")", "for", "issue", "in", "reversed", "(", "list", "(", "issue_group", ")", ")", ":", "func", "(", "' - {}'", ".", "format", "(", "issue_line", "(", "issue", ")", ")", "+", "endofline", ")", "func", "(", "endofline", "+", "append", ")", "if", "rtag", "is", "not", "False", ":", "with", "open", "(", "\"../CHANGELOG\"", ",", "\"r+\"", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "f", ".", "seek", "(", "0", ")", "write", "(", "f", ".", "write", ",", "'\\n'", ",", "content", ")", "else", ":", "write", "(", "print", ")" ]
Prints out changelog.
[ "Prints", "out", "changelog", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L298-L317
train
bokeh/bokeh
bokeh/colors/rgb.py
RGB.copy
def copy(self): ''' Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB` ''' return RGB(self.r, self.g, self.b, self.a)
python
def copy(self): ''' Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB` ''' return RGB(self.r, self.g, self.b, self.a)
[ "def", "copy", "(", "self", ")", ":", "return", "RGB", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ",", "self", ".", "a", ")" ]
Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB`
[ "Return", "a", "copy", "of", "this", "color", "value", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/rgb.py#L73-L80
train
bokeh/bokeh
bokeh/colors/rgb.py
RGB.to_css
def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: return "rgb(%d, %d, %d)" % (self.r, self.g, self.b) else: return "rgba(%d, %d, %d, %s)" % (self.r, self.g, self.b, self.a)
python
def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: return "rgb(%d, %d, %d)" % (self.r, self.g, self.b) else: return "rgba(%d, %d, %d, %s)" % (self.r, self.g, self.b, self.a)
[ "def", "to_css", "(", "self", ")", ":", "if", "self", ".", "a", "==", "1.0", ":", "return", "\"rgb(%d, %d, %d)\"", "%", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ")", "else", ":", "return", "\"rgba(%d, %d, %d, %s)\"", "%", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ",", "self", ".", "a", ")" ]
Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"``
[ "Generate", "the", "CSS", "representation", "of", "this", "RGB", "color", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/rgb.py#L110-L120
train
bokeh/bokeh
bokeh/colors/rgb.py
RGB.to_hsl
def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ''' from .hsl import HSL # prevent circular import h, l, s = colorsys.rgb_to_hls(float(self.r)/255, float(self.g)/255, float(self.b)/255) return HSL(round(h*360), s, l, self.a)
python
def to_hsl(self): ''' Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB` ''' from .hsl import HSL # prevent circular import h, l, s = colorsys.rgb_to_hls(float(self.r)/255, float(self.g)/255, float(self.b)/255) return HSL(round(h*360), s, l, self.a)
[ "def", "to_hsl", "(", "self", ")", ":", "from", ".", "hsl", "import", "HSL", "# prevent circular import", "h", ",", "l", ",", "s", "=", "colorsys", ".", "rgb_to_hls", "(", "float", "(", "self", ".", "r", ")", "/", "255", ",", "float", "(", "self", ".", "g", ")", "/", "255", ",", "float", "(", "self", ".", "b", ")", "/", "255", ")", "return", "HSL", "(", "round", "(", "h", "*", "360", ")", ",", "s", ",", "l", ",", "self", ".", "a", ")" ]
Return a corresponding HSL color for this RGB color. Returns: :class:`~bokeh.colors.rgb.RGB`
[ "Return", "a", "corresponding", "HSL", "color", "for", "this", "RGB", "color", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/rgb.py#L134-L143
train
bokeh/bokeh
bokeh/util/tornado.py
yield_for_all_futures
def yield_for_all_futures(result): """ Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on. """ while True: # This is needed for Tornado >= 4.5 where convert_yielded will no # longer raise BadYieldError on None if result is None: break try: future = gen.convert_yielded(result) except gen.BadYieldError: # result is not a yieldable thing, we are done break else: result = yield future raise gen.Return(result)
python
def yield_for_all_futures(result): """ Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on. """ while True: # This is needed for Tornado >= 4.5 where convert_yielded will no # longer raise BadYieldError on None if result is None: break try: future = gen.convert_yielded(result) except gen.BadYieldError: # result is not a yieldable thing, we are done break else: result = yield future raise gen.Return(result)
[ "def", "yield_for_all_futures", "(", "result", ")", ":", "while", "True", ":", "# This is needed for Tornado >= 4.5 where convert_yielded will no", "# longer raise BadYieldError on None", "if", "result", "is", "None", ":", "break", "try", ":", "future", "=", "gen", ".", "convert_yielded", "(", "result", ")", "except", "gen", ".", "BadYieldError", ":", "# result is not a yieldable thing, we are done", "break", "else", ":", "result", "=", "yield", "future", "raise", "gen", ".", "Return", "(", "result", ")" ]
Converts result into a Future by collapsing any futures inside result. If result is a Future we yield until it's done, then if the value inside the Future is another Future we yield until it's done as well, and so on.
[ "Converts", "result", "into", "a", "Future", "by", "collapsing", "any", "futures", "inside", "result", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/tornado.py#L49-L70
train
bokeh/bokeh
bokeh/util/tornado.py
_CallbackGroup.remove_all_callbacks
def remove_all_callbacks(self): """ Removes all registered callbacks.""" for cb_id in list(self._next_tick_callback_removers.keys()): self.remove_next_tick_callback(cb_id) for cb_id in list(self._timeout_callback_removers.keys()): self.remove_timeout_callback(cb_id) for cb_id in list(self._periodic_callback_removers.keys()): self.remove_periodic_callback(cb_id)
python
def remove_all_callbacks(self): """ Removes all registered callbacks.""" for cb_id in list(self._next_tick_callback_removers.keys()): self.remove_next_tick_callback(cb_id) for cb_id in list(self._timeout_callback_removers.keys()): self.remove_timeout_callback(cb_id) for cb_id in list(self._periodic_callback_removers.keys()): self.remove_periodic_callback(cb_id)
[ "def", "remove_all_callbacks", "(", "self", ")", ":", "for", "cb_id", "in", "list", "(", "self", ".", "_next_tick_callback_removers", ".", "keys", "(", ")", ")", ":", "self", ".", "remove_next_tick_callback", "(", "cb_id", ")", "for", "cb_id", "in", "list", "(", "self", ".", "_timeout_callback_removers", ".", "keys", "(", ")", ")", ":", "self", ".", "remove_timeout_callback", "(", "cb_id", ")", "for", "cb_id", "in", "list", "(", "self", ".", "_periodic_callback_removers", ".", "keys", "(", ")", ")", ":", "self", ".", "remove_periodic_callback", "(", "cb_id", ")" ]
Removes all registered callbacks.
[ "Removes", "all", "registered", "callbacks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/tornado.py#L164-L171
train
bokeh/bokeh
bokeh/util/tornado.py
_CallbackGroup.add_next_tick_callback
def add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback.""" def wrapper(*args, **kwargs): # this 'removed' flag is a hack because Tornado has no way # to remove a "next tick" callback added with # IOLoop.add_callback. So instead we make our wrapper skip # invoking the callback. if not wrapper.removed: self.remove_next_tick_callback(callback_id) return callback(*args, **kwargs) else: return None wrapper.removed = False def remover(): wrapper.removed = True callback_id = self._assign_remover(callback, callback_id, self._next_tick_callback_removers, remover) self._loop.add_callback(wrapper) return callback_id
python
def add_next_tick_callback(self, callback, callback_id=None): """ Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback.""" def wrapper(*args, **kwargs): # this 'removed' flag is a hack because Tornado has no way # to remove a "next tick" callback added with # IOLoop.add_callback. So instead we make our wrapper skip # invoking the callback. if not wrapper.removed: self.remove_next_tick_callback(callback_id) return callback(*args, **kwargs) else: return None wrapper.removed = False def remover(): wrapper.removed = True callback_id = self._assign_remover(callback, callback_id, self._next_tick_callback_removers, remover) self._loop.add_callback(wrapper) return callback_id
[ "def", "add_next_tick_callback", "(", "self", ",", "callback", ",", "callback_id", "=", "None", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# this 'removed' flag is a hack because Tornado has no way", "# to remove a \"next tick\" callback added with", "# IOLoop.add_callback. So instead we make our wrapper skip", "# invoking the callback.", "if", "not", "wrapper", ".", "removed", ":", "self", ".", "remove_next_tick_callback", "(", "callback_id", ")", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "None", "wrapper", ".", "removed", "=", "False", "def", "remover", "(", ")", ":", "wrapper", ".", "removed", "=", "True", "callback_id", "=", "self", ".", "_assign_remover", "(", "callback", ",", "callback_id", ",", "self", ".", "_next_tick_callback_removers", ",", "remover", ")", "self", ".", "_loop", ".", "add_callback", "(", "wrapper", ")", "return", "callback_id" ]
Adds a callback to be run on the next tick. Returns an ID that can be used with remove_next_tick_callback.
[ "Adds", "a", "callback", "to", "be", "run", "on", "the", "next", "tick", ".", "Returns", "an", "ID", "that", "can", "be", "used", "with", "remove_next_tick_callback", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/tornado.py#L207-L228
train
bokeh/bokeh
bokeh/util/tornado.py
_CallbackGroup.add_timeout_callback
def add_timeout_callback(self, callback, timeout_milliseconds, callback_id=None): """ Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used with remove_timeout_callback.""" def wrapper(*args, **kwargs): self.remove_timeout_callback(callback_id) return callback(*args, **kwargs) handle = None def remover(): if handle is not None: self._loop.remove_timeout(handle) callback_id = self._assign_remover(callback, callback_id, self._timeout_callback_removers, remover) handle = self._loop.call_later(timeout_milliseconds / 1000.0, wrapper) return callback_id
python
def add_timeout_callback(self, callback, timeout_milliseconds, callback_id=None): """ Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used with remove_timeout_callback.""" def wrapper(*args, **kwargs): self.remove_timeout_callback(callback_id) return callback(*args, **kwargs) handle = None def remover(): if handle is not None: self._loop.remove_timeout(handle) callback_id = self._assign_remover(callback, callback_id, self._timeout_callback_removers, remover) handle = self._loop.call_later(timeout_milliseconds / 1000.0, wrapper) return callback_id
[ "def", "add_timeout_callback", "(", "self", ",", "callback", ",", "timeout_milliseconds", ",", "callback_id", "=", "None", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "remove_timeout_callback", "(", "callback_id", ")", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "handle", "=", "None", "def", "remover", "(", ")", ":", "if", "handle", "is", "not", "None", ":", "self", ".", "_loop", ".", "remove_timeout", "(", "handle", ")", "callback_id", "=", "self", ".", "_assign_remover", "(", "callback", ",", "callback_id", ",", "self", ".", "_timeout_callback_removers", ",", "remover", ")", "handle", "=", "self", ".", "_loop", ".", "call_later", "(", "timeout_milliseconds", "/", "1000.0", ",", "wrapper", ")", "return", "callback_id" ]
Adds a callback to be run once after timeout_milliseconds. Returns an ID that can be used with remove_timeout_callback.
[ "Adds", "a", "callback", "to", "be", "run", "once", "after", "timeout_milliseconds", ".", "Returns", "an", "ID", "that", "can", "be", "used", "with", "remove_timeout_callback", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/tornado.py#L234-L249
train
bokeh/bokeh
bokeh/util/tornado.py
_CallbackGroup.add_periodic_callback
def add_periodic_callback(self, callback, period_milliseconds, callback_id=None): """ Adds a callback to be run every period_milliseconds until it is removed. Returns an ID that can be used with remove_periodic_callback.""" cb = _AsyncPeriodic(callback, period_milliseconds, io_loop=self._loop) callback_id = self._assign_remover(callback, callback_id, self._periodic_callback_removers, cb.stop) cb.start() return callback_id
python
def add_periodic_callback(self, callback, period_milliseconds, callback_id=None): """ Adds a callback to be run every period_milliseconds until it is removed. Returns an ID that can be used with remove_periodic_callback.""" cb = _AsyncPeriodic(callback, period_milliseconds, io_loop=self._loop) callback_id = self._assign_remover(callback, callback_id, self._periodic_callback_removers, cb.stop) cb.start() return callback_id
[ "def", "add_periodic_callback", "(", "self", ",", "callback", ",", "period_milliseconds", ",", "callback_id", "=", "None", ")", ":", "cb", "=", "_AsyncPeriodic", "(", "callback", ",", "period_milliseconds", ",", "io_loop", "=", "self", ".", "_loop", ")", "callback_id", "=", "self", ".", "_assign_remover", "(", "callback", ",", "callback_id", ",", "self", ".", "_periodic_callback_removers", ",", "cb", ".", "stop", ")", "cb", ".", "start", "(", ")", "return", "callback_id" ]
Adds a callback to be run every period_milliseconds until it is removed. Returns an ID that can be used with remove_periodic_callback.
[ "Adds", "a", "callback", "to", "be", "run", "every", "period_milliseconds", "until", "it", "is", "removed", ".", "Returns", "an", "ID", "that", "can", "be", "used", "with", "remove_periodic_callback", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/tornado.py#L255-L262
train
bokeh/bokeh
bokeh/sphinxext/bokeh_github.py
bokeh_commit
def bokeh_commit(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app node = _make_gh_link_node(app, rawtext, 'commit', 'commit ', 'commit', text, options) return [node], []
python
def bokeh_commit(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app node = _make_gh_link_node(app, rawtext, 'commit', 'commit ', 'commit', text, options) return [node], []
[ "def", "bokeh_commit", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "node", "=", "_make_gh_link_node", "(", "app", ",", "rawtext", ",", "'commit'", ",", "'commit '", ",", "'commit'", ",", "text", ",", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty.
[ "Link", "to", "a", "Bokeh", "Github", "issue", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_github.py#L79-L89
train
bokeh/bokeh
bokeh/sphinxext/bokeh_github.py
bokeh_issue
def bokeh_issue(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'Github issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = _make_gh_link_node(app, rawtext, 'issue', '#', 'issues', str(issue_num), options) return [node], []
python
def bokeh_issue(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app try: issue_num = int(text) if issue_num <= 0: raise ValueError except ValueError: msg = inliner.reporter.error( 'Github issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=lineno) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] node = _make_gh_link_node(app, rawtext, 'issue', '#', 'issues', str(issue_num), options) return [node], []
[ "def", "bokeh_issue", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "try", ":", "issue_num", "=", "int", "(", "text", ")", "if", "issue_num", "<=", "0", ":", "raise", "ValueError", "except", "ValueError", ":", "msg", "=", "inliner", ".", "reporter", ".", "error", "(", "'Github issue number must be a number greater than or equal to 1; '", "'\"%s\" is invalid.'", "%", "text", ",", "line", "=", "lineno", ")", "prb", "=", "inliner", ".", "problematic", "(", "rawtext", ",", "rawtext", ",", "msg", ")", "return", "[", "prb", "]", ",", "[", "msg", "]", "node", "=", "_make_gh_link_node", "(", "app", ",", "rawtext", ",", "'issue'", ",", "'#'", ",", "'issues'", ",", "str", "(", "issue_num", ")", ",", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
Link to a Bokeh Github issue. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty.
[ "Link", "to", "a", "Bokeh", "Github", "issue", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_github.py#L91-L111
train
bokeh/bokeh
bokeh/sphinxext/bokeh_github.py
bokeh_tree
def bokeh_tree(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags for releases, or to master otherwise. The link text is simply the URL path supplied, so typical usage might look like: .. code-block:: none All of the examples are located in the :bokeh-tree:`examples` subdirectory of your Bokeh checkout. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app tag = app.env.config['version'] if '-' in tag: tag = 'master' url = "%s/tree/%s/%s" % (_BOKEH_GH, tag, text) options = options or {} set_classes(options) node = nodes.reference(rawtext, text, refuri=url, **options) return [node], []
python
def bokeh_tree(name, rawtext, text, lineno, inliner, options=None, content=None): ''' Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags for releases, or to master otherwise. The link text is simply the URL path supplied, so typical usage might look like: .. code-block:: none All of the examples are located in the :bokeh-tree:`examples` subdirectory of your Bokeh checkout. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. ''' app = inliner.document.settings.env.app tag = app.env.config['version'] if '-' in tag: tag = 'master' url = "%s/tree/%s/%s" % (_BOKEH_GH, tag, text) options = options or {} set_classes(options) node = nodes.reference(rawtext, text, refuri=url, **options) return [node], []
[ "def", "bokeh_tree", "(", "name", ",", "rawtext", ",", "text", ",", "lineno", ",", "inliner", ",", "options", "=", "None", ",", "content", "=", "None", ")", ":", "app", "=", "inliner", ".", "document", ".", "settings", ".", "env", ".", "app", "tag", "=", "app", ".", "env", ".", "config", "[", "'version'", "]", "if", "'-'", "in", "tag", ":", "tag", "=", "'master'", "url", "=", "\"%s/tree/%s/%s\"", "%", "(", "_BOKEH_GH", ",", "tag", ",", "text", ")", "options", "=", "options", "or", "{", "}", "set_classes", "(", "options", ")", "node", "=", "nodes", ".", "reference", "(", "rawtext", ",", "text", ",", "refuri", "=", "url", ",", "*", "*", "options", ")", "return", "[", "node", "]", ",", "[", "]" ]
Link to a URL in the Bokeh GitHub tree, pointing to appropriate tags for releases, or to master otherwise. The link text is simply the URL path supplied, so typical usage might look like: .. code-block:: none All of the examples are located in the :bokeh-tree:`examples` subdirectory of your Bokeh checkout. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty.
[ "Link", "to", "a", "URL", "in", "the", "Bokeh", "GitHub", "tree", "pointing", "to", "appropriate", "tags", "for", "releases", "or", "to", "master", "otherwise", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_github.py#L135-L162
train
bokeh/bokeh
bokeh/sphinxext/bokeh_github.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_role('bokeh-commit', bokeh_commit) app.add_role('bokeh-issue', bokeh_issue) app.add_role('bokeh-pull', bokeh_pull) app.add_role('bokeh-tree', bokeh_tree)
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_role('bokeh-commit', bokeh_commit) app.add_role('bokeh-issue', bokeh_issue) app.add_role('bokeh-pull', bokeh_pull) app.add_role('bokeh-tree', bokeh_tree)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_role", "(", "'bokeh-commit'", ",", "bokeh_commit", ")", "app", ".", "add_role", "(", "'bokeh-issue'", ",", "bokeh_issue", ")", "app", ".", "add_role", "(", "'bokeh-pull'", ",", "bokeh_pull", ")", "app", ".", "add_role", "(", "'bokeh-tree'", ",", "bokeh_tree", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_github.py#L164-L169
train
bokeh/bokeh
bokeh/sphinxext/bokeh_github.py
_make_gh_link_node
def _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None): ''' Return a link to a Bokeh Github resource. Args: app (Sphinx app) : current app rawtext (str) : text being replaced with link node. role (str) : role name kind (str) : resource type (issue, pull, etc.) api_type (str) : type for api link id : (str) : id of the resource to link to options (dict) : options dictionary passed to role function ''' url = "%s/%s/%s" % (_BOKEH_GH, api_type, id) options = options or {} set_classes(options) node = nodes.reference( rawtext, kind + utils.unescape(id), refuri=url, **options) return node
python
def _make_gh_link_node(app, rawtext, role, kind, api_type, id, options=None): ''' Return a link to a Bokeh Github resource. Args: app (Sphinx app) : current app rawtext (str) : text being replaced with link node. role (str) : role name kind (str) : resource type (issue, pull, etc.) api_type (str) : type for api link id : (str) : id of the resource to link to options (dict) : options dictionary passed to role function ''' url = "%s/%s/%s" % (_BOKEH_GH, api_type, id) options = options or {} set_classes(options) node = nodes.reference( rawtext, kind + utils.unescape(id), refuri=url, **options) return node
[ "def", "_make_gh_link_node", "(", "app", ",", "rawtext", ",", "role", ",", "kind", ",", "api_type", ",", "id", ",", "options", "=", "None", ")", ":", "url", "=", "\"%s/%s/%s\"", "%", "(", "_BOKEH_GH", ",", "api_type", ",", "id", ")", "options", "=", "options", "or", "{", "}", "set_classes", "(", "options", ")", "node", "=", "nodes", ".", "reference", "(", "rawtext", ",", "kind", "+", "utils", ".", "unescape", "(", "id", ")", ",", "refuri", "=", "url", ",", "*", "*", "options", ")", "return", "node" ]
Return a link to a Bokeh Github resource. Args: app (Sphinx app) : current app rawtext (str) : text being replaced with link node. role (str) : role name kind (str) : resource type (issue, pull, etc.) api_type (str) : type for api link id : (str) : id of the resource to link to options (dict) : options dictionary passed to role function
[ "Return", "a", "link", "to", "a", "Bokeh", "Github", "resource", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_github.py#L177-L195
train
bokeh/bokeh
bokeh/document/events.py
DocumentPatchedEvent.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._document_patched(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._document_patched(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "DocumentPatchedEvent", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_document_patched'", ")", ":", "receiver", ".", "_document_patched", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L118-L126
train
bokeh/bokeh
bokeh/document/events.py
ModelChangedEvent.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists. ''' super(ModelChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_model_changed'): receiver._document_model_changed(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists. ''' super(ModelChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_model_changed'): receiver._document_model_changed(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "ModelChangedEvent", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_document_model_changed'", ")", ":", "receiver", ".", "_document_model_changed", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L237-L246
train
bokeh/bokeh
bokeh/document/events.py
ModelChangedEvent.generate
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' from ..model import collect_models if self.hint is not None: return self.hint.generate(references, buffers) value = self.serializable_new # the new value is an object that may have # not-yet-in-the-remote-doc references, and may also # itself not be in the remote doc yet. the remote may # already have some of the references, but # unfortunately we don't have an easy way to know # unless we were to check BEFORE the attr gets changed # (we need the old _all_models before setting the # property). So we have to send all the references the # remote could need, even though it could be inefficient. # If it turns out we need to fix this we could probably # do it by adding some complexity. value_refs = set(collect_models(value)) # we know we don't want a whole new copy of the obj we're patching # unless it's also the new value if self.model != value: value_refs.discard(self.model) references.update(value_refs) return { 'kind' : 'ModelChanged', 'model' : self.model.ref, 'attr' : self.attr, 'new' : value }
python
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' from ..model import collect_models if self.hint is not None: return self.hint.generate(references, buffers) value = self.serializable_new # the new value is an object that may have # not-yet-in-the-remote-doc references, and may also # itself not be in the remote doc yet. the remote may # already have some of the references, but # unfortunately we don't have an easy way to know # unless we were to check BEFORE the attr gets changed # (we need the old _all_models before setting the # property). So we have to send all the references the # remote could need, even though it could be inefficient. # If it turns out we need to fix this we could probably # do it by adding some complexity. value_refs = set(collect_models(value)) # we know we don't want a whole new copy of the obj we're patching # unless it's also the new value if self.model != value: value_refs.discard(self.model) references.update(value_refs) return { 'kind' : 'ModelChanged', 'model' : self.model.ref, 'attr' : self.attr, 'new' : value }
[ "def", "generate", "(", "self", ",", "references", ",", "buffers", ")", ":", "from", ".", ".", "model", "import", "collect_models", "if", "self", ".", "hint", "is", "not", "None", ":", "return", "self", ".", "hint", ".", "generate", "(", "references", ",", "buffers", ")", "value", "=", "self", ".", "serializable_new", "# the new value is an object that may have", "# not-yet-in-the-remote-doc references, and may also", "# itself not be in the remote doc yet. the remote may", "# already have some of the references, but", "# unfortunately we don't have an easy way to know", "# unless we were to check BEFORE the attr gets changed", "# (we need the old _all_models before setting the", "# property). So we have to send all the references the", "# remote could need, even though it could be inefficient.", "# If it turns out we need to fix this we could probably", "# do it by adding some complexity.", "value_refs", "=", "set", "(", "collect_models", "(", "value", ")", ")", "# we know we don't want a whole new copy of the obj we're patching", "# unless it's also the new value", "if", "self", ".", "model", "!=", "value", ":", "value_refs", ".", "discard", "(", "self", ".", "model", ")", "references", ".", "update", "(", "value_refs", ")", "return", "{", "'kind'", ":", "'ModelChanged'", ",", "'model'", ":", "self", ".", "model", ".", "ref", ",", "'attr'", ":", "self", ".", "attr", ",", "'new'", ":", "value", "}" ]
Create a JSON representation of this event suitable for sending to clients. Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place.
[ "Create", "a", "JSON", "representation", "of", "this", "event", "suitable", "for", "sending", "to", "clients", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L248-L298
train
bokeh/bokeh
bokeh/document/events.py
ColumnDataChangedEvent.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. ''' super(ColumnDataChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_column_data_changed'): receiver._column_data_changed(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists. ''' super(ColumnDataChangedEvent, self).dispatch(receiver) if hasattr(receiver, '_column_data_changed'): receiver._column_data_changed(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "ColumnDataChangedEvent", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_column_data_changed'", ")", ":", "receiver", ".", "_column_data_changed", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._column_data_changed`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L337-L345
train
bokeh/bokeh
bokeh/document/events.py
ColumnDataChangedEvent.generate
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnDataChanged' 'column_source' : <reference to a CDS> 'new' : <new data to steam to column_source> 'cols' : <specific columns to update> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' from ..util.serialization import transform_column_source_data data_dict = transform_column_source_data(self.column_source.data, buffers=buffers, cols=self.cols) return { 'kind' : 'ColumnDataChanged', 'column_source' : self.column_source.ref, 'new' : data_dict, 'cols' : self.cols}
python
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnDataChanged' 'column_source' : <reference to a CDS> 'new' : <new data to steam to column_source> 'cols' : <specific columns to update> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' from ..util.serialization import transform_column_source_data data_dict = transform_column_source_data(self.column_source.data, buffers=buffers, cols=self.cols) return { 'kind' : 'ColumnDataChanged', 'column_source' : self.column_source.ref, 'new' : data_dict, 'cols' : self.cols}
[ "def", "generate", "(", "self", ",", "references", ",", "buffers", ")", ":", "from", ".", ".", "util", ".", "serialization", "import", "transform_column_source_data", "data_dict", "=", "transform_column_source_data", "(", "self", ".", "column_source", ".", "data", ",", "buffers", "=", "buffers", ",", "cols", "=", "self", ".", "cols", ")", "return", "{", "'kind'", ":", "'ColumnDataChanged'", ",", "'column_source'", ":", "self", ".", "column_source", ".", "ref", ",", "'new'", ":", "data_dict", ",", "'cols'", ":", "self", ".", "cols", "}" ]
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnDataChanged' 'column_source' : <reference to a CDS> 'new' : <new data to steam to column_source> 'cols' : <specific columns to update> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place.
[ "Create", "a", "JSON", "representation", "of", "this", "event", "suitable", "for", "sending", "to", "clients", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L347-L384
train
bokeh/bokeh
bokeh/document/events.py
ColumnsStreamedEvent.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists. ''' super(ColumnsStreamedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_streamed'): receiver._columns_streamed(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists. ''' super(ColumnsStreamedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_streamed'): receiver._columns_streamed(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "ColumnsStreamedEvent", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_columns_streamed'", ")", ":", "receiver", ".", "_columns_streamed", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_streamed`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L434-L442
train
bokeh/bokeh
bokeh/document/events.py
ColumnsStreamedEvent.generate
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnsStreamed' 'column_source' : <reference to a CDS> 'data' : <new data to steam to column_source> 'rollover' : <rollover limit> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' return { 'kind' : 'ColumnsStreamed', 'column_source' : self.column_source.ref, 'data' : self.data, 'rollover' : self.rollover }
python
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnsStreamed' 'column_source' : <reference to a CDS> 'data' : <new data to steam to column_source> 'rollover' : <rollover limit> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' return { 'kind' : 'ColumnsStreamed', 'column_source' : self.column_source.ref, 'data' : self.data, 'rollover' : self.rollover }
[ "def", "generate", "(", "self", ",", "references", ",", "buffers", ")", ":", "return", "{", "'kind'", ":", "'ColumnsStreamed'", ",", "'column_source'", ":", "self", ".", "column_source", ".", "ref", ",", "'data'", ":", "self", ".", "data", ",", "'rollover'", ":", "self", ".", "rollover", "}" ]
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'ColumnsStreamed' 'column_source' : <reference to a CDS> 'data' : <new data to steam to column_source> 'rollover' : <rollover limit> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place.
[ "Create", "a", "JSON", "representation", "of", "this", "event", "suitable", "for", "sending", "to", "clients", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L444-L476
train
bokeh/bokeh
bokeh/document/events.py
ColumnsPatchedEvent.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists. ''' super(ColumnsPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_patched'): receiver._columns_patched(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists. ''' super(ColumnsPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_columns_patched'): receiver._columns_patched(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "ColumnsPatchedEvent", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_columns_patched'", ")", ":", "receiver", ".", "_columns_patched", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._columns_patched`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L513-L521
train
bokeh/bokeh
bokeh/document/events.py
RootAddedEvent.generate
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' references.update(self.model.references()) return { 'kind' : 'RootAdded', 'model' : self.model.ref }
python
def generate(self, references, buffers): ''' Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place. ''' references.update(self.model.references()) return { 'kind' : 'RootAdded', 'model' : self.model.ref }
[ "def", "generate", "(", "self", ",", "references", ",", "buffers", ")", ":", "references", ".", "update", "(", "self", ".", "model", ".", "references", "(", ")", ")", "return", "{", "'kind'", ":", "'RootAdded'", ",", "'model'", ":", "self", ".", "model", ".", "ref", "}" ]
Create a JSON representation of this event suitable for sending to clients. .. code-block:: python { 'kind' : 'RootAdded' 'title' : <reference to a Model> } Args: references (dict[str, Model]) : If the event requires references to certain models in order to function, they may be collected here. **This is an "out" parameter**. The values it contains will be modified in-place. buffers (set) : If the event needs to supply any additional Bokeh protocol buffers, they may be added to this set. **This is an "out" parameter**. The values it contains will be modified in-place.
[ "Create", "a", "JSON", "representation", "of", "this", "event", "suitable", "for", "sending", "to", "clients", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L665-L694
train
bokeh/bokeh
bokeh/document/events.py
SessionCallbackAdded.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists. ''' super(SessionCallbackAdded, self).dispatch(receiver) if hasattr(receiver, '_session_callback_added'): receiver._session_callback_added(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists. ''' super(SessionCallbackAdded, self).dispatch(receiver) if hasattr(receiver, '_session_callback_added'): receiver._session_callback_added(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "SessionCallbackAdded", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_session_callback_added'", ")", ":", "receiver", ".", "_session_callback_added", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_added`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L779-L788
train
bokeh/bokeh
bokeh/document/events.py
SessionCallbackRemoved.dispatch
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. ''' super(SessionCallbackRemoved, self).dispatch(receiver) if hasattr(receiver, '_session_callback_removed'): receiver._session_callback_removed(self)
python
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists. ''' super(SessionCallbackRemoved, self).dispatch(receiver) if hasattr(receiver, '_session_callback_removed'): receiver._session_callback_removed(self)
[ "def", "dispatch", "(", "self", ",", "receiver", ")", ":", "super", "(", "SessionCallbackRemoved", ",", "self", ")", ".", "dispatch", "(", "receiver", ")", "if", "hasattr", "(", "receiver", ",", "'_session_callback_removed'", ")", ":", "receiver", ".", "_session_callback_removed", "(", "self", ")" ]
Dispatch handling of this event to a receiver. This method will invoke ``receiver._session_callback_removed`` if it exists.
[ "Dispatch", "handling", "of", "this", "event", "to", "a", "receiver", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/events.py#L811-L820
train
bokeh/bokeh
_setup_support.py
show_bokehjs
def show_bokehjs(bokehjs_action, develop=False): ''' Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree develop (bool, optional) : whether the command was for "develop" mode (default: False) Returns: None ''' print() if develop: print("Installed Bokeh for DEVELOPMENT:") else: print("Installed Bokeh:") if bokehjs_action in ['built', 'installed']: print(" - using %s built BokehJS from bokehjs/build\n" % (bright(yellow("NEWLY")) if bokehjs_action=='built' else bright(yellow("PREVIOUSLY")))) else: print(" - using %s BokehJS, located in 'bokeh.server.static'\n" % bright(yellow("PACKAGED"))) print()
python
def show_bokehjs(bokehjs_action, develop=False): ''' Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree develop (bool, optional) : whether the command was for "develop" mode (default: False) Returns: None ''' print() if develop: print("Installed Bokeh for DEVELOPMENT:") else: print("Installed Bokeh:") if bokehjs_action in ['built', 'installed']: print(" - using %s built BokehJS from bokehjs/build\n" % (bright(yellow("NEWLY")) if bokehjs_action=='built' else bright(yellow("PREVIOUSLY")))) else: print(" - using %s BokehJS, located in 'bokeh.server.static'\n" % bright(yellow("PACKAGED"))) print()
[ "def", "show_bokehjs", "(", "bokehjs_action", ",", "develop", "=", "False", ")", ":", "print", "(", ")", "if", "develop", ":", "print", "(", "\"Installed Bokeh for DEVELOPMENT:\"", ")", "else", ":", "print", "(", "\"Installed Bokeh:\"", ")", "if", "bokehjs_action", "in", "[", "'built'", ",", "'installed'", "]", ":", "print", "(", "\" - using %s built BokehJS from bokehjs/build\\n\"", "%", "(", "bright", "(", "yellow", "(", "\"NEWLY\"", ")", ")", "if", "bokehjs_action", "==", "'built'", "else", "bright", "(", "yellow", "(", "\"PREVIOUSLY\"", ")", ")", ")", ")", "else", ":", "print", "(", "\" - using %s BokehJS, located in 'bokeh.server.static'\\n\"", "%", "bright", "(", "yellow", "(", "\"PACKAGED\"", ")", ")", ")", "print", "(", ")" ]
Print a useful report after setuptools output describing where and how BokehJS is installed. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree develop (bool, optional) : whether the command was for "develop" mode (default: False) Returns: None
[ "Print", "a", "useful", "report", "after", "setuptools", "output", "describing", "where", "and", "how", "BokehJS", "is", "installed", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L50-L74
train
bokeh/bokeh
_setup_support.py
show_help
def show_help(bokehjs_action): ''' Print information about extra Bokeh-specific command line options. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree Returns: None ''' print() if bokehjs_action in ['built', 'installed']: print("Bokeh-specific options available with 'install' or 'develop':") print() print(" --build-js build and install a fresh BokehJS") print(" --install-js install only last previously built BokehJS") else: print("Bokeh is using PACKAGED BokehJS, located in 'bokeh.server.static'") print() print("No extra Bokeh-specific options are available.") print()
python
def show_help(bokehjs_action): ''' Print information about extra Bokeh-specific command line options. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree Returns: None ''' print() if bokehjs_action in ['built', 'installed']: print("Bokeh-specific options available with 'install' or 'develop':") print() print(" --build-js build and install a fresh BokehJS") print(" --install-js install only last previously built BokehJS") else: print("Bokeh is using PACKAGED BokehJS, located in 'bokeh.server.static'") print() print("No extra Bokeh-specific options are available.") print()
[ "def", "show_help", "(", "bokehjs_action", ")", ":", "print", "(", ")", "if", "bokehjs_action", "in", "[", "'built'", ",", "'installed'", "]", ":", "print", "(", "\"Bokeh-specific options available with 'install' or 'develop':\"", ")", "print", "(", ")", "print", "(", "\" --build-js build and install a fresh BokehJS\"", ")", "print", "(", "\" --install-js install only last previously built BokehJS\"", ")", "else", ":", "print", "(", "\"Bokeh is using PACKAGED BokehJS, located in 'bokeh.server.static'\"", ")", "print", "(", ")", "print", "(", "\"No extra Bokeh-specific options are available.\"", ")", "print", "(", ")" ]
Print information about extra Bokeh-specific command line options. Args: bokehjs_action (str) : one of 'built', 'installed', or 'packaged' how (or if) BokehJS was installed into the python source tree Returns: None
[ "Print", "information", "about", "extra", "Bokeh", "-", "specific", "command", "line", "options", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L76-L97
train
bokeh/bokeh
_setup_support.py
build_or_install_bokehjs
def build_or_install_bokehjs(): ''' Build a new BokehJS (and install it) or install a previously build BokehJS. If no options ``--build-js`` or ``--install-js`` are detected, the user is prompted for what to do. If ``--existing-js`` is detected, then this setup.py is being run from a packaged sdist, no action is taken. Note that ``-build-js`` is only compatible with the following ``setup.py`` commands: install, develop, sdist, egg_info, build Returns: str : one of 'built', 'installed', 'packaged' How (or if) BokehJS was installed into the python source tree ''' # This happens when building from inside a published, pre-packaged sdist # The --existing-js option is not otherwise documented if '--existing-js' in sys.argv: sys.argv.remove('--existing-js') return "packaged" if '--build-js' not in sys.argv and '--install-js' not in sys.argv: jsbuild = jsbuild_prompt() elif '--build-js' in sys.argv: jsbuild = True sys.argv.remove('--build-js') # must be "--install-js" else: jsbuild = False sys.argv.remove('--install-js') jsbuild_ok = ('install', 'develop', 'sdist', 'egg_info', 'build') if jsbuild and not any(arg in sys.argv for arg in jsbuild_ok): print("Error: Option '--build-js' only valid with 'install', 'develop', 'sdist', or 'build', exiting.") sys.exit(1) if jsbuild: build_js() install_js() return "built" else: install_js() return "installed"
python
def build_or_install_bokehjs(): ''' Build a new BokehJS (and install it) or install a previously build BokehJS. If no options ``--build-js`` or ``--install-js`` are detected, the user is prompted for what to do. If ``--existing-js`` is detected, then this setup.py is being run from a packaged sdist, no action is taken. Note that ``-build-js`` is only compatible with the following ``setup.py`` commands: install, develop, sdist, egg_info, build Returns: str : one of 'built', 'installed', 'packaged' How (or if) BokehJS was installed into the python source tree ''' # This happens when building from inside a published, pre-packaged sdist # The --existing-js option is not otherwise documented if '--existing-js' in sys.argv: sys.argv.remove('--existing-js') return "packaged" if '--build-js' not in sys.argv and '--install-js' not in sys.argv: jsbuild = jsbuild_prompt() elif '--build-js' in sys.argv: jsbuild = True sys.argv.remove('--build-js') # must be "--install-js" else: jsbuild = False sys.argv.remove('--install-js') jsbuild_ok = ('install', 'develop', 'sdist', 'egg_info', 'build') if jsbuild and not any(arg in sys.argv for arg in jsbuild_ok): print("Error: Option '--build-js' only valid with 'install', 'develop', 'sdist', or 'build', exiting.") sys.exit(1) if jsbuild: build_js() install_js() return "built" else: install_js() return "installed"
[ "def", "build_or_install_bokehjs", "(", ")", ":", "# This happens when building from inside a published, pre-packaged sdist", "# The --existing-js option is not otherwise documented", "if", "'--existing-js'", "in", "sys", ".", "argv", ":", "sys", ".", "argv", ".", "remove", "(", "'--existing-js'", ")", "return", "\"packaged\"", "if", "'--build-js'", "not", "in", "sys", ".", "argv", "and", "'--install-js'", "not", "in", "sys", ".", "argv", ":", "jsbuild", "=", "jsbuild_prompt", "(", ")", "elif", "'--build-js'", "in", "sys", ".", "argv", ":", "jsbuild", "=", "True", "sys", ".", "argv", ".", "remove", "(", "'--build-js'", ")", "# must be \"--install-js\"", "else", ":", "jsbuild", "=", "False", "sys", ".", "argv", ".", "remove", "(", "'--install-js'", ")", "jsbuild_ok", "=", "(", "'install'", ",", "'develop'", ",", "'sdist'", ",", "'egg_info'", ",", "'build'", ")", "if", "jsbuild", "and", "not", "any", "(", "arg", "in", "sys", ".", "argv", "for", "arg", "in", "jsbuild_ok", ")", ":", "print", "(", "\"Error: Option '--build-js' only valid with 'install', 'develop', 'sdist', or 'build', exiting.\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "jsbuild", ":", "build_js", "(", ")", "install_js", "(", ")", "return", "\"built\"", "else", ":", "install_js", "(", ")", "return", "\"installed\"" ]
Build a new BokehJS (and install it) or install a previously build BokehJS. If no options ``--build-js`` or ``--install-js`` are detected, the user is prompted for what to do. If ``--existing-js`` is detected, then this setup.py is being run from a packaged sdist, no action is taken. Note that ``-build-js`` is only compatible with the following ``setup.py`` commands: install, develop, sdist, egg_info, build Returns: str : one of 'built', 'installed', 'packaged' How (or if) BokehJS was installed into the python source tree
[ "Build", "a", "new", "BokehJS", "(", "and", "install", "it", ")", "or", "install", "a", "previously", "build", "BokehJS", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L103-L151
train
bokeh/bokeh
_setup_support.py
fixup_building_sdist
def fixup_building_sdist(): ''' Check for 'sdist' and ensure we always build BokehJS when packaging Source distributions do not ship with BokehJS source code, but must ship with a pre-built BokehJS library. This function modifies ``sys.argv`` as necessary so that ``--build-js`` IS present, and ``--install-js` is NOT. Returns: None ''' if "sdist" in sys.argv: if "--install-js" in sys.argv: print("Removing '--install-js' incompatible with 'sdist'") sys.argv.remove('--install-js') if "--build-js" not in sys.argv: print("Adding '--build-js' required for 'sdist'") sys.argv.append('--build-js')
python
def fixup_building_sdist(): ''' Check for 'sdist' and ensure we always build BokehJS when packaging Source distributions do not ship with BokehJS source code, but must ship with a pre-built BokehJS library. This function modifies ``sys.argv`` as necessary so that ``--build-js`` IS present, and ``--install-js` is NOT. Returns: None ''' if "sdist" in sys.argv: if "--install-js" in sys.argv: print("Removing '--install-js' incompatible with 'sdist'") sys.argv.remove('--install-js') if "--build-js" not in sys.argv: print("Adding '--build-js' required for 'sdist'") sys.argv.append('--build-js')
[ "def", "fixup_building_sdist", "(", ")", ":", "if", "\"sdist\"", "in", "sys", ".", "argv", ":", "if", "\"--install-js\"", "in", "sys", ".", "argv", ":", "print", "(", "\"Removing '--install-js' incompatible with 'sdist'\"", ")", "sys", ".", "argv", ".", "remove", "(", "'--install-js'", ")", "if", "\"--build-js\"", "not", "in", "sys", ".", "argv", ":", "print", "(", "\"Adding '--build-js' required for 'sdist'\"", ")", "sys", ".", "argv", ".", "append", "(", "'--build-js'", ")" ]
Check for 'sdist' and ensure we always build BokehJS when packaging Source distributions do not ship with BokehJS source code, but must ship with a pre-built BokehJS library. This function modifies ``sys.argv`` as necessary so that ``--build-js`` IS present, and ``--install-js` is NOT. Returns: None
[ "Check", "for", "sdist", "and", "ensure", "we", "always", "build", "BokehJS", "when", "packaging" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L157-L174
train
bokeh/bokeh
_setup_support.py
fixup_for_packaged
def fixup_for_packaged(): ''' If we are installing FROM an sdist, then a pre-built BokehJS is already installed in the python source tree. The command line options ``--build-js`` or ``--install-js`` are removed from ``sys.argv``, with a warning. Also adds ``--existing-js`` to ``sys.argv`` to signal that BokehJS is already packaged. Returns: None ''' if exists(join(ROOT, 'PKG-INFO')): if "--build-js" in sys.argv or "--install-js" in sys.argv: print(SDIST_BUILD_WARNING) if "--build-js" in sys.argv: sys.argv.remove('--build-js') if "--install-js" in sys.argv: sys.argv.remove('--install-js') if "--existing-js" not in sys.argv: sys.argv.append('--existing-js')
python
def fixup_for_packaged(): ''' If we are installing FROM an sdist, then a pre-built BokehJS is already installed in the python source tree. The command line options ``--build-js`` or ``--install-js`` are removed from ``sys.argv``, with a warning. Also adds ``--existing-js`` to ``sys.argv`` to signal that BokehJS is already packaged. Returns: None ''' if exists(join(ROOT, 'PKG-INFO')): if "--build-js" in sys.argv or "--install-js" in sys.argv: print(SDIST_BUILD_WARNING) if "--build-js" in sys.argv: sys.argv.remove('--build-js') if "--install-js" in sys.argv: sys.argv.remove('--install-js') if "--existing-js" not in sys.argv: sys.argv.append('--existing-js')
[ "def", "fixup_for_packaged", "(", ")", ":", "if", "exists", "(", "join", "(", "ROOT", ",", "'PKG-INFO'", ")", ")", ":", "if", "\"--build-js\"", "in", "sys", ".", "argv", "or", "\"--install-js\"", "in", "sys", ".", "argv", ":", "print", "(", "SDIST_BUILD_WARNING", ")", "if", "\"--build-js\"", "in", "sys", ".", "argv", ":", "sys", ".", "argv", ".", "remove", "(", "'--build-js'", ")", "if", "\"--install-js\"", "in", "sys", ".", "argv", ":", "sys", ".", "argv", ".", "remove", "(", "'--install-js'", ")", "if", "\"--existing-js\"", "not", "in", "sys", ".", "argv", ":", "sys", ".", "argv", ".", "append", "(", "'--existing-js'", ")" ]
If we are installing FROM an sdist, then a pre-built BokehJS is already installed in the python source tree. The command line options ``--build-js`` or ``--install-js`` are removed from ``sys.argv``, with a warning. Also adds ``--existing-js`` to ``sys.argv`` to signal that BokehJS is already packaged. Returns: None
[ "If", "we", "are", "installing", "FROM", "an", "sdist", "then", "a", "pre", "-", "built", "BokehJS", "is", "already", "installed", "in", "the", "python", "source", "tree", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L176-L198
train
bokeh/bokeh
_setup_support.py
get_cmdclass
def get_cmdclass(): ''' A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having wheel installed is not a fatal error. ''' cmdclass = versioneer.get_cmdclass() try: from wheel.bdist_wheel import bdist_wheel except ImportError: # pip is not claiming for bdist_wheel when wheel is not installed bdist_wheel = None if bdist_wheel is not None: cmdclass["bdist_wheel"] = bdist_wheel return cmdclass
python
def get_cmdclass(): ''' A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having wheel installed is not a fatal error. ''' cmdclass = versioneer.get_cmdclass() try: from wheel.bdist_wheel import bdist_wheel except ImportError: # pip is not claiming for bdist_wheel when wheel is not installed bdist_wheel = None if bdist_wheel is not None: cmdclass["bdist_wheel"] = bdist_wheel return cmdclass
[ "def", "get_cmdclass", "(", ")", ":", "cmdclass", "=", "versioneer", ".", "get_cmdclass", "(", ")", "try", ":", "from", "wheel", ".", "bdist_wheel", "import", "bdist_wheel", "except", "ImportError", ":", "# pip is not claiming for bdist_wheel when wheel is not installed", "bdist_wheel", "=", "None", "if", "bdist_wheel", "is", "not", "None", ":", "cmdclass", "[", "\"bdist_wheel\"", "]", "=", "bdist_wheel", "return", "cmdclass" ]
A ``cmdclass`` that works around a setuptools deficiency. There is no need to build wheels when installing a package, however some versions of setuptools seem to mandate this. This is a hacky workaround that modifies the ``cmdclass`` returned by versioneer so that not having wheel installed is not a fatal error.
[ "A", "cmdclass", "that", "works", "around", "a", "setuptools", "deficiency", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L203-L223
train
bokeh/bokeh
_setup_support.py
jsbuild_prompt
def jsbuild_prompt(): ''' Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise ''' print(BOKEHJS_BUILD_PROMPT) mapping = {"1": True, "2": False} value = input("Choice? ") while value not in mapping: print("Input '%s' not understood. Valid choices: 1, 2\n" % value) value = input("Choice? ") return mapping[value]
python
def jsbuild_prompt(): ''' Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise ''' print(BOKEHJS_BUILD_PROMPT) mapping = {"1": True, "2": False} value = input("Choice? ") while value not in mapping: print("Input '%s' not understood. Valid choices: 1, 2\n" % value) value = input("Choice? ") return mapping[value]
[ "def", "jsbuild_prompt", "(", ")", ":", "print", "(", "BOKEHJS_BUILD_PROMPT", ")", "mapping", "=", "{", "\"1\"", ":", "True", ",", "\"2\"", ":", "False", "}", "value", "=", "input", "(", "\"Choice? \"", ")", "while", "value", "not", "in", "mapping", ":", "print", "(", "\"Input '%s' not understood. Valid choices: 1, 2\\n\"", "%", "value", ")", "value", "=", "input", "(", "\"Choice? \"", ")", "return", "mapping", "[", "value", "]" ]
Prompt users whether to build a new BokehJS or install an existing one. Returns: bool : True, if a new build is requested, False otherwise
[ "Prompt", "users", "whether", "to", "build", "a", "new", "BokehJS", "or", "install", "an", "existing", "one", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L245-L258
train
bokeh/bokeh
_setup_support.py
build_js
def build_js(): ''' Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them into the python source tree. ''' print("Building BokehJS... ", end="") sys.stdout.flush() os.chdir('bokehjs') cmd = ["node", "make", 'build', '--emit-error'] t0 = time.time() try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as e: print(BUILD_EXEC_FAIL_MSG % (cmd, e)) sys.exit(1) finally: os.chdir('..') result = proc.wait() t1 = time.time() if result != 0: indented_msg = "" outmsg = proc.stdout.read().decode('ascii', errors='ignore') outmsg = "\n".join(" " + x for x in outmsg.split("\n")) errmsg = proc.stderr.read().decode('ascii', errors='ignore') errmsg = "\n".join(" " + x for x in errmsg.split("\n")) print(BUILD_FAIL_MSG % (red(outmsg), red(errmsg))) sys.exit(1) indented_msg = "" msg = proc.stdout.read().decode('ascii', errors='ignore') pat = re.compile(r"(\[.*\]) (.*)", re.DOTALL) for line in msg.strip().split("\n"): m = pat.match(line) if not m: continue # skip generate.py output lines stamp, txt = m.groups() indented_msg += " " + dim(green(stamp)) + " " + dim(txt) + "\n" msg = "\n".join(" " + x for x in msg.split("\n")) print(BUILD_SUCCESS_MSG % indented_msg) print("Build time: %s" % bright(yellow("%0.1f seconds" % (t1-t0)))) print() print("Build artifact sizes:") try: def size(*path): return os.stat(join("bokehjs", "build", *path)).st_size / 2**10 print(" - bokeh.js : %6.1f KB" % size("js", "bokeh.js")) print(" - bokeh.css : %6.1f KB" % size("css", "bokeh.css")) print(" - bokeh.min.js : %6.1f KB" % size("js", "bokeh.min.js")) print(" - bokeh.min.css : %6.1f KB" % size("css", "bokeh.min.css")) print(" - bokeh-widgets.js : %6.1f KB" % size("js", "bokeh-widgets.js")) print(" - bokeh-widgets.css : %6.1f KB" % size("css", "bokeh-widgets.css")) print(" - bokeh-widgets.min.js : %6.1f KB" % size("js", "bokeh-widgets.min.js")) print(" - bokeh-widgets.min.css : %6.1f KB" % size("css", "bokeh-widgets.min.css")) print(" - bokeh-tables.js : %6.1f KB" % size("js", "bokeh-tables.js")) print(" - bokeh-tables.css : %6.1f KB" % size("css", "bokeh-tables.css")) print(" - bokeh-tables.min.js : %6.1f KB" % size("js", "bokeh-tables.min.js")) print(" - bokeh-tables.min.css : %6.1f KB" % size("css", "bokeh-tables.min.css")) print(" - bokeh-api.js : %6.1f KB" % size("js", "bokeh-api.js")) print(" - bokeh-api.min.js : %6.1f KB" % size("js", "bokeh-api.min.js")) except Exception as e: print(BUILD_SIZE_FAIL_MSG % e) sys.exit(1)
python
def build_js(): ''' Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them into the python source tree. ''' print("Building BokehJS... ", end="") sys.stdout.flush() os.chdir('bokehjs') cmd = ["node", "make", 'build', '--emit-error'] t0 = time.time() try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as e: print(BUILD_EXEC_FAIL_MSG % (cmd, e)) sys.exit(1) finally: os.chdir('..') result = proc.wait() t1 = time.time() if result != 0: indented_msg = "" outmsg = proc.stdout.read().decode('ascii', errors='ignore') outmsg = "\n".join(" " + x for x in outmsg.split("\n")) errmsg = proc.stderr.read().decode('ascii', errors='ignore') errmsg = "\n".join(" " + x for x in errmsg.split("\n")) print(BUILD_FAIL_MSG % (red(outmsg), red(errmsg))) sys.exit(1) indented_msg = "" msg = proc.stdout.read().decode('ascii', errors='ignore') pat = re.compile(r"(\[.*\]) (.*)", re.DOTALL) for line in msg.strip().split("\n"): m = pat.match(line) if not m: continue # skip generate.py output lines stamp, txt = m.groups() indented_msg += " " + dim(green(stamp)) + " " + dim(txt) + "\n" msg = "\n".join(" " + x for x in msg.split("\n")) print(BUILD_SUCCESS_MSG % indented_msg) print("Build time: %s" % bright(yellow("%0.1f seconds" % (t1-t0)))) print() print("Build artifact sizes:") try: def size(*path): return os.stat(join("bokehjs", "build", *path)).st_size / 2**10 print(" - bokeh.js : %6.1f KB" % size("js", "bokeh.js")) print(" - bokeh.css : %6.1f KB" % size("css", "bokeh.css")) print(" - bokeh.min.js : %6.1f KB" % size("js", "bokeh.min.js")) print(" - bokeh.min.css : %6.1f KB" % size("css", "bokeh.min.css")) print(" - bokeh-widgets.js : %6.1f KB" % size("js", "bokeh-widgets.js")) print(" - bokeh-widgets.css : %6.1f KB" % size("css", "bokeh-widgets.css")) print(" - bokeh-widgets.min.js : %6.1f KB" % size("js", "bokeh-widgets.min.js")) print(" - bokeh-widgets.min.css : %6.1f KB" % size("css", "bokeh-widgets.min.css")) print(" - bokeh-tables.js : %6.1f KB" % size("js", "bokeh-tables.js")) print(" - bokeh-tables.css : %6.1f KB" % size("css", "bokeh-tables.css")) print(" - bokeh-tables.min.js : %6.1f KB" % size("js", "bokeh-tables.min.js")) print(" - bokeh-tables.min.css : %6.1f KB" % size("css", "bokeh-tables.min.css")) print(" - bokeh-api.js : %6.1f KB" % size("js", "bokeh-api.js")) print(" - bokeh-api.min.js : %6.1f KB" % size("js", "bokeh-api.min.js")) except Exception as e: print(BUILD_SIZE_FAIL_MSG % e) sys.exit(1)
[ "def", "build_js", "(", ")", ":", "print", "(", "\"Building BokehJS... \"", ",", "end", "=", "\"\"", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "os", ".", "chdir", "(", "'bokehjs'", ")", "cmd", "=", "[", "\"node\"", ",", "\"make\"", ",", "'build'", ",", "'--emit-error'", "]", "t0", "=", "time", ".", "time", "(", ")", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "OSError", "as", "e", ":", "print", "(", "BUILD_EXEC_FAIL_MSG", "%", "(", "cmd", ",", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "finally", ":", "os", ".", "chdir", "(", "'..'", ")", "result", "=", "proc", ".", "wait", "(", ")", "t1", "=", "time", ".", "time", "(", ")", "if", "result", "!=", "0", ":", "indented_msg", "=", "\"\"", "outmsg", "=", "proc", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "'ascii'", ",", "errors", "=", "'ignore'", ")", "outmsg", "=", "\"\\n\"", ".", "join", "(", "\" \"", "+", "x", "for", "x", "in", "outmsg", ".", "split", "(", "\"\\n\"", ")", ")", "errmsg", "=", "proc", ".", "stderr", ".", "read", "(", ")", ".", "decode", "(", "'ascii'", ",", "errors", "=", "'ignore'", ")", "errmsg", "=", "\"\\n\"", ".", "join", "(", "\" \"", "+", "x", "for", "x", "in", "errmsg", ".", "split", "(", "\"\\n\"", ")", ")", "print", "(", "BUILD_FAIL_MSG", "%", "(", "red", "(", "outmsg", ")", ",", "red", "(", "errmsg", ")", ")", ")", "sys", ".", "exit", "(", "1", ")", "indented_msg", "=", "\"\"", "msg", "=", "proc", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "'ascii'", ",", "errors", "=", "'ignore'", ")", "pat", "=", "re", ".", "compile", "(", "r\"(\\[.*\\]) (.*)\"", ",", "re", ".", "DOTALL", ")", "for", "line", "in", "msg", ".", "strip", "(", ")", ".", "split", "(", "\"\\n\"", ")", ":", "m", "=", "pat", ".", "match", "(", "line", ")", "if", "not", "m", ":", "continue", "# skip generate.py output lines", "stamp", ",", "txt", "=", "m", ".", "groups", "(", ")", "indented_msg", "+=", "\" \"", "+", "dim", "(", "green", "(", "stamp", ")", ")", "+", "\" \"", "+", "dim", "(", "txt", ")", "+", "\"\\n\"", "msg", "=", "\"\\n\"", ".", "join", "(", "\" \"", "+", "x", "for", "x", "in", "msg", ".", "split", "(", "\"\\n\"", ")", ")", "print", "(", "BUILD_SUCCESS_MSG", "%", "indented_msg", ")", "print", "(", "\"Build time: %s\"", "%", "bright", "(", "yellow", "(", "\"%0.1f seconds\"", "%", "(", "t1", "-", "t0", ")", ")", ")", ")", "print", "(", ")", "print", "(", "\"Build artifact sizes:\"", ")", "try", ":", "def", "size", "(", "*", "path", ")", ":", "return", "os", ".", "stat", "(", "join", "(", "\"bokehjs\"", ",", "\"build\"", ",", "*", "path", ")", ")", ".", "st_size", "/", "2", "**", "10", "print", "(", "\" - bokeh.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh.js\"", ")", ")", "print", "(", "\" - bokeh.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh.css\"", ")", ")", "print", "(", "\" - bokeh.min.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh.min.js\"", ")", ")", "print", "(", "\" - bokeh.min.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh.min.css\"", ")", ")", "print", "(", "\" - bokeh-widgets.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-widgets.js\"", ")", ")", "print", "(", "\" - bokeh-widgets.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh-widgets.css\"", ")", ")", "print", "(", "\" - bokeh-widgets.min.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-widgets.min.js\"", ")", ")", "print", "(", "\" - bokeh-widgets.min.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh-widgets.min.css\"", ")", ")", "print", "(", "\" - bokeh-tables.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-tables.js\"", ")", ")", "print", "(", "\" - bokeh-tables.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh-tables.css\"", ")", ")", "print", "(", "\" - bokeh-tables.min.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-tables.min.js\"", ")", ")", "print", "(", "\" - bokeh-tables.min.css : %6.1f KB\"", "%", "size", "(", "\"css\"", ",", "\"bokeh-tables.min.css\"", ")", ")", "print", "(", "\" - bokeh-api.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-api.js\"", ")", ")", "print", "(", "\" - bokeh-api.min.js : %6.1f KB\"", "%", "size", "(", "\"js\"", ",", "\"bokeh-api.min.js\"", ")", ")", "except", "Exception", "as", "e", ":", "print", "(", "BUILD_SIZE_FAIL_MSG", "%", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them into the python source tree.
[ "Build", "BokehJS", "files", "(", "CSS", "JS", "etc", ")", "under", "the", "bokehjs", "source", "subdirectory", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L264-L338
train
bokeh/bokeh
_setup_support.py
install_js
def install_js(): ''' Copy built BokehJS files into the Python source tree. Returns: None ''' target_jsdir = join(SERVER, 'static', 'js') target_cssdir = join(SERVER, 'static', 'css') target_tslibdir = join(SERVER, 'static', 'lib') STATIC_ASSETS = [ join(JS, 'bokeh.js'), join(JS, 'bokeh.min.js'), join(CSS, 'bokeh.css'), join(CSS, 'bokeh.min.css'), ] if not all(exists(a) for a in STATIC_ASSETS): print(BOKEHJS_INSTALL_FAIL) sys.exit(1) if exists(target_jsdir): shutil.rmtree(target_jsdir) shutil.copytree(JS, target_jsdir) if exists(target_cssdir): shutil.rmtree(target_cssdir) shutil.copytree(CSS, target_cssdir) if exists(target_tslibdir): shutil.rmtree(target_tslibdir) if exists(TSLIB): # keep in sync with bokehjs/src/compiler/compile.ts lib = { "lib.es5.d.ts", "lib.dom.d.ts", "lib.es2015.core.d.ts", "lib.es2015.promise.d.ts", "lib.es2015.symbol.d.ts", "lib.es2015.iterable.d.ts", } shutil.copytree(TSLIB, target_tslibdir, ignore=lambda _, files: [ f for f in files if f not in lib ])
python
def install_js(): ''' Copy built BokehJS files into the Python source tree. Returns: None ''' target_jsdir = join(SERVER, 'static', 'js') target_cssdir = join(SERVER, 'static', 'css') target_tslibdir = join(SERVER, 'static', 'lib') STATIC_ASSETS = [ join(JS, 'bokeh.js'), join(JS, 'bokeh.min.js'), join(CSS, 'bokeh.css'), join(CSS, 'bokeh.min.css'), ] if not all(exists(a) for a in STATIC_ASSETS): print(BOKEHJS_INSTALL_FAIL) sys.exit(1) if exists(target_jsdir): shutil.rmtree(target_jsdir) shutil.copytree(JS, target_jsdir) if exists(target_cssdir): shutil.rmtree(target_cssdir) shutil.copytree(CSS, target_cssdir) if exists(target_tslibdir): shutil.rmtree(target_tslibdir) if exists(TSLIB): # keep in sync with bokehjs/src/compiler/compile.ts lib = { "lib.es5.d.ts", "lib.dom.d.ts", "lib.es2015.core.d.ts", "lib.es2015.promise.d.ts", "lib.es2015.symbol.d.ts", "lib.es2015.iterable.d.ts", } shutil.copytree(TSLIB, target_tslibdir, ignore=lambda _, files: [ f for f in files if f not in lib ])
[ "def", "install_js", "(", ")", ":", "target_jsdir", "=", "join", "(", "SERVER", ",", "'static'", ",", "'js'", ")", "target_cssdir", "=", "join", "(", "SERVER", ",", "'static'", ",", "'css'", ")", "target_tslibdir", "=", "join", "(", "SERVER", ",", "'static'", ",", "'lib'", ")", "STATIC_ASSETS", "=", "[", "join", "(", "JS", ",", "'bokeh.js'", ")", ",", "join", "(", "JS", ",", "'bokeh.min.js'", ")", ",", "join", "(", "CSS", ",", "'bokeh.css'", ")", ",", "join", "(", "CSS", ",", "'bokeh.min.css'", ")", ",", "]", "if", "not", "all", "(", "exists", "(", "a", ")", "for", "a", "in", "STATIC_ASSETS", ")", ":", "print", "(", "BOKEHJS_INSTALL_FAIL", ")", "sys", ".", "exit", "(", "1", ")", "if", "exists", "(", "target_jsdir", ")", ":", "shutil", ".", "rmtree", "(", "target_jsdir", ")", "shutil", ".", "copytree", "(", "JS", ",", "target_jsdir", ")", "if", "exists", "(", "target_cssdir", ")", ":", "shutil", ".", "rmtree", "(", "target_cssdir", ")", "shutil", ".", "copytree", "(", "CSS", ",", "target_cssdir", ")", "if", "exists", "(", "target_tslibdir", ")", ":", "shutil", ".", "rmtree", "(", "target_tslibdir", ")", "if", "exists", "(", "TSLIB", ")", ":", "# keep in sync with bokehjs/src/compiler/compile.ts", "lib", "=", "{", "\"lib.es5.d.ts\"", ",", "\"lib.dom.d.ts\"", ",", "\"lib.es2015.core.d.ts\"", ",", "\"lib.es2015.promise.d.ts\"", ",", "\"lib.es2015.symbol.d.ts\"", ",", "\"lib.es2015.iterable.d.ts\"", ",", "}", "shutil", ".", "copytree", "(", "TSLIB", ",", "target_tslibdir", ",", "ignore", "=", "lambda", "_", ",", "files", ":", "[", "f", "for", "f", "in", "files", "if", "f", "not", "in", "lib", "]", ")" ]
Copy built BokehJS files into the Python source tree. Returns: None
[ "Copy", "built", "BokehJS", "files", "into", "the", "Python", "source", "tree", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/_setup_support.py#L340-L381
train
bokeh/bokeh
bokeh/util/hex.py
axial_to_cartesian
def axial_to_cartesian(q, r, size, orientation, aspect_scale=1): ''' Map axial *(q,r)* coordinates to cartesian *(x,y)* coordinates of tiles centers. This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#hex-to-pixel Args: q (array[float]) : A NumPy array of q-coordinates for binning r (array[float]) : A NumPy array of r-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int]) ''' if orientation == "pointytop": x = size * np.sqrt(3) * (q + r/2.0) / aspect_scale y = -size * 3/2.0 * r else: x = size * 3/2.0 * q y = -size * np.sqrt(3) * (r + q/2.0) * aspect_scale return (x, y)
python
def axial_to_cartesian(q, r, size, orientation, aspect_scale=1): ''' Map axial *(q,r)* coordinates to cartesian *(x,y)* coordinates of tiles centers. This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#hex-to-pixel Args: q (array[float]) : A NumPy array of q-coordinates for binning r (array[float]) : A NumPy array of r-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int]) ''' if orientation == "pointytop": x = size * np.sqrt(3) * (q + r/2.0) / aspect_scale y = -size * 3/2.0 * r else: x = size * 3/2.0 * q y = -size * np.sqrt(3) * (r + q/2.0) * aspect_scale return (x, y)
[ "def", "axial_to_cartesian", "(", "q", ",", "r", ",", "size", ",", "orientation", ",", "aspect_scale", "=", "1", ")", ":", "if", "orientation", "==", "\"pointytop\"", ":", "x", "=", "size", "*", "np", ".", "sqrt", "(", "3", ")", "*", "(", "q", "+", "r", "/", "2.0", ")", "/", "aspect_scale", "y", "=", "-", "size", "*", "3", "/", "2.0", "*", "r", "else", ":", "x", "=", "size", "*", "3", "/", "2.0", "*", "q", "y", "=", "-", "size", "*", "np", ".", "sqrt", "(", "3", ")", "*", "(", "r", "+", "q", "/", "2.0", ")", "*", "aspect_scale", "return", "(", "x", ",", "y", ")" ]
Map axial *(q,r)* coordinates to cartesian *(x,y)* coordinates of tiles centers. This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#hex-to-pixel Args: q (array[float]) : A NumPy array of q-coordinates for binning r (array[float]) : A NumPy array of r-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int])
[ "Map", "axial", "*", "(", "q", "r", ")", "*", "coordinates", "to", "cartesian", "*", "(", "x", "y", ")", "*", "coordinates", "of", "tiles", "centers", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/hex.py#L49-L98
train
bokeh/bokeh
bokeh/util/hex.py
cartesian_to_axial
def cartesian_to_axial(x, y, size, orientation, aspect_scale=1): ''' Map Cartesion *(x,y)* points to axial *(q,r)* coordinates of enclosing tiles. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#pixel-to-hex Args: x (array[float]) : A NumPy array of x-coordinates to convert y (array[float]) : A NumPy array of y-coordinates to convert size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int]) ''' HEX_FLAT = [2.0/3.0, 0.0, -1.0/3.0, np.sqrt(3.0)/3.0] HEX_POINTY = [np.sqrt(3.0)/3.0, -1.0/3.0, 0.0, 2.0/3.0] coords = HEX_FLAT if orientation == 'flattop' else HEX_POINTY x = x / size * (aspect_scale if orientation == "pointytop" else 1) y = -y / size / (aspect_scale if orientation == "flattop" else 1) q = coords[0] * x + coords[1] * y r = coords[2] * x + coords[3] * y return _round_hex(q, r)
python
def cartesian_to_axial(x, y, size, orientation, aspect_scale=1): ''' Map Cartesion *(x,y)* points to axial *(q,r)* coordinates of enclosing tiles. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#pixel-to-hex Args: x (array[float]) : A NumPy array of x-coordinates to convert y (array[float]) : A NumPy array of y-coordinates to convert size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int]) ''' HEX_FLAT = [2.0/3.0, 0.0, -1.0/3.0, np.sqrt(3.0)/3.0] HEX_POINTY = [np.sqrt(3.0)/3.0, -1.0/3.0, 0.0, 2.0/3.0] coords = HEX_FLAT if orientation == 'flattop' else HEX_POINTY x = x / size * (aspect_scale if orientation == "pointytop" else 1) y = -y / size / (aspect_scale if orientation == "flattop" else 1) q = coords[0] * x + coords[1] * y r = coords[2] * x + coords[3] * y return _round_hex(q, r)
[ "def", "cartesian_to_axial", "(", "x", ",", "y", ",", "size", ",", "orientation", ",", "aspect_scale", "=", "1", ")", ":", "HEX_FLAT", "=", "[", "2.0", "/", "3.0", ",", "0.0", ",", "-", "1.0", "/", "3.0", ",", "np", ".", "sqrt", "(", "3.0", ")", "/", "3.0", "]", "HEX_POINTY", "=", "[", "np", ".", "sqrt", "(", "3.0", ")", "/", "3.0", ",", "-", "1.0", "/", "3.0", ",", "0.0", ",", "2.0", "/", "3.0", "]", "coords", "=", "HEX_FLAT", "if", "orientation", "==", "'flattop'", "else", "HEX_POINTY", "x", "=", "x", "/", "size", "*", "(", "aspect_scale", "if", "orientation", "==", "\"pointytop\"", "else", "1", ")", "y", "=", "-", "y", "/", "size", "/", "(", "aspect_scale", "if", "orientation", "==", "\"flattop\"", "else", "1", ")", "q", "=", "coords", "[", "0", "]", "*", "x", "+", "coords", "[", "1", "]", "*", "y", "r", "=", "coords", "[", "2", "]", "*", "x", "+", "coords", "[", "3", "]", "*", "y", "return", "_round_hex", "(", "q", ",", "r", ")" ]
Map Cartesion *(x,y)* points to axial *(q,r)* coordinates of enclosing tiles. This function was adapted from: https://www.redblobgames.com/grids/hexagons/#pixel-to-hex Args: x (array[float]) : A NumPy array of x-coordinates to convert y (array[float]) : A NumPy array of y-coordinates to convert size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str) : Whether the hex tile orientation should be "pointytop" or "flattop". aspect_scale (float, optional) : Scale the hexagons in the "cross" dimension. For "pointytop" orientations, hexagons are scaled in the horizontal direction. For "flattop", they are scaled in vertical direction. When working with a plot with ``aspect_scale != 1``, it may be useful to set this value to match the plot. Returns: (array[int], array[int])
[ "Map", "Cartesion", "*", "(", "x", "y", ")", "*", "points", "to", "axial", "*", "(", "q", "r", ")", "*", "coordinates", "of", "enclosing", "tiles", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/hex.py#L100-L150
train
bokeh/bokeh
bokeh/util/hex.py
hexbin
def hexbin(x, y, size, orientation="pointytop", aspect_scale=1): ''' Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates for binning y (array[float]) : A NumPy array of y-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str, optional) : Whether the hex tile orientation should be "pointytop" or "flattop". (default: "pointytop") aspect_scale (float, optional) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Returns: DataFrame The resulting DataFrame will have columns *q* and *r* that specify hexagon tile locations in axial coordinates, and a column *counts* that provides the count for each tile. .. warning:: Hex binning only functions on linear scales, i.e. not on log plots. ''' pd = import_required('pandas','hexbin requires pandas to be installed') q, r = cartesian_to_axial(x, y, size, orientation, aspect_scale=aspect_scale) df = pd.DataFrame(dict(r=r, q=q)) return df.groupby(['q', 'r']).size().reset_index(name='counts')
python
def hexbin(x, y, size, orientation="pointytop", aspect_scale=1): ''' Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates for binning y (array[float]) : A NumPy array of y-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str, optional) : Whether the hex tile orientation should be "pointytop" or "flattop". (default: "pointytop") aspect_scale (float, optional) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Returns: DataFrame The resulting DataFrame will have columns *q* and *r* that specify hexagon tile locations in axial coordinates, and a column *counts* that provides the count for each tile. .. warning:: Hex binning only functions on linear scales, i.e. not on log plots. ''' pd = import_required('pandas','hexbin requires pandas to be installed') q, r = cartesian_to_axial(x, y, size, orientation, aspect_scale=aspect_scale) df = pd.DataFrame(dict(r=r, q=q)) return df.groupby(['q', 'r']).size().reset_index(name='counts')
[ "def", "hexbin", "(", "x", ",", "y", ",", "size", ",", "orientation", "=", "\"pointytop\"", ",", "aspect_scale", "=", "1", ")", ":", "pd", "=", "import_required", "(", "'pandas'", ",", "'hexbin requires pandas to be installed'", ")", "q", ",", "r", "=", "cartesian_to_axial", "(", "x", ",", "y", ",", "size", ",", "orientation", ",", "aspect_scale", "=", "aspect_scale", ")", "df", "=", "pd", ".", "DataFrame", "(", "dict", "(", "r", "=", "r", ",", "q", "=", "q", ")", ")", "return", "df", ".", "groupby", "(", "[", "'q'", ",", "'r'", "]", ")", ".", "size", "(", ")", ".", "reset_index", "(", "name", "=", "'counts'", ")" ]
Perform an equal-weight binning of data points into hexagonal tiles. For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates for binning y (array[float]) : A NumPy array of y-coordinates for binning size (float) : The size of the hexagonal tiling. The size is defined as the distance from the center of a hexagon to the top corner for "pointytop" orientation, or from the center to a side corner for "flattop" orientation. orientation (str, optional) : Whether the hex tile orientation should be "pointytop" or "flattop". (default: "pointytop") aspect_scale (float, optional) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Returns: DataFrame The resulting DataFrame will have columns *q* and *r* that specify hexagon tile locations in axial coordinates, and a column *counts* that provides the count for each tile. .. warning:: Hex binning only functions on linear scales, i.e. not on log plots.
[ "Perform", "an", "equal", "-", "weight", "binning", "of", "data", "points", "into", "hexagonal", "tiles", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/hex.py#L152-L204
train
bokeh/bokeh
bokeh/util/hex.py
_round_hex
def _round_hex(q, r): ''' Round floating point axial hex coordinates to integer *(q,r)* coordinates. This code was adapted from: https://www.redblobgames.com/grids/hexagons/#rounding Args: q (array[float]) : NumPy array of Floating point axial *q* coordinates to round r (array[float]) : NumPy array of Floating point axial *q* coordinates to round Returns: (array[int], array[int]) ''' x = q z = r y = -x-z rx = np.round(x) ry = np.round(y) rz = np.round(z) dx = np.abs(rx - x) dy = np.abs(ry - y) dz = np.abs(rz - z) cond = (dx > dy) & (dx > dz) q = np.where(cond , -(ry + rz), rx) r = np.where(~cond & ~(dy > dz), -(rx + ry), rz) return q.astype(int), r.astype(int)
python
def _round_hex(q, r): ''' Round floating point axial hex coordinates to integer *(q,r)* coordinates. This code was adapted from: https://www.redblobgames.com/grids/hexagons/#rounding Args: q (array[float]) : NumPy array of Floating point axial *q* coordinates to round r (array[float]) : NumPy array of Floating point axial *q* coordinates to round Returns: (array[int], array[int]) ''' x = q z = r y = -x-z rx = np.round(x) ry = np.round(y) rz = np.round(z) dx = np.abs(rx - x) dy = np.abs(ry - y) dz = np.abs(rz - z) cond = (dx > dy) & (dx > dz) q = np.where(cond , -(ry + rz), rx) r = np.where(~cond & ~(dy > dz), -(rx + ry), rz) return q.astype(int), r.astype(int)
[ "def", "_round_hex", "(", "q", ",", "r", ")", ":", "x", "=", "q", "z", "=", "r", "y", "=", "-", "x", "-", "z", "rx", "=", "np", ".", "round", "(", "x", ")", "ry", "=", "np", ".", "round", "(", "y", ")", "rz", "=", "np", ".", "round", "(", "z", ")", "dx", "=", "np", ".", "abs", "(", "rx", "-", "x", ")", "dy", "=", "np", ".", "abs", "(", "ry", "-", "y", ")", "dz", "=", "np", ".", "abs", "(", "rz", "-", "z", ")", "cond", "=", "(", "dx", ">", "dy", ")", "&", "(", "dx", ">", "dz", ")", "q", "=", "np", ".", "where", "(", "cond", ",", "-", "(", "ry", "+", "rz", ")", ",", "rx", ")", "r", "=", "np", ".", "where", "(", "~", "cond", "&", "~", "(", "dy", ">", "dz", ")", ",", "-", "(", "rx", "+", "ry", ")", ",", "rz", ")", "return", "q", ".", "astype", "(", "int", ")", ",", "r", ".", "astype", "(", "int", ")" ]
Round floating point axial hex coordinates to integer *(q,r)* coordinates. This code was adapted from: https://www.redblobgames.com/grids/hexagons/#rounding Args: q (array[float]) : NumPy array of Floating point axial *q* coordinates to round r (array[float]) : NumPy array of Floating point axial *q* coordinates to round Returns: (array[int], array[int])
[ "Round", "floating", "point", "axial", "hex", "coordinates", "to", "integer", "*", "(", "q", "r", ")", "*", "coordinates", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/hex.py#L214-L249
train
bokeh/bokeh
versioneer.py
versions_from_parentdir
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
python
def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
[ "def", "versions_from_parentdir", "(", "parentdir_prefix", ",", "root", ",", "verbose", ")", ":", "rootdirs", "=", "[", "]", "for", "i", "in", "range", "(", "3", ")", ":", "dirname", "=", "os", ".", "path", ".", "basename", "(", "root", ")", "if", "dirname", ".", "startswith", "(", "parentdir_prefix", ")", ":", "return", "{", "\"version\"", ":", "dirname", "[", "len", "(", "parentdir_prefix", ")", ":", "]", ",", "\"full-revisionid\"", ":", "None", ",", "\"dirty\"", ":", "False", ",", "\"error\"", ":", "None", ",", "\"date\"", ":", "None", "}", "else", ":", "rootdirs", ".", "append", "(", "root", ")", "root", "=", "os", ".", "path", ".", "dirname", "(", "root", ")", "# up a level", "if", "verbose", ":", "print", "(", "\"Tried directories %s but none started with prefix %s\"", "%", "(", "str", "(", "rootdirs", ")", ",", "parentdir_prefix", ")", ")", "raise", "NotThisMethod", "(", "\"rootdir doesn't start with parentdir_prefix\"", ")" ]
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
[ "Try", "to", "determine", "the", "version", "from", "the", "parent", "directory", "name", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/versioneer.py#L1166-L1188
train
bokeh/bokeh
versioneer.py
render_pep440_pre
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered
python
def render_pep440_pre(pieces): """TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered
[ "def", "render_pep440_pre", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\".post.dev%d\"", "%", "pieces", "[", "\"distance\"", "]", "else", ":", "# exception #1", "rendered", "=", "\"0.post.dev%d\"", "%", "pieces", "[", "\"distance\"", "]", "return", "rendered" ]
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
[ "TAG", "[", ".", "post", ".", "devDISTANCE", "]", "--", "No", "-", "dirty", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/versioneer.py#L1268-L1281
train
bokeh/bokeh
bokeh/core/property/container.py
List.wrap
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, list): if isinstance(value, PropertyValueList): return value else: return PropertyValueList(value) else: return value
python
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, list): if isinstance(value, PropertyValueList): return value else: return PropertyValueList(value) else: return value
[ "def", "wrap", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "if", "isinstance", "(", "value", ",", "PropertyValueList", ")", ":", "return", "value", "else", ":", "return", "PropertyValueList", "(", "value", ")", "else", ":", "return", "value" ]
Some property types need to wrap their values in special containers, etc.
[ "Some", "property", "types", "need", "to", "wrap", "their", "values", "in", "special", "containers", "etc", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/container.py#L124-L134
train
bokeh/bokeh
bokeh/core/property/container.py
Dict.wrap
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueDict): return value else: return PropertyValueDict(value) else: return value
python
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueDict): return value else: return PropertyValueDict(value) else: return value
[ "def", "wrap", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "isinstance", "(", "value", ",", "PropertyValueDict", ")", ":", "return", "value", "else", ":", "return", "PropertyValueDict", "(", "value", ")", "else", ":", "return", "value" ]
Some property types need to wrap their values in special containers, etc.
[ "Some", "property", "types", "need", "to", "wrap", "their", "values", "in", "special", "containers", "etc", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/container.py#L193-L203
train
bokeh/bokeh
bokeh/core/property/container.py
ColumnData.from_json
def from_json(self, json, models=None): ''' Decodes column source data encoded as lists or base64 strings. ''' if json is None: return None elif not isinstance(json, dict): raise DeserializationError("%s expected a dict or None, got %s" % (self, json)) new_data = {} for key, value in json.items(): key = self.keys_type.from_json(key, models) if isinstance(value, dict) and '__ndarray__' in value: new_data[key] = decode_base64_dict(value) elif isinstance(value, list) and any(isinstance(el, dict) and '__ndarray__' in el for el in value): new_list = [] for el in value: if isinstance(el, dict) and '__ndarray__' in el: el = decode_base64_dict(el) elif isinstance(el, list): el = self.values_type.from_json(el) new_list.append(el) new_data[key] = new_list else: new_data[key] = self.values_type.from_json(value, models) return new_data
python
def from_json(self, json, models=None): ''' Decodes column source data encoded as lists or base64 strings. ''' if json is None: return None elif not isinstance(json, dict): raise DeserializationError("%s expected a dict or None, got %s" % (self, json)) new_data = {} for key, value in json.items(): key = self.keys_type.from_json(key, models) if isinstance(value, dict) and '__ndarray__' in value: new_data[key] = decode_base64_dict(value) elif isinstance(value, list) and any(isinstance(el, dict) and '__ndarray__' in el for el in value): new_list = [] for el in value: if isinstance(el, dict) and '__ndarray__' in el: el = decode_base64_dict(el) elif isinstance(el, list): el = self.values_type.from_json(el) new_list.append(el) new_data[key] = new_list else: new_data[key] = self.values_type.from_json(value, models) return new_data
[ "def", "from_json", "(", "self", ",", "json", ",", "models", "=", "None", ")", ":", "if", "json", "is", "None", ":", "return", "None", "elif", "not", "isinstance", "(", "json", ",", "dict", ")", ":", "raise", "DeserializationError", "(", "\"%s expected a dict or None, got %s\"", "%", "(", "self", ",", "json", ")", ")", "new_data", "=", "{", "}", "for", "key", ",", "value", "in", "json", ".", "items", "(", ")", ":", "key", "=", "self", ".", "keys_type", ".", "from_json", "(", "key", ",", "models", ")", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "'__ndarray__'", "in", "value", ":", "new_data", "[", "key", "]", "=", "decode_base64_dict", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", "and", "any", "(", "isinstance", "(", "el", ",", "dict", ")", "and", "'__ndarray__'", "in", "el", "for", "el", "in", "value", ")", ":", "new_list", "=", "[", "]", "for", "el", "in", "value", ":", "if", "isinstance", "(", "el", ",", "dict", ")", "and", "'__ndarray__'", "in", "el", ":", "el", "=", "decode_base64_dict", "(", "el", ")", "elif", "isinstance", "(", "el", ",", "list", ")", ":", "el", "=", "self", ".", "values_type", ".", "from_json", "(", "el", ")", "new_list", ".", "append", "(", "el", ")", "new_data", "[", "key", "]", "=", "new_list", "else", ":", "new_data", "[", "key", "]", "=", "self", ".", "values_type", ".", "from_json", "(", "value", ",", "models", ")", "return", "new_data" ]
Decodes column source data encoded as lists or base64 strings.
[ "Decodes", "column", "source", "data", "encoded", "as", "lists", "or", "base64", "strings", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/container.py#L234-L257
train
bokeh/bokeh
bokeh/core/property/container.py
ColumnData.wrap
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueColumnData): return value else: return PropertyValueColumnData(value) else: return value
python
def wrap(cls, value): ''' Some property types need to wrap their values in special containers, etc. ''' if isinstance(value, dict): if isinstance(value, PropertyValueColumnData): return value else: return PropertyValueColumnData(value) else: return value
[ "def", "wrap", "(", "cls", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "isinstance", "(", "value", ",", "PropertyValueColumnData", ")", ":", "return", "value", "else", ":", "return", "PropertyValueColumnData", "(", "value", ")", "else", ":", "return", "value" ]
Some property types need to wrap their values in special containers, etc.
[ "Some", "property", "types", "need", "to", "wrap", "their", "values", "in", "special", "containers", "etc", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/container.py#L263-L273
train
bokeh/bokeh
bokeh/util/serialization.py
convert_timedelta_type
def convert_timedelta_type(obj): ''' Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' if isinstance(obj, dt.timedelta): return obj.total_seconds() * 1000. elif isinstance(obj, np.timedelta64): return (obj / NP_MS_DELTA)
python
def convert_timedelta_type(obj): ''' Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' if isinstance(obj, dt.timedelta): return obj.total_seconds() * 1000. elif isinstance(obj, np.timedelta64): return (obj / NP_MS_DELTA)
[ "def", "convert_timedelta_type", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dt", ".", "timedelta", ")", ":", "return", "obj", ".", "total_seconds", "(", ")", "*", "1000.", "elif", "isinstance", "(", "obj", ",", "np", ".", "timedelta64", ")", ":", "return", "(", "obj", "/", "NP_MS_DELTA", ")" ]
Convert any recognized timedelta value to floating point absolute milliseconds. Arg: obj (object) : the object to convert Returns: float : milliseconds
[ "Convert", "any", "recognized", "timedelta", "value", "to", "floating", "point", "absolute", "milliseconds", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L136-L150
train
bokeh/bokeh
bokeh/util/serialization.py
convert_datetime_type
def convert_datetime_type(obj): ''' Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' # Pandas NaT if pd and obj is pd.NaT: return np.nan # Pandas Period if pd and isinstance(obj, pd.Period): return obj.to_timestamp().value / 10**6.0 # Pandas Timestamp if pd and isinstance(obj, _pd_timestamp): return obj.value / 10**6.0 # Pandas Timedelta elif pd and isinstance(obj, pd.Timedelta): return obj.value / 10**6.0 # Datetime (datetime is a subclass of date) elif isinstance(obj, dt.datetime): diff = obj.replace(tzinfo=None) - DT_EPOCH return diff.total_seconds() * 1000. # Date elif isinstance(obj, dt.date): return (dt.datetime(*obj.timetuple()[:6]) - DT_EPOCH).total_seconds() * 1000 # NumPy datetime64 elif isinstance(obj, np.datetime64): epoch_delta = obj - NP_EPOCH return (epoch_delta / NP_MS_DELTA) # Time elif isinstance(obj, dt.time): return (obj.hour * 3600 + obj.minute * 60 + obj.second) * 1000 + obj.microsecond / 1000.
python
def convert_datetime_type(obj): ''' Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds ''' # Pandas NaT if pd and obj is pd.NaT: return np.nan # Pandas Period if pd and isinstance(obj, pd.Period): return obj.to_timestamp().value / 10**6.0 # Pandas Timestamp if pd and isinstance(obj, _pd_timestamp): return obj.value / 10**6.0 # Pandas Timedelta elif pd and isinstance(obj, pd.Timedelta): return obj.value / 10**6.0 # Datetime (datetime is a subclass of date) elif isinstance(obj, dt.datetime): diff = obj.replace(tzinfo=None) - DT_EPOCH return diff.total_seconds() * 1000. # Date elif isinstance(obj, dt.date): return (dt.datetime(*obj.timetuple()[:6]) - DT_EPOCH).total_seconds() * 1000 # NumPy datetime64 elif isinstance(obj, np.datetime64): epoch_delta = obj - NP_EPOCH return (epoch_delta / NP_MS_DELTA) # Time elif isinstance(obj, dt.time): return (obj.hour * 3600 + obj.minute * 60 + obj.second) * 1000 + obj.microsecond / 1000.
[ "def", "convert_datetime_type", "(", "obj", ")", ":", "# Pandas NaT", "if", "pd", "and", "obj", "is", "pd", ".", "NaT", ":", "return", "np", ".", "nan", "# Pandas Period", "if", "pd", "and", "isinstance", "(", "obj", ",", "pd", ".", "Period", ")", ":", "return", "obj", ".", "to_timestamp", "(", ")", ".", "value", "/", "10", "**", "6.0", "# Pandas Timestamp", "if", "pd", "and", "isinstance", "(", "obj", ",", "_pd_timestamp", ")", ":", "return", "obj", ".", "value", "/", "10", "**", "6.0", "# Pandas Timedelta", "elif", "pd", "and", "isinstance", "(", "obj", ",", "pd", ".", "Timedelta", ")", ":", "return", "obj", ".", "value", "/", "10", "**", "6.0", "# Datetime (datetime is a subclass of date)", "elif", "isinstance", "(", "obj", ",", "dt", ".", "datetime", ")", ":", "diff", "=", "obj", ".", "replace", "(", "tzinfo", "=", "None", ")", "-", "DT_EPOCH", "return", "diff", ".", "total_seconds", "(", ")", "*", "1000.", "# Date", "elif", "isinstance", "(", "obj", ",", "dt", ".", "date", ")", ":", "return", "(", "dt", ".", "datetime", "(", "*", "obj", ".", "timetuple", "(", ")", "[", ":", "6", "]", ")", "-", "DT_EPOCH", ")", ".", "total_seconds", "(", ")", "*", "1000", "# NumPy datetime64", "elif", "isinstance", "(", "obj", ",", "np", ".", "datetime64", ")", ":", "epoch_delta", "=", "obj", "-", "NP_EPOCH", "return", "(", "epoch_delta", "/", "NP_MS_DELTA", ")", "# Time", "elif", "isinstance", "(", "obj", ",", "dt", ".", "time", ")", ":", "return", "(", "obj", ".", "hour", "*", "3600", "+", "obj", ".", "minute", "*", "60", "+", "obj", ".", "second", ")", "*", "1000", "+", "obj", ".", "microsecond", "/", "1000." ]
Convert any recognized date, time, or datetime value to floating point milliseconds since epoch. Arg: obj (object) : the object to convert Returns: float : milliseconds
[ "Convert", "any", "recognized", "date", "time", "or", "datetime", "value", "to", "floating", "point", "milliseconds", "since", "epoch", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L152-L193
train
bokeh/bokeh
bokeh/util/serialization.py
convert_datetime_array
def convert_datetime_array(array): ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array ''' if not isinstance(array, np.ndarray): return array try: dt2001 = np.datetime64('2001') legacy_datetime64 = (dt2001.astype('int64') == dt2001.astype('datetime64[ms]').astype('int64')) except AttributeError as e: if e.args == ("'module' object has no attribute 'datetime64'",): # for compatibility with PyPy that doesn't have datetime64 if 'PyPy' in sys.version: legacy_datetime64 = False pass else: raise e else: raise e # not quite correct, truncates to ms.. if array.dtype.kind == 'M': if legacy_datetime64: if array.dtype == np.dtype('datetime64[ns]'): array = array.astype('int64') / 10**6.0 else: array = array.astype('datetime64[us]').astype('int64') / 1000. elif array.dtype.kind == 'm': array = array.astype('timedelta64[us]').astype('int64') / 1000. return array
python
def convert_datetime_array(array): ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array ''' if not isinstance(array, np.ndarray): return array try: dt2001 = np.datetime64('2001') legacy_datetime64 = (dt2001.astype('int64') == dt2001.astype('datetime64[ms]').astype('int64')) except AttributeError as e: if e.args == ("'module' object has no attribute 'datetime64'",): # for compatibility with PyPy that doesn't have datetime64 if 'PyPy' in sys.version: legacy_datetime64 = False pass else: raise e else: raise e # not quite correct, truncates to ms.. if array.dtype.kind == 'M': if legacy_datetime64: if array.dtype == np.dtype('datetime64[ns]'): array = array.astype('int64') / 10**6.0 else: array = array.astype('datetime64[us]').astype('int64') / 1000. elif array.dtype.kind == 'm': array = array.astype('timedelta64[us]').astype('int64') / 1000. return array
[ "def", "convert_datetime_array", "(", "array", ")", ":", "if", "not", "isinstance", "(", "array", ",", "np", ".", "ndarray", ")", ":", "return", "array", "try", ":", "dt2001", "=", "np", ".", "datetime64", "(", "'2001'", ")", "legacy_datetime64", "=", "(", "dt2001", ".", "astype", "(", "'int64'", ")", "==", "dt2001", ".", "astype", "(", "'datetime64[ms]'", ")", ".", "astype", "(", "'int64'", ")", ")", "except", "AttributeError", "as", "e", ":", "if", "e", ".", "args", "==", "(", "\"'module' object has no attribute 'datetime64'\"", ",", ")", ":", "# for compatibility with PyPy that doesn't have datetime64", "if", "'PyPy'", "in", "sys", ".", "version", ":", "legacy_datetime64", "=", "False", "pass", "else", ":", "raise", "e", "else", ":", "raise", "e", "# not quite correct, truncates to ms..", "if", "array", ".", "dtype", ".", "kind", "==", "'M'", ":", "if", "legacy_datetime64", ":", "if", "array", ".", "dtype", "==", "np", ".", "dtype", "(", "'datetime64[ns]'", ")", ":", "array", "=", "array", ".", "astype", "(", "'int64'", ")", "/", "10", "**", "6.0", "else", ":", "array", "=", "array", ".", "astype", "(", "'datetime64[us]'", ")", ".", "astype", "(", "'int64'", ")", "/", "1000.", "elif", "array", ".", "dtype", ".", "kind", "==", "'m'", ":", "array", "=", "array", ".", "astype", "(", "'timedelta64[us]'", ")", ".", "astype", "(", "'int64'", ")", "/", "1000.", "return", "array" ]
Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array
[ "Convert", "NumPy", "datetime", "arrays", "to", "arrays", "to", "milliseconds", "since", "epoch", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L195-L238
train
bokeh/bokeh
bokeh/util/serialization.py
make_id
def make_id(): ''' Return a new unique ID for a Bokeh object. Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overridden by setting the environment variable ``BOKEH_SIMPLE_IDS=no``. Returns: str ''' global _simple_id if settings.simple_ids(True): with _simple_id_lock: _simple_id += 1 return str(_simple_id) else: return make_globally_unique_id()
python
def make_id(): ''' Return a new unique ID for a Bokeh object. Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overridden by setting the environment variable ``BOKEH_SIMPLE_IDS=no``. Returns: str ''' global _simple_id if settings.simple_ids(True): with _simple_id_lock: _simple_id += 1 return str(_simple_id) else: return make_globally_unique_id()
[ "def", "make_id", "(", ")", ":", "global", "_simple_id", "if", "settings", ".", "simple_ids", "(", "True", ")", ":", "with", "_simple_id_lock", ":", "_simple_id", "+=", "1", "return", "str", "(", "_simple_id", ")", "else", ":", "return", "make_globally_unique_id", "(", ")" ]
Return a new unique ID for a Bokeh object. Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overridden by setting the environment variable ``BOKEH_SIMPLE_IDS=no``. Returns: str
[ "Return", "a", "new", "unique", "ID", "for", "a", "Bokeh", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L240-L259
train
bokeh/bokeh
bokeh/util/serialization.py
transform_array
def transform_array(array, force_list=False, buffers=None): ''' Transform a NumPy arrays into serialized format Converts un-serializable dtypes and returns JSON serializable format Args: array (np.ndarray) : a NumPy array to be transformed force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: JSON ''' array = convert_datetime_array(array) return serialize_array(array, force_list=force_list, buffers=buffers)
python
def transform_array(array, force_list=False, buffers=None): ''' Transform a NumPy arrays into serialized format Converts un-serializable dtypes and returns JSON serializable format Args: array (np.ndarray) : a NumPy array to be transformed force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: JSON ''' array = convert_datetime_array(array) return serialize_array(array, force_list=force_list, buffers=buffers)
[ "def", "transform_array", "(", "array", ",", "force_list", "=", "False", ",", "buffers", "=", "None", ")", ":", "array", "=", "convert_datetime_array", "(", "array", ")", "return", "serialize_array", "(", "array", ",", "force_list", "=", "force_list", ",", "buffers", "=", "buffers", ")" ]
Transform a NumPy arrays into serialized format Converts un-serializable dtypes and returns JSON serializable format Args: array (np.ndarray) : a NumPy array to be transformed force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: JSON
[ "Transform", "a", "NumPy", "arrays", "into", "serialized", "format" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L295-L328
train
bokeh/bokeh
bokeh/util/serialization.py
transform_array_to_list
def transform_array_to_list(array): ''' Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict ''' if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()): transformed = array.astype('object') transformed[np.isnan(array)] = 'NaN' transformed[np.isposinf(array)] = 'Infinity' transformed[np.isneginf(array)] = '-Infinity' return transformed.tolist() elif (array.dtype.kind == 'O' and pd and pd.isnull(array).any()): transformed = array.astype('object') transformed[pd.isnull(array)] = 'NaN' return transformed.tolist() return array.tolist()
python
def transform_array_to_list(array): ''' Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict ''' if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()): transformed = array.astype('object') transformed[np.isnan(array)] = 'NaN' transformed[np.isposinf(array)] = 'Infinity' transformed[np.isneginf(array)] = '-Infinity' return transformed.tolist() elif (array.dtype.kind == 'O' and pd and pd.isnull(array).any()): transformed = array.astype('object') transformed[pd.isnull(array)] = 'NaN' return transformed.tolist() return array.tolist()
[ "def", "transform_array_to_list", "(", "array", ")", ":", "if", "(", "array", ".", "dtype", ".", "kind", "in", "(", "'u'", ",", "'i'", ",", "'f'", ")", "and", "(", "~", "np", ".", "isfinite", "(", "array", ")", ")", ".", "any", "(", ")", ")", ":", "transformed", "=", "array", ".", "astype", "(", "'object'", ")", "transformed", "[", "np", ".", "isnan", "(", "array", ")", "]", "=", "'NaN'", "transformed", "[", "np", ".", "isposinf", "(", "array", ")", "]", "=", "'Infinity'", "transformed", "[", "np", ".", "isneginf", "(", "array", ")", "]", "=", "'-Infinity'", "return", "transformed", ".", "tolist", "(", ")", "elif", "(", "array", ".", "dtype", ".", "kind", "==", "'O'", "and", "pd", "and", "pd", ".", "isnull", "(", "array", ")", ".", "any", "(", ")", ")", ":", "transformed", "=", "array", ".", "astype", "(", "'object'", ")", "transformed", "[", "pd", ".", "isnull", "(", "array", ")", "]", "=", "'NaN'", "return", "transformed", ".", "tolist", "(", ")", "return", "array", ".", "tolist", "(", ")" ]
Transforms a NumPy array into a list of values Args: array (np.nadarray) : the NumPy array series to transform Returns: list or dict
[ "Transforms", "a", "NumPy", "array", "into", "a", "list", "of", "values" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L330-L350
train
bokeh/bokeh
bokeh/util/serialization.py
transform_series
def transform_series(series, force_list=False, buffers=None): ''' Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict ''' # not checking for pd here, this function should only be called if it # is already known that series is a Pandas Series type if isinstance(series, pd.PeriodIndex): vals = series.to_timestamp().values else: vals = series.values return transform_array(vals, force_list=force_list, buffers=buffers)
python
def transform_series(series, force_list=False, buffers=None): ''' Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict ''' # not checking for pd here, this function should only be called if it # is already known that series is a Pandas Series type if isinstance(series, pd.PeriodIndex): vals = series.to_timestamp().values else: vals = series.values return transform_array(vals, force_list=force_list, buffers=buffers)
[ "def", "transform_series", "(", "series", ",", "force_list", "=", "False", ",", "buffers", "=", "None", ")", ":", "# not checking for pd here, this function should only be called if it", "# is already known that series is a Pandas Series type", "if", "isinstance", "(", "series", ",", "pd", ".", "PeriodIndex", ")", ":", "vals", "=", "series", ".", "to_timestamp", "(", ")", ".", "values", "else", ":", "vals", "=", "series", ".", "values", "return", "transform_array", "(", "vals", ",", "force_list", "=", "force_list", ",", "buffers", "=", "buffers", ")" ]
Transforms a Pandas series into serialized form Args: series (pd.Series) : the Pandas series to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict
[ "Transforms", "a", "Pandas", "series", "into", "serialized", "form" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L352-L384
train
bokeh/bokeh
bokeh/util/serialization.py
serialize_array
def serialize_array(array, force_list=False, buffers=None): ''' Transforms a NumPy array into serialized form. Args: array (np.ndarray) : the NumPy array to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict ''' if isinstance(array, np.ma.MaskedArray): array = array.filled(np.nan) # Set masked values to nan if (array_encoding_disabled(array) or force_list): return transform_array_to_list(array) if not array.flags['C_CONTIGUOUS']: array = np.ascontiguousarray(array) if buffers is None: return encode_base64_dict(array) else: return encode_binary_dict(array, buffers)
python
def serialize_array(array, force_list=False, buffers=None): ''' Transforms a NumPy array into serialized form. Args: array (np.ndarray) : the NumPy array to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict ''' if isinstance(array, np.ma.MaskedArray): array = array.filled(np.nan) # Set masked values to nan if (array_encoding_disabled(array) or force_list): return transform_array_to_list(array) if not array.flags['C_CONTIGUOUS']: array = np.ascontiguousarray(array) if buffers is None: return encode_base64_dict(array) else: return encode_binary_dict(array, buffers)
[ "def", "serialize_array", "(", "array", ",", "force_list", "=", "False", ",", "buffers", "=", "None", ")", ":", "if", "isinstance", "(", "array", ",", "np", ".", "ma", ".", "MaskedArray", ")", ":", "array", "=", "array", ".", "filled", "(", "np", ".", "nan", ")", "# Set masked values to nan", "if", "(", "array_encoding_disabled", "(", "array", ")", "or", "force_list", ")", ":", "return", "transform_array_to_list", "(", "array", ")", "if", "not", "array", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ":", "array", "=", "np", ".", "ascontiguousarray", "(", "array", ")", "if", "buffers", "is", "None", ":", "return", "encode_base64_dict", "(", "array", ")", "else", ":", "return", "encode_binary_dict", "(", "array", ",", "buffers", ")" ]
Transforms a NumPy array into serialized form. Args: array (np.ndarray) : the NumPy array to transform force_list (bool, optional) : whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False) buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) If force_list is True, then this value will be ignored, and no buffers will be generated. **This is an "out" parameter**. The values it contains will be modified in-place. Returns: list or dict
[ "Transforms", "a", "NumPy", "array", "into", "serialized", "form", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L386-L421
train
bokeh/bokeh
bokeh/util/serialization.py
traverse_data
def traverse_data(obj, use_numpy=True, buffers=None): ''' Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, converting non-JSON items Args: obj (list) : a list of values or lists use_numpy (bool, optional) toggle NumPy as a dependency for testing This argument is only useful for testing (default: True) ''' if use_numpy and all(isinstance(el, np.ndarray) for el in obj): return [transform_array(el, buffers=buffers) for el in obj] obj_copy = [] for item in obj: # Check the base/common case first for performance reasons # Also use type(x) is float because it's faster than isinstance if type(item) is float: if math.isnan(item): item = 'NaN' elif math.isinf(item): if item > 0: item = 'Infinity' else: item = '-Infinity' obj_copy.append(item) elif isinstance(item, (list, tuple)): # check less common type second obj_copy.append(traverse_data(item)) else: obj_copy.append(item) return obj_copy
python
def traverse_data(obj, use_numpy=True, buffers=None): ''' Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, converting non-JSON items Args: obj (list) : a list of values or lists use_numpy (bool, optional) toggle NumPy as a dependency for testing This argument is only useful for testing (default: True) ''' if use_numpy and all(isinstance(el, np.ndarray) for el in obj): return [transform_array(el, buffers=buffers) for el in obj] obj_copy = [] for item in obj: # Check the base/common case first for performance reasons # Also use type(x) is float because it's faster than isinstance if type(item) is float: if math.isnan(item): item = 'NaN' elif math.isinf(item): if item > 0: item = 'Infinity' else: item = '-Infinity' obj_copy.append(item) elif isinstance(item, (list, tuple)): # check less common type second obj_copy.append(traverse_data(item)) else: obj_copy.append(item) return obj_copy
[ "def", "traverse_data", "(", "obj", ",", "use_numpy", "=", "True", ",", "buffers", "=", "None", ")", ":", "if", "use_numpy", "and", "all", "(", "isinstance", "(", "el", ",", "np", ".", "ndarray", ")", "for", "el", "in", "obj", ")", ":", "return", "[", "transform_array", "(", "el", ",", "buffers", "=", "buffers", ")", "for", "el", "in", "obj", "]", "obj_copy", "=", "[", "]", "for", "item", "in", "obj", ":", "# Check the base/common case first for performance reasons", "# Also use type(x) is float because it's faster than isinstance", "if", "type", "(", "item", ")", "is", "float", ":", "if", "math", ".", "isnan", "(", "item", ")", ":", "item", "=", "'NaN'", "elif", "math", ".", "isinf", "(", "item", ")", ":", "if", "item", ">", "0", ":", "item", "=", "'Infinity'", "else", ":", "item", "=", "'-Infinity'", "obj_copy", ".", "append", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "# check less common type second", "obj_copy", ".", "append", "(", "traverse_data", "(", "item", ")", ")", "else", ":", "obj_copy", ".", "append", "(", "item", ")", "return", "obj_copy" ]
Recursively traverse an object until a flat list is found. If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle ``nan``, ``inf``, and ``-inf``. Otherwise, iterate through all items, converting non-JSON items Args: obj (list) : a list of values or lists use_numpy (bool, optional) toggle NumPy as a dependency for testing This argument is only useful for testing (default: True)
[ "Recursively", "traverse", "an", "object", "until", "a", "flat", "list", "is", "found", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L423-L456
train
bokeh/bokeh
bokeh/util/serialization.py
transform_column_source_data
def transform_column_source_data(data, buffers=None, cols=None): ''' Transform ``ColumnSourceData`` data to a serialized format Args: data (dict) : the mapping of names to data columns to transform buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) **This is an "out" parameter**. The values it contains will be modified in-place. cols (list[str], optional) : Optional list of subset of columns to transform. If None, all columns will be transformed (default: None) Returns: JSON compatible dict ''' to_transform = set(data) if cols is None else set(cols) data_copy = {} for key in to_transform: if pd and isinstance(data[key], (pd.Series, pd.Index)): data_copy[key] = transform_series(data[key], buffers=buffers) elif isinstance(data[key], np.ndarray): data_copy[key] = transform_array(data[key], buffers=buffers) else: data_copy[key] = traverse_data(data[key], buffers=buffers) return data_copy
python
def transform_column_source_data(data, buffers=None, cols=None): ''' Transform ``ColumnSourceData`` data to a serialized format Args: data (dict) : the mapping of names to data columns to transform buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) **This is an "out" parameter**. The values it contains will be modified in-place. cols (list[str], optional) : Optional list of subset of columns to transform. If None, all columns will be transformed (default: None) Returns: JSON compatible dict ''' to_transform = set(data) if cols is None else set(cols) data_copy = {} for key in to_transform: if pd and isinstance(data[key], (pd.Series, pd.Index)): data_copy[key] = transform_series(data[key], buffers=buffers) elif isinstance(data[key], np.ndarray): data_copy[key] = transform_array(data[key], buffers=buffers) else: data_copy[key] = traverse_data(data[key], buffers=buffers) return data_copy
[ "def", "transform_column_source_data", "(", "data", ",", "buffers", "=", "None", ",", "cols", "=", "None", ")", ":", "to_transform", "=", "set", "(", "data", ")", "if", "cols", "is", "None", "else", "set", "(", "cols", ")", "data_copy", "=", "{", "}", "for", "key", "in", "to_transform", ":", "if", "pd", "and", "isinstance", "(", "data", "[", "key", "]", ",", "(", "pd", ".", "Series", ",", "pd", ".", "Index", ")", ")", ":", "data_copy", "[", "key", "]", "=", "transform_series", "(", "data", "[", "key", "]", ",", "buffers", "=", "buffers", ")", "elif", "isinstance", "(", "data", "[", "key", "]", ",", "np", ".", "ndarray", ")", ":", "data_copy", "[", "key", "]", "=", "transform_array", "(", "data", "[", "key", "]", ",", "buffers", "=", "buffers", ")", "else", ":", "data_copy", "[", "key", "]", "=", "traverse_data", "(", "data", "[", "key", "]", ",", "buffers", "=", "buffers", ")", "return", "data_copy" ]
Transform ``ColumnSourceData`` data to a serialized format Args: data (dict) : the mapping of names to data columns to transform buffers (set, optional) : If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encoding will be used (default: None) **This is an "out" parameter**. The values it contains will be modified in-place. cols (list[str], optional) : Optional list of subset of columns to transform. If None, all columns will be transformed (default: None) Returns: JSON compatible dict
[ "Transform", "ColumnSourceData", "data", "to", "a", "serialized", "format" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L458-L492
train
bokeh/bokeh
bokeh/util/serialization.py
encode_binary_dict
def encode_binary_dict(array, buffers): ''' Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, 'order' : << byte order at origin (little or big)>> } Args: array (np.ndarray) : an array to encode buffers (set) : Set to add buffers to **This is an "out" parameter**. The values it contains will be modified in-place. Returns: dict ''' buffer_id = make_id() buf = (dict(id=buffer_id), array.tobytes()) buffers.append(buf) return { '__buffer__' : buffer_id, 'shape' : array.shape, 'dtype' : array.dtype.name, 'order' : sys.byteorder }
python
def encode_binary_dict(array, buffers): ''' Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, 'order' : << byte order at origin (little or big)>> } Args: array (np.ndarray) : an array to encode buffers (set) : Set to add buffers to **This is an "out" parameter**. The values it contains will be modified in-place. Returns: dict ''' buffer_id = make_id() buf = (dict(id=buffer_id), array.tobytes()) buffers.append(buf) return { '__buffer__' : buffer_id, 'shape' : array.shape, 'dtype' : array.dtype.name, 'order' : sys.byteorder }
[ "def", "encode_binary_dict", "(", "array", ",", "buffers", ")", ":", "buffer_id", "=", "make_id", "(", ")", "buf", "=", "(", "dict", "(", "id", "=", "buffer_id", ")", ",", "array", ".", "tobytes", "(", ")", ")", "buffers", ".", "append", "(", "buf", ")", "return", "{", "'__buffer__'", ":", "buffer_id", ",", "'shape'", ":", "array", ".", "shape", ",", "'dtype'", ":", "array", ".", "dtype", ".", "name", ",", "'order'", ":", "sys", ".", "byteorder", "}" ]
Send a numpy array as an unencoded binary buffer The encoded format is a dict with the following structure: .. code:: python { '__buffer__' : << an ID to locate the buffer >>, 'shape' : << array shape >>, 'dtype' : << dtype name >>, 'order' : << byte order at origin (little or big)>> } Args: array (np.ndarray) : an array to encode buffers (set) : Set to add buffers to **This is an "out" parameter**. The values it contains will be modified in-place. Returns: dict
[ "Send", "a", "numpy", "array", "as", "an", "unencoded", "binary", "buffer" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L494-L530
train
bokeh/bokeh
bokeh/util/serialization.py
decode_base64_dict
def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray ''' b64 = base64.b64decode(data['__ndarray__']) array = np.copy(np.frombuffer(b64, dtype=data['dtype'])) if len(data['shape']) > 1: array = array.reshape(data['shape']) return array
python
def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray ''' b64 = base64.b64decode(data['__ndarray__']) array = np.copy(np.frombuffer(b64, dtype=data['dtype'])) if len(data['shape']) > 1: array = array.reshape(data['shape']) return array
[ "def", "decode_base64_dict", "(", "data", ")", ":", "b64", "=", "base64", ".", "b64decode", "(", "data", "[", "'__ndarray__'", "]", ")", "array", "=", "np", ".", "copy", "(", "np", ".", "frombuffer", "(", "b64", ",", "dtype", "=", "data", "[", "'dtype'", "]", ")", ")", "if", "len", "(", "data", "[", "'shape'", "]", ")", ">", "1", ":", "array", "=", "array", ".", "reshape", "(", "data", "[", "'shape'", "]", ")", "return", "array" ]
Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray
[ "Decode", "a", "base64", "encoded", "array", "into", "a", "NumPy", "array", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L559-L575
train
bokeh/bokeh
bokeh/models/tools.py
CustomJSHover.from_py_func
def from_py_func(cls, code): ''' Create a ``CustomJSHover`` instance from a Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It is possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``code`` function namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``format`` and ``special_vars`` as described in the class description. Args: code (function) : a scalar function to transform a single ``value`` Returns: CustomJSHover ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSHover directly instead.") if not isinstance(code, FunctionType): raise ValueError('CustomJSHover.from_py_func only accepts function objects.') pscript = import_required('pscript', 'To use Python functions for CustomJSHover, you need PScript ' + '("conda install -c conda-forge pscript" or "pip install pscript")') def pscript_compile(code): sig = signature(code) all_names, default_values = get_param_info(sig) if len(all_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a Bokeh Model.") func_kwargs = dict(zip(all_names, default_values)) # Wrap the code attr in a function named `code` and call it # with arguments that match the `args` attr code = pscript.py2js(code, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names) return code, func_kwargs jsfunc, func_kwargs = pscript_compile(code) return cls(code=jsfunc, args=func_kwargs)
python
def from_py_func(cls, code): ''' Create a ``CustomJSHover`` instance from a Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It is possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``code`` function namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``format`` and ``special_vars`` as described in the class description. Args: code (function) : a scalar function to transform a single ``value`` Returns: CustomJSHover ''' from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJSHover directly instead.") if not isinstance(code, FunctionType): raise ValueError('CustomJSHover.from_py_func only accepts function objects.') pscript = import_required('pscript', 'To use Python functions for CustomJSHover, you need PScript ' + '("conda install -c conda-forge pscript" or "pip install pscript")') def pscript_compile(code): sig = signature(code) all_names, default_values = get_param_info(sig) if len(all_names) - len(default_values) != 0: raise ValueError("Function may only contain keyword arguments.") if default_values and not any(isinstance(value, Model) for value in default_values): raise ValueError("Default value must be a Bokeh Model.") func_kwargs = dict(zip(all_names, default_values)) # Wrap the code attr in a function named `code` and call it # with arguments that match the `args` attr code = pscript.py2js(code, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names) return code, func_kwargs jsfunc, func_kwargs = pscript_compile(code) return cls(code=jsfunc, args=func_kwargs)
[ "def", "from_py_func", "(", "cls", ",", "code", ")", ":", "from", "bokeh", ".", "util", ".", "deprecation", "import", "deprecated", "deprecated", "(", "\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"", "\"Use CustomJSHover directly instead.\"", ")", "if", "not", "isinstance", "(", "code", ",", "FunctionType", ")", ":", "raise", "ValueError", "(", "'CustomJSHover.from_py_func only accepts function objects.'", ")", "pscript", "=", "import_required", "(", "'pscript'", ",", "'To use Python functions for CustomJSHover, you need PScript '", "+", "'(\"conda install -c conda-forge pscript\" or \"pip install pscript\")'", ")", "def", "pscript_compile", "(", "code", ")", ":", "sig", "=", "signature", "(", "code", ")", "all_names", ",", "default_values", "=", "get_param_info", "(", "sig", ")", "if", "len", "(", "all_names", ")", "-", "len", "(", "default_values", ")", "!=", "0", ":", "raise", "ValueError", "(", "\"Function may only contain keyword arguments.\"", ")", "if", "default_values", "and", "not", "any", "(", "isinstance", "(", "value", ",", "Model", ")", "for", "value", "in", "default_values", ")", ":", "raise", "ValueError", "(", "\"Default value must be a Bokeh Model.\"", ")", "func_kwargs", "=", "dict", "(", "zip", "(", "all_names", ",", "default_values", ")", ")", "# Wrap the code attr in a function named `code` and call it", "# with arguments that match the `args` attr", "code", "=", "pscript", ".", "py2js", "(", "code", ",", "'transformer'", ")", "+", "'return transformer(%s);\\n'", "%", "', '", ".", "join", "(", "all_names", ")", "return", "code", ",", "func_kwargs", "jsfunc", ",", "func_kwargs", "=", "pscript_compile", "(", "code", ")", "return", "cls", "(", "code", "=", "jsfunc", ",", "args", "=", "func_kwargs", ")" ]
Create a ``CustomJSHover`` instance from a Python functions. The function is translated to JavaScript using PScript. The python functions must have no positional arguments. It is possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword arguments to the functions. The ``code`` function namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``format`` and ``special_vars`` as described in the class description. Args: code (function) : a scalar function to transform a single ``value`` Returns: CustomJSHover
[ "Create", "a", "CustomJSHover", "instance", "from", "a", "Python", "functions", ".", "The", "function", "is", "translated", "to", "JavaScript", "using", "PScript", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/tools.py#L882-L932
train
bokeh/bokeh
bokeh/models/tools.py
CustomJSHover.from_coffeescript
def from_coffeescript(cls, code, args={}): ''' Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``code`` snippet namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``special_vars`` and ``format`` as described in the class description. Example: .. code-block:: coffeescript formatter = CustomJSHover.from_coffeescript("return value + " total") Args: code (str) : A coffeescript snippet to transform a single ``value`` value Returns: CustomJSHover ''' compiled = nodejs_compile(code, lang="coffeescript", file="???") if "error" in compiled: raise CompilationError(compiled.error) return cls(code=compiled.code, args=args)
python
def from_coffeescript(cls, code, args={}): ''' Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``code`` snippet namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``special_vars`` and ``format`` as described in the class description. Example: .. code-block:: coffeescript formatter = CustomJSHover.from_coffeescript("return value + " total") Args: code (str) : A coffeescript snippet to transform a single ``value`` value Returns: CustomJSHover ''' compiled = nodejs_compile(code, lang="coffeescript", file="???") if "error" in compiled: raise CompilationError(compiled.error) return cls(code=compiled.code, args=args)
[ "def", "from_coffeescript", "(", "cls", ",", "code", ",", "args", "=", "{", "}", ")", ":", "compiled", "=", "nodejs_compile", "(", "code", ",", "lang", "=", "\"coffeescript\"", ",", "file", "=", "\"???\"", ")", "if", "\"error\"", "in", "compiled", ":", "raise", "CompilationError", "(", "compiled", ".", "error", ")", "return", "cls", "(", "code", "=", "compiled", ".", "code", ",", "args", "=", "args", ")" ]
Create a CustomJSHover instance from a CoffeeScript snippet. The function bodies are translated to JavaScript functions using node and therefore require return statements. The ``code`` snippet namespace will contain the variable ``value`` (the untransformed value) at render time as well as ``special_vars`` and ``format`` as described in the class description. Example: .. code-block:: coffeescript formatter = CustomJSHover.from_coffeescript("return value + " total") Args: code (str) : A coffeescript snippet to transform a single ``value`` value Returns: CustomJSHover
[ "Create", "a", "CustomJSHover", "instance", "from", "a", "CoffeeScript", "snippet", ".", "The", "function", "bodies", "are", "translated", "to", "JavaScript", "functions", "using", "node", "and", "therefore", "require", "return", "statements", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/tools.py#L935-L962
train
bokeh/bokeh
bokeh/sphinxext/bokehjs_content.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node( bokehjs_content, html=( html_visit_bokehjs_content, html_depart_bokehjs_content ) ) app.add_directive('bokehjs-content', BokehJSContent)
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node( bokehjs_content, html=( html_visit_bokehjs_content, html_depart_bokehjs_content ) ) app.add_directive('bokehjs-content', BokehJSContent)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_node", "(", "bokehjs_content", ",", "html", "=", "(", "html_visit_bokehjs_content", ",", "html_depart_bokehjs_content", ")", ")", "app", ".", "add_directive", "(", "'bokehjs-content'", ",", "BokehJSContent", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L268-L277
train
bokeh/bokeh
bokeh/sphinxext/bokehjs_content.py
BokehJSContent.get_codeblock_node
def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self """ # type: () -> List[nodes.Node] document = self.state.document location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(code.split('\n')) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): log.warning(__('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = language literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options literal['classes'] += self.options.get('class', []) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(text_type(exc), line=self.lineno)] # literal will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(literal) return [literal]
python
def get_codeblock_node(self, code, language): """this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self """ # type: () -> List[nodes.Node] document = self.state.document location = self.state_machine.get_source_and_line(self.lineno) linespec = self.options.get('emphasize-lines') if linespec: try: nlines = len(code.split('\n')) hl_lines = parselinenos(linespec, nlines) if any(i >= nlines for i in hl_lines): log.warning(__('line number spec is out of range(1-%d): %r') % (nlines, self.options['emphasize-lines']), location=location) hl_lines = [x + 1 for x in hl_lines if x < nlines] except ValueError as err: return [document.reporter.warning(str(err), line=self.lineno)] else: hl_lines = None if 'dedent' in self.options: location = self.state_machine.get_source_and_line(self.lineno) lines = code.split('\n') lines = dedent_lines(lines, self.options['dedent'], location=location) code = '\n'.join(lines) literal = nodes.literal_block(code, code) literal['language'] = language literal['linenos'] = 'linenos' in self.options or \ 'lineno-start' in self.options literal['classes'] += self.options.get('class', []) extra_args = literal['highlight_args'] = {} if hl_lines is not None: extra_args['hl_lines'] = hl_lines if 'lineno-start' in self.options: extra_args['linenostart'] = self.options['lineno-start'] set_source_info(self, literal) caption = self.options.get('caption') if caption: try: literal = container_wrapper(self, literal, caption) except ValueError as exc: return [document.reporter.warning(text_type(exc), line=self.lineno)] # literal will be note_implicit_target that is linked from caption and numref. # when options['name'] is provided, it should be primary ID. self.add_name(literal) return [literal]
[ "def", "get_codeblock_node", "(", "self", ",", "code", ",", "language", ")", ":", "# type: () -> List[nodes.Node]", "document", "=", "self", ".", "state", ".", "document", "location", "=", "self", ".", "state_machine", ".", "get_source_and_line", "(", "self", ".", "lineno", ")", "linespec", "=", "self", ".", "options", ".", "get", "(", "'emphasize-lines'", ")", "if", "linespec", ":", "try", ":", "nlines", "=", "len", "(", "code", ".", "split", "(", "'\\n'", ")", ")", "hl_lines", "=", "parselinenos", "(", "linespec", ",", "nlines", ")", "if", "any", "(", "i", ">=", "nlines", "for", "i", "in", "hl_lines", ")", ":", "log", ".", "warning", "(", "__", "(", "'line number spec is out of range(1-%d): %r'", ")", "%", "(", "nlines", ",", "self", ".", "options", "[", "'emphasize-lines'", "]", ")", ",", "location", "=", "location", ")", "hl_lines", "=", "[", "x", "+", "1", "for", "x", "in", "hl_lines", "if", "x", "<", "nlines", "]", "except", "ValueError", "as", "err", ":", "return", "[", "document", ".", "reporter", ".", "warning", "(", "str", "(", "err", ")", ",", "line", "=", "self", ".", "lineno", ")", "]", "else", ":", "hl_lines", "=", "None", "if", "'dedent'", "in", "self", ".", "options", ":", "location", "=", "self", ".", "state_machine", ".", "get_source_and_line", "(", "self", ".", "lineno", ")", "lines", "=", "code", ".", "split", "(", "'\\n'", ")", "lines", "=", "dedent_lines", "(", "lines", ",", "self", ".", "options", "[", "'dedent'", "]", ",", "location", "=", "location", ")", "code", "=", "'\\n'", ".", "join", "(", "lines", ")", "literal", "=", "nodes", ".", "literal_block", "(", "code", ",", "code", ")", "literal", "[", "'language'", "]", "=", "language", "literal", "[", "'linenos'", "]", "=", "'linenos'", "in", "self", ".", "options", "or", "'lineno-start'", "in", "self", ".", "options", "literal", "[", "'classes'", "]", "+=", "self", ".", "options", ".", "get", "(", "'class'", ",", "[", "]", ")", "extra_args", "=", "literal", "[", "'highlight_args'", "]", "=", "{", "}", "if", "hl_lines", "is", "not", "None", ":", "extra_args", "[", "'hl_lines'", "]", "=", "hl_lines", "if", "'lineno-start'", "in", "self", ".", "options", ":", "extra_args", "[", "'linenostart'", "]", "=", "self", ".", "options", "[", "'lineno-start'", "]", "set_source_info", "(", "self", ",", "literal", ")", "caption", "=", "self", ".", "options", ".", "get", "(", "'caption'", ")", "if", "caption", ":", "try", ":", "literal", "=", "container_wrapper", "(", "self", ",", "literal", ",", "caption", ")", "except", "ValueError", "as", "exc", ":", "return", "[", "document", ".", "reporter", ".", "warning", "(", "text_type", "(", "exc", ")", ",", "line", "=", "self", ".", "lineno", ")", "]", "# literal will be note_implicit_target that is linked from caption and numref.", "# when options['name'] is provided, it should be primary ID.", "self", ".", "add_name", "(", "literal", ")", "return", "[", "literal", "]" ]
this is copied from sphinx.directives.code.CodeBlock.run it has been changed to accept code and language as an arguments instead of reading from self
[ "this", "is", "copied", "from", "sphinx", ".", "directives", ".", "code", ".", "CodeBlock", ".", "run" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L117-L174
train
bokeh/bokeh
bokeh/sphinxext/bokehjs_content.py
BokehJSContent.get_code_language
def get_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """ js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.render( css_files=resources.css_files, js_files=resources.js_files, bjs_script=js_source) return [html_source, "html"] else: return [js_source, "javascript"]
python
def get_code_language(self): """ This is largely copied from bokeh.sphinxext.bokeh_plot.run """ js_source = self.get_js_source() if self.options.get("include_html", False): resources = get_sphinx_resources(include_bokehjs_api=True) html_source = BJS_HTML.render( css_files=resources.css_files, js_files=resources.js_files, bjs_script=js_source) return [html_source, "html"] else: return [js_source, "javascript"]
[ "def", "get_code_language", "(", "self", ")", ":", "js_source", "=", "self", ".", "get_js_source", "(", ")", "if", "self", ".", "options", ".", "get", "(", "\"include_html\"", ",", "False", ")", ":", "resources", "=", "get_sphinx_resources", "(", "include_bokehjs_api", "=", "True", ")", "html_source", "=", "BJS_HTML", ".", "render", "(", "css_files", "=", "resources", ".", "css_files", ",", "js_files", "=", "resources", ".", "js_files", ",", "bjs_script", "=", "js_source", ")", "return", "[", "html_source", ",", "\"html\"", "]", "else", ":", "return", "[", "js_source", ",", "\"javascript\"", "]" ]
This is largely copied from bokeh.sphinxext.bokeh_plot.run
[ "This", "is", "largely", "copied", "from", "bokeh", ".", "sphinxext", ".", "bokeh_plot", ".", "run" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L196-L209
train
bokeh/bokeh
bokeh/embed/standalone.py
autoload_static
def autoload_static(model, resources, script_path): ''' Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_path (str) : Returns: (js, tag) : JavaScript code to be saved at ``script_path`` and a ``<script>`` tag to load it Raises: ValueError ''' # TODO: maybe warn that it's not exactly useful, but technically possible # if resources.mode == 'inline': # raise ValueError("autoload_static() requires non-inline resources") if isinstance(model, Model): models = [model] elif isinstance (model, Document): models = model.roots else: raise ValueError("autoload_static expects a single Model or Document") with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_docs_json_and_render_items([model]) bundle = bundle_all_models() or "" script = script_for_render_items(docs_json, [render_item]) (modelid, elementid) = list(render_item.roots.to_json().items())[0] js = wrap_in_onload(AUTOLOAD_JS.render( js_urls = resources.js_files, css_urls = resources.css_files, js_raw = resources.js_raw + [bundle, script], css_raw = resources.css_raw_str, elementid = elementid, )) tag = AUTOLOAD_TAG.render( src_path = script_path, elementid = elementid, ) return encode_utf8(js), encode_utf8(tag)
python
def autoload_static(model, resources, script_path): ''' Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_path (str) : Returns: (js, tag) : JavaScript code to be saved at ``script_path`` and a ``<script>`` tag to load it Raises: ValueError ''' # TODO: maybe warn that it's not exactly useful, but technically possible # if resources.mode == 'inline': # raise ValueError("autoload_static() requires non-inline resources") if isinstance(model, Model): models = [model] elif isinstance (model, Document): models = model.roots else: raise ValueError("autoload_static expects a single Model or Document") with OutputDocumentFor(models): (docs_json, [render_item]) = standalone_docs_json_and_render_items([model]) bundle = bundle_all_models() or "" script = script_for_render_items(docs_json, [render_item]) (modelid, elementid) = list(render_item.roots.to_json().items())[0] js = wrap_in_onload(AUTOLOAD_JS.render( js_urls = resources.js_files, css_urls = resources.css_files, js_raw = resources.js_raw + [bundle, script], css_raw = resources.css_raw_str, elementid = elementid, )) tag = AUTOLOAD_TAG.render( src_path = script_path, elementid = elementid, ) return encode_utf8(js), encode_utf8(tag)
[ "def", "autoload_static", "(", "model", ",", "resources", ",", "script_path", ")", ":", "# TODO: maybe warn that it's not exactly useful, but technically possible", "# if resources.mode == 'inline':", "# raise ValueError(\"autoload_static() requires non-inline resources\")", "if", "isinstance", "(", "model", ",", "Model", ")", ":", "models", "=", "[", "model", "]", "elif", "isinstance", "(", "model", ",", "Document", ")", ":", "models", "=", "model", ".", "roots", "else", ":", "raise", "ValueError", "(", "\"autoload_static expects a single Model or Document\"", ")", "with", "OutputDocumentFor", "(", "models", ")", ":", "(", "docs_json", ",", "[", "render_item", "]", ")", "=", "standalone_docs_json_and_render_items", "(", "[", "model", "]", ")", "bundle", "=", "bundle_all_models", "(", ")", "or", "\"\"", "script", "=", "script_for_render_items", "(", "docs_json", ",", "[", "render_item", "]", ")", "(", "modelid", ",", "elementid", ")", "=", "list", "(", "render_item", ".", "roots", ".", "to_json", "(", ")", ".", "items", "(", ")", ")", "[", "0", "]", "js", "=", "wrap_in_onload", "(", "AUTOLOAD_JS", ".", "render", "(", "js_urls", "=", "resources", ".", "js_files", ",", "css_urls", "=", "resources", ".", "css_files", ",", "js_raw", "=", "resources", ".", "js_raw", "+", "[", "bundle", ",", "script", "]", ",", "css_raw", "=", "resources", ".", "css_raw_str", ",", "elementid", "=", "elementid", ",", ")", ")", "tag", "=", "AUTOLOAD_TAG", ".", "render", "(", "src_path", "=", "script_path", ",", "elementid", "=", "elementid", ",", ")", "return", "encode_utf8", "(", "js", ")", ",", "encode_utf8", "(", "tag", ")" ]
Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_path (str) : Returns: (js, tag) : JavaScript code to be saved at ``script_path`` and a ``<script>`` tag to load it Raises: ValueError
[ "Return", "JavaScript", "code", "and", "a", "script", "tag", "that", "can", "be", "used", "to", "embed", "Bokeh", "Plots", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L55-L109
train
bokeh/bokeh
bokeh/embed/standalone.py
components
def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS resources are **already loaded**. The html template in which they will be embedded needs to include the following links and scripts tags. The widgets and tables resources are only necessary if the components make use of widgets and tables. .. code-block:: html <link href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script> Note that in Jupyter Notebooks, it is not possible to use components and show in the same notebook cell. Args: models (Model|list|dict|tuple) : A single Model, a list/tuple of Models, or a dictionary of keys and Models. wrap_script (boolean, optional) : If True, the returned javascript is wrapped in a script tag. (default: True) wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings. Otherwise, return dicts that can be used to build your own divs. (default: True) If False, the returned dictionary contains the following information: .. code-block:: python { 'modelid': 'The model ID, used with Document.get_model_by_id', 'elementid': 'The css identifier the BokehJS will look for to target the plot', 'docid': 'Used by Bokeh to find the doc embedded in the returned script', } theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])* Examples: With default wrapping parameter values: .. code-block:: python components(plot) # => (script, plot_div) components((plot1, plot2)) # => (script, (plot1_div, plot2_div)) components({"Plot 1": plot1, "Plot 2": plot2}) # => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div}) Examples: With wrapping parameters set to ``False``: .. code-block:: python components(plot, wrap_script=False, wrap_plot_info=False) # => (javascript, plot_dict) components((plot1, plot2), wrap_script=False, wrap_plot_info=False) # => (javascript, (plot1_dict, plot2_dict)) components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False) # => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict}) ''' # 1) Convert single items and dicts into list was_single_object = isinstance(models, Model) or isinstance(models, Document) models = _check_models_or_docs(models) # now convert dict to list, saving keys in the same order model_keys = None dict_type = None if isinstance(models, dict): model_keys = models.keys() dict_type = models.__class__ values = [] # don't just use .values() to ensure we are in the same order as key list for k in model_keys: values.append(models[k]) models = values # 2) Append models to one document. Either pre-existing or new and render with OutputDocumentFor(models, apply_theme=theme): (docs_json, [render_item]) = standalone_docs_json_and_render_items(models) script = bundle_all_models() or "" script += script_for_render_items(docs_json, [render_item]) if wrap_script: script = wrap_in_script_tag(script) script = encode_utf8(script) def div_for_root(root): return ROOT_DIV.render(root=root, macros=MACROS) if wrap_plot_info: results = list(div_for_root(root) for root in render_item.roots) else: results = render_item.roots # 3) convert back to the input shape if was_single_object: result = results[0] elif model_keys is not None: result = dict_type(zip(model_keys, results)) else: result = tuple(results) return script, result
python
def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS resources are **already loaded**. The html template in which they will be embedded needs to include the following links and scripts tags. The widgets and tables resources are only necessary if the components make use of widgets and tables. .. code-block:: html <link href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script> Note that in Jupyter Notebooks, it is not possible to use components and show in the same notebook cell. Args: models (Model|list|dict|tuple) : A single Model, a list/tuple of Models, or a dictionary of keys and Models. wrap_script (boolean, optional) : If True, the returned javascript is wrapped in a script tag. (default: True) wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings. Otherwise, return dicts that can be used to build your own divs. (default: True) If False, the returned dictionary contains the following information: .. code-block:: python { 'modelid': 'The model ID, used with Document.get_model_by_id', 'elementid': 'The css identifier the BokehJS will look for to target the plot', 'docid': 'Used by Bokeh to find the doc embedded in the returned script', } theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])* Examples: With default wrapping parameter values: .. code-block:: python components(plot) # => (script, plot_div) components((plot1, plot2)) # => (script, (plot1_div, plot2_div)) components({"Plot 1": plot1, "Plot 2": plot2}) # => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div}) Examples: With wrapping parameters set to ``False``: .. code-block:: python components(plot, wrap_script=False, wrap_plot_info=False) # => (javascript, plot_dict) components((plot1, plot2), wrap_script=False, wrap_plot_info=False) # => (javascript, (plot1_dict, plot2_dict)) components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False) # => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict}) ''' # 1) Convert single items and dicts into list was_single_object = isinstance(models, Model) or isinstance(models, Document) models = _check_models_or_docs(models) # now convert dict to list, saving keys in the same order model_keys = None dict_type = None if isinstance(models, dict): model_keys = models.keys() dict_type = models.__class__ values = [] # don't just use .values() to ensure we are in the same order as key list for k in model_keys: values.append(models[k]) models = values # 2) Append models to one document. Either pre-existing or new and render with OutputDocumentFor(models, apply_theme=theme): (docs_json, [render_item]) = standalone_docs_json_and_render_items(models) script = bundle_all_models() or "" script += script_for_render_items(docs_json, [render_item]) if wrap_script: script = wrap_in_script_tag(script) script = encode_utf8(script) def div_for_root(root): return ROOT_DIV.render(root=root, macros=MACROS) if wrap_plot_info: results = list(div_for_root(root) for root in render_item.roots) else: results = render_item.roots # 3) convert back to the input shape if was_single_object: result = results[0] elif model_keys is not None: result = dict_type(zip(model_keys, results)) else: result = tuple(results) return script, result
[ "def", "components", "(", "models", ",", "wrap_script", "=", "True", ",", "wrap_plot_info", "=", "True", ",", "theme", "=", "FromCurdoc", ")", ":", "# 1) Convert single items and dicts into list", "was_single_object", "=", "isinstance", "(", "models", ",", "Model", ")", "or", "isinstance", "(", "models", ",", "Document", ")", "models", "=", "_check_models_or_docs", "(", "models", ")", "# now convert dict to list, saving keys in the same order", "model_keys", "=", "None", "dict_type", "=", "None", "if", "isinstance", "(", "models", ",", "dict", ")", ":", "model_keys", "=", "models", ".", "keys", "(", ")", "dict_type", "=", "models", ".", "__class__", "values", "=", "[", "]", "# don't just use .values() to ensure we are in the same order as key list", "for", "k", "in", "model_keys", ":", "values", ".", "append", "(", "models", "[", "k", "]", ")", "models", "=", "values", "# 2) Append models to one document. Either pre-existing or new and render", "with", "OutputDocumentFor", "(", "models", ",", "apply_theme", "=", "theme", ")", ":", "(", "docs_json", ",", "[", "render_item", "]", ")", "=", "standalone_docs_json_and_render_items", "(", "models", ")", "script", "=", "bundle_all_models", "(", ")", "or", "\"\"", "script", "+=", "script_for_render_items", "(", "docs_json", ",", "[", "render_item", "]", ")", "if", "wrap_script", ":", "script", "=", "wrap_in_script_tag", "(", "script", ")", "script", "=", "encode_utf8", "(", "script", ")", "def", "div_for_root", "(", "root", ")", ":", "return", "ROOT_DIV", ".", "render", "(", "root", "=", "root", ",", "macros", "=", "MACROS", ")", "if", "wrap_plot_info", ":", "results", "=", "list", "(", "div_for_root", "(", "root", ")", "for", "root", "in", "render_item", ".", "roots", ")", "else", ":", "results", "=", "render_item", ".", "roots", "# 3) convert back to the input shape", "if", "was_single_object", ":", "result", "=", "results", "[", "0", "]", "elif", "model_keys", "is", "not", "None", ":", "result", "=", "dict_type", "(", "zip", "(", "model_keys", ",", "results", ")", ")", "else", ":", "result", "=", "tuple", "(", "results", ")", "return", "script", ",", "result" ]
Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS resources are **already loaded**. The html template in which they will be embedded needs to include the following links and scripts tags. The widgets and tables resources are only necessary if the components make use of widgets and tables. .. code-block:: html <link href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css" rel="stylesheet" type="text/css"> <link href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css" rel="stylesheet" type="text/css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script> <script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script> Note that in Jupyter Notebooks, it is not possible to use components and show in the same notebook cell. Args: models (Model|list|dict|tuple) : A single Model, a list/tuple of Models, or a dictionary of keys and Models. wrap_script (boolean, optional) : If True, the returned javascript is wrapped in a script tag. (default: True) wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings. Otherwise, return dicts that can be used to build your own divs. (default: True) If False, the returned dictionary contains the following information: .. code-block:: python { 'modelid': 'The model ID, used with Document.get_model_by_id', 'elementid': 'The css identifier the BokehJS will look for to target the plot', 'docid': 'Used by Bokeh to find the doc embedded in the returned script', } theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])* Examples: With default wrapping parameter values: .. code-block:: python components(plot) # => (script, plot_div) components((plot1, plot2)) # => (script, (plot1_div, plot2_div)) components({"Plot 1": plot1, "Plot 2": plot2}) # => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div}) Examples: With wrapping parameters set to ``False``: .. code-block:: python components(plot, wrap_script=False, wrap_plot_info=False) # => (javascript, plot_dict) components((plot1, plot2), wrap_script=False, wrap_plot_info=False) # => (javascript, (plot1_dict, plot2_dict)) components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False) # => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict})
[ "Return", "HTML", "components", "to", "embed", "a", "Bokeh", "plot", ".", "The", "data", "for", "the", "plot", "is", "stored", "directly", "in", "the", "returned", "HTML", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L111-L248
train
bokeh/bokeh
bokeh/embed/standalone.py
file_html
def file_html(models, resources, title=None, template=FILE, template_variables={}, theme=FromCurdoc, suppress_callback_warning=False, _always_new=False): ''' Return an HTML document that embeds Bokeh Model or Document objects. The data for the plot is stored directly in the returned HTML, with support for customizing the JS/CSS resources independently and customizing the jinja2 template. Args: models (Model or Document or seq[Model]) : Bokeh object or objects to render typically a Model or Document resources (Resources or tuple(JSResources or None, CSSResources or None)) : A resource configuration for Bokeh JS & CSS assets. title (str, optional) : A title for the HTML document ``<title>`` tags or None. (default: None) If None, attempt to automatically find the Document title from the given plot objects. template (Template, optional) : HTML document template (default: FILE) A Jinja2 Template, see bokeh.core.templates.FILE for the required template parameters template_variables (dict, optional) : variables to be used in the Jinja2 template. If used, the following variable names will be overwritten: title, bokeh_js, bokeh_css, plot_script, plot_div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. suppress_callback_warning (bool, optional) : Normally generating standalone HTML from a Bokeh Document that has Python callbacks will result in a warning stating that the callbacks cannot function. However, this warning can be suppressed by setting this value to True (default: False) Returns: UTF-8 encoded HTML ''' if isinstance(models, Model): models = [models] if isinstance(models, Document): models = models.roots with OutputDocumentFor(models, apply_theme=theme, always_new=_always_new) as doc: (docs_json, render_items) = standalone_docs_json_and_render_items(models, suppress_callback_warning=suppress_callback_warning) title = _title_from_models(models, title) bundle = bundle_for_objs_and_resources([doc], resources) return html_page_for_render_items(bundle, docs_json, render_items, title=title, template=template, template_variables=template_variables)
python
def file_html(models, resources, title=None, template=FILE, template_variables={}, theme=FromCurdoc, suppress_callback_warning=False, _always_new=False): ''' Return an HTML document that embeds Bokeh Model or Document objects. The data for the plot is stored directly in the returned HTML, with support for customizing the JS/CSS resources independently and customizing the jinja2 template. Args: models (Model or Document or seq[Model]) : Bokeh object or objects to render typically a Model or Document resources (Resources or tuple(JSResources or None, CSSResources or None)) : A resource configuration for Bokeh JS & CSS assets. title (str, optional) : A title for the HTML document ``<title>`` tags or None. (default: None) If None, attempt to automatically find the Document title from the given plot objects. template (Template, optional) : HTML document template (default: FILE) A Jinja2 Template, see bokeh.core.templates.FILE for the required template parameters template_variables (dict, optional) : variables to be used in the Jinja2 template. If used, the following variable names will be overwritten: title, bokeh_js, bokeh_css, plot_script, plot_div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. suppress_callback_warning (bool, optional) : Normally generating standalone HTML from a Bokeh Document that has Python callbacks will result in a warning stating that the callbacks cannot function. However, this warning can be suppressed by setting this value to True (default: False) Returns: UTF-8 encoded HTML ''' if isinstance(models, Model): models = [models] if isinstance(models, Document): models = models.roots with OutputDocumentFor(models, apply_theme=theme, always_new=_always_new) as doc: (docs_json, render_items) = standalone_docs_json_and_render_items(models, suppress_callback_warning=suppress_callback_warning) title = _title_from_models(models, title) bundle = bundle_for_objs_and_resources([doc], resources) return html_page_for_render_items(bundle, docs_json, render_items, title=title, template=template, template_variables=template_variables)
[ "def", "file_html", "(", "models", ",", "resources", ",", "title", "=", "None", ",", "template", "=", "FILE", ",", "template_variables", "=", "{", "}", ",", "theme", "=", "FromCurdoc", ",", "suppress_callback_warning", "=", "False", ",", "_always_new", "=", "False", ")", ":", "if", "isinstance", "(", "models", ",", "Model", ")", ":", "models", "=", "[", "models", "]", "if", "isinstance", "(", "models", ",", "Document", ")", ":", "models", "=", "models", ".", "roots", "with", "OutputDocumentFor", "(", "models", ",", "apply_theme", "=", "theme", ",", "always_new", "=", "_always_new", ")", "as", "doc", ":", "(", "docs_json", ",", "render_items", ")", "=", "standalone_docs_json_and_render_items", "(", "models", ",", "suppress_callback_warning", "=", "suppress_callback_warning", ")", "title", "=", "_title_from_models", "(", "models", ",", "title", ")", "bundle", "=", "bundle_for_objs_and_resources", "(", "[", "doc", "]", ",", "resources", ")", "return", "html_page_for_render_items", "(", "bundle", ",", "docs_json", ",", "render_items", ",", "title", "=", "title", ",", "template", "=", "template", ",", "template_variables", "=", "template_variables", ")" ]
Return an HTML document that embeds Bokeh Model or Document objects. The data for the plot is stored directly in the returned HTML, with support for customizing the JS/CSS resources independently and customizing the jinja2 template. Args: models (Model or Document or seq[Model]) : Bokeh object or objects to render typically a Model or Document resources (Resources or tuple(JSResources or None, CSSResources or None)) : A resource configuration for Bokeh JS & CSS assets. title (str, optional) : A title for the HTML document ``<title>`` tags or None. (default: None) If None, attempt to automatically find the Document title from the given plot objects. template (Template, optional) : HTML document template (default: FILE) A Jinja2 Template, see bokeh.core.templates.FILE for the required template parameters template_variables (dict, optional) : variables to be used in the Jinja2 template. If used, the following variable names will be overwritten: title, bokeh_js, bokeh_css, plot_script, plot_div theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. suppress_callback_warning (bool, optional) : Normally generating standalone HTML from a Bokeh Document that has Python callbacks will result in a warning stating that the callbacks cannot function. However, this warning can be suppressed by setting this value to True (default: False) Returns: UTF-8 encoded HTML
[ "Return", "an", "HTML", "document", "that", "embeds", "Bokeh", "Model", "or", "Document", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L250-L312
train
bokeh/bokeh
bokeh/embed/standalone.py
json_item
def json_item(model, target=None, theme=FromCurdoc): ''' Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must be supplied in the JavaScript call. theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: JSON-like This function returns a JSON block that can be consumed by the BokehJS function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for ``/plot`` might return the following content to embed a Bokeh plot into a div with id *"myplot"*: .. code-block:: python @app.route('/plot') def plot(): p = make_plot('petal_width', 'petal_length') return json.dumps(json_item(p, "myplot")) Then a web page can retrieve this JSON and embed the plot by calling ``Bokeh.embed.embed_item``: .. code-block:: html <script> fetch('/plot') .then(function(response) { return response.json(); }) .then(function(item) { Bokeh.embed.embed_item(item); }) </script> Alternatively, if is more convenient to supply the target div id directly in the page source, that is also possible. If `target_id` is omitted in the call to this function: .. code-block:: python return json.dumps(json_item(p)) Then the value passed to ``embed_item`` is used: .. code-block:: javascript Bokeh.embed.embed_item(item, "myplot"); ''' with OutputDocumentFor([model], apply_theme=theme) as doc: doc.title = "" docs_json = standalone_docs_json([model]) doc = list(docs_json.values())[0] root_id = doc['roots']['root_ids'][0] return { 'target_id' : target, 'root_id' : root_id, 'doc' : doc, }
python
def json_item(model, target=None, theme=FromCurdoc): ''' Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must be supplied in the JavaScript call. theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: JSON-like This function returns a JSON block that can be consumed by the BokehJS function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for ``/plot`` might return the following content to embed a Bokeh plot into a div with id *"myplot"*: .. code-block:: python @app.route('/plot') def plot(): p = make_plot('petal_width', 'petal_length') return json.dumps(json_item(p, "myplot")) Then a web page can retrieve this JSON and embed the plot by calling ``Bokeh.embed.embed_item``: .. code-block:: html <script> fetch('/plot') .then(function(response) { return response.json(); }) .then(function(item) { Bokeh.embed.embed_item(item); }) </script> Alternatively, if is more convenient to supply the target div id directly in the page source, that is also possible. If `target_id` is omitted in the call to this function: .. code-block:: python return json.dumps(json_item(p)) Then the value passed to ``embed_item`` is used: .. code-block:: javascript Bokeh.embed.embed_item(item, "myplot"); ''' with OutputDocumentFor([model], apply_theme=theme) as doc: doc.title = "" docs_json = standalone_docs_json([model]) doc = list(docs_json.values())[0] root_id = doc['roots']['root_ids'][0] return { 'target_id' : target, 'root_id' : root_id, 'doc' : doc, }
[ "def", "json_item", "(", "model", ",", "target", "=", "None", ",", "theme", "=", "FromCurdoc", ")", ":", "with", "OutputDocumentFor", "(", "[", "model", "]", ",", "apply_theme", "=", "theme", ")", "as", "doc", ":", "doc", ".", "title", "=", "\"\"", "docs_json", "=", "standalone_docs_json", "(", "[", "model", "]", ")", "doc", "=", "list", "(", "docs_json", ".", "values", "(", ")", ")", "[", "0", "]", "root_id", "=", "doc", "[", "'roots'", "]", "[", "'root_ids'", "]", "[", "0", "]", "return", "{", "'target_id'", ":", "target", ",", "'root_id'", ":", "root_id", ",", "'doc'", ":", "doc", ",", "}" ]
Return a JSON block that can be used to embed standalone Bokeh content. Args: model (Model) : The Bokeh object to embed target (string, optional) A div id to embed the model into. If None, the target id must be supplied in the JavaScript call. theme (Theme, optional) : Defaults to the ``Theme`` instance in the current document. Setting this to ``None`` uses the default theme or the theme already specified in the document. Any other value must be an instance of the ``Theme`` class. Returns: JSON-like This function returns a JSON block that can be consumed by the BokehJS function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for ``/plot`` might return the following content to embed a Bokeh plot into a div with id *"myplot"*: .. code-block:: python @app.route('/plot') def plot(): p = make_plot('petal_width', 'petal_length') return json.dumps(json_item(p, "myplot")) Then a web page can retrieve this JSON and embed the plot by calling ``Bokeh.embed.embed_item``: .. code-block:: html <script> fetch('/plot') .then(function(response) { return response.json(); }) .then(function(item) { Bokeh.embed.embed_item(item); }) </script> Alternatively, if is more convenient to supply the target div id directly in the page source, that is also possible. If `target_id` is omitted in the call to this function: .. code-block:: python return json.dumps(json_item(p)) Then the value passed to ``embed_item`` is used: .. code-block:: javascript Bokeh.embed.embed_item(item, "myplot");
[ "Return", "a", "JSON", "block", "that", "can", "be", "used", "to", "embed", "standalone", "Bokeh", "content", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L314-L383
train
bokeh/bokeh
bokeh/protocol/messages/patch_doc.py
process_document_events
def process_document_events(events, use_buffers=True): ''' Create a JSON string describing a patch to be applied as well as any optional buffers. Args: events : list of events to be translated into patches Returns: str, list : JSON string which can be applied to make the given updates to obj as well as any optional buffers ''' json_events = [] references = set() buffers = [] if use_buffers else None for event in events: json_events.append(event.generate(references, buffers)) json = { 'events' : json_events, 'references' : references_json(references), } return serialize_json(json), buffers if use_buffers else []
python
def process_document_events(events, use_buffers=True): ''' Create a JSON string describing a patch to be applied as well as any optional buffers. Args: events : list of events to be translated into patches Returns: str, list : JSON string which can be applied to make the given updates to obj as well as any optional buffers ''' json_events = [] references = set() buffers = [] if use_buffers else None for event in events: json_events.append(event.generate(references, buffers)) json = { 'events' : json_events, 'references' : references_json(references), } return serialize_json(json), buffers if use_buffers else []
[ "def", "process_document_events", "(", "events", ",", "use_buffers", "=", "True", ")", ":", "json_events", "=", "[", "]", "references", "=", "set", "(", ")", "buffers", "=", "[", "]", "if", "use_buffers", "else", "None", "for", "event", "in", "events", ":", "json_events", ".", "append", "(", "event", ".", "generate", "(", "references", ",", "buffers", ")", ")", "json", "=", "{", "'events'", ":", "json_events", ",", "'references'", ":", "references_json", "(", "references", ")", ",", "}", "return", "serialize_json", "(", "json", ")", ",", "buffers", "if", "use_buffers", "else", "[", "]" ]
Create a JSON string describing a patch to be applied as well as any optional buffers. Args: events : list of events to be translated into patches Returns: str, list : JSON string which can be applied to make the given updates to obj as well as any optional buffers
[ "Create", "a", "JSON", "string", "describing", "a", "patch", "to", "be", "applied", "as", "well", "as", "any", "optional", "buffers", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/messages/patch_doc.py#L109-L136
train
bokeh/bokeh
bokeh/server/callbacks.py
PeriodicCallback._copy_with_changed_callback
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return PeriodicCallback(self._document, new_callback, self._period, self._id)
python
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return PeriodicCallback(self._document, new_callback, self._period, self._id)
[ "def", "_copy_with_changed_callback", "(", "self", ",", "new_callback", ")", ":", "return", "PeriodicCallback", "(", "self", ".", "_document", ",", "new_callback", ",", "self", ".", "_period", ",", "self", ".", "_id", ")" ]
Dev API used to wrap the callback with decorators.
[ "Dev", "API", "used", "to", "wrap", "the", "callback", "with", "decorators", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/callbacks.py#L139-L141
train
bokeh/bokeh
bokeh/server/callbacks.py
TimeoutCallback._copy_with_changed_callback
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
python
def _copy_with_changed_callback(self, new_callback): ''' Dev API used to wrap the callback with decorators. ''' return TimeoutCallback(self._document, new_callback, self._timeout, self._id)
[ "def", "_copy_with_changed_callback", "(", "self", ",", "new_callback", ")", ":", "return", "TimeoutCallback", "(", "self", ".", "_document", ",", "new_callback", ",", "self", ".", "_timeout", ",", "self", ".", "_id", ")" ]
Dev API used to wrap the callback with decorators.
[ "Dev", "API", "used", "to", "wrap", "the", "callback", "with", "decorators", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/callbacks.py#L171-L173
train
bokeh/bokeh
bokeh/util/compiler.py
calc_cache_key
def calc_cache_key(custom_models): ''' Generate a key to cache a custom extension implementation with. There is no metadata other than the Model classes, so this is the only base to generate a cache key. We build the model keys from the list of ``model.full_name``. This is not ideal but possibly a better solution can be found found later. ''' model_names = {model.full_name for model in custom_models.values()} encoded_names = ",".join(sorted(model_names)).encode('utf-8') return hashlib.sha256(encoded_names).hexdigest()
python
def calc_cache_key(custom_models): ''' Generate a key to cache a custom extension implementation with. There is no metadata other than the Model classes, so this is the only base to generate a cache key. We build the model keys from the list of ``model.full_name``. This is not ideal but possibly a better solution can be found found later. ''' model_names = {model.full_name for model in custom_models.values()} encoded_names = ",".join(sorted(model_names)).encode('utf-8') return hashlib.sha256(encoded_names).hexdigest()
[ "def", "calc_cache_key", "(", "custom_models", ")", ":", "model_names", "=", "{", "model", ".", "full_name", "for", "model", "in", "custom_models", ".", "values", "(", ")", "}", "encoded_names", "=", "\",\"", ".", "join", "(", "sorted", "(", "model_names", ")", ")", ".", "encode", "(", "'utf-8'", ")", "return", "hashlib", ".", "sha256", "(", "encoded_names", ")", ".", "hexdigest", "(", ")" ]
Generate a key to cache a custom extension implementation with. There is no metadata other than the Model classes, so this is the only base to generate a cache key. We build the model keys from the list of ``model.full_name``. This is not ideal but possibly a better solution can be found found later.
[ "Generate", "a", "key", "to", "cache", "a", "custom", "extension", "implementation", "with", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L312-L324
train
bokeh/bokeh
bokeh/util/compiler.py
bundle_models
def bundle_models(models): """Create a bundle of selected `models`. """ custom_models = _get_custom_models(models) if custom_models is None: return None key = calc_cache_key(custom_models) bundle = _bundle_cache.get(key, None) if bundle is None: try: _bundle_cache[key] = bundle = _bundle_models(custom_models) except CompilationError as error: print("Compilation failed:", file=sys.stderr) print(str(error), file=sys.stderr) sys.exit(1) return bundle
python
def bundle_models(models): """Create a bundle of selected `models`. """ custom_models = _get_custom_models(models) if custom_models is None: return None key = calc_cache_key(custom_models) bundle = _bundle_cache.get(key, None) if bundle is None: try: _bundle_cache[key] = bundle = _bundle_models(custom_models) except CompilationError as error: print("Compilation failed:", file=sys.stderr) print(str(error), file=sys.stderr) sys.exit(1) return bundle
[ "def", "bundle_models", "(", "models", ")", ":", "custom_models", "=", "_get_custom_models", "(", "models", ")", "if", "custom_models", "is", "None", ":", "return", "None", "key", "=", "calc_cache_key", "(", "custom_models", ")", "bundle", "=", "_bundle_cache", ".", "get", "(", "key", ",", "None", ")", "if", "bundle", "is", "None", ":", "try", ":", "_bundle_cache", "[", "key", "]", "=", "bundle", "=", "_bundle_models", "(", "custom_models", ")", "except", "CompilationError", "as", "error", ":", "print", "(", "\"Compilation failed:\"", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "str", "(", "error", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "return", "bundle" ]
Create a bundle of selected `models`.
[ "Create", "a", "bundle", "of", "selected", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L328-L343
train
bokeh/bokeh
bokeh/util/compiler.py
_get_custom_models
def _get_custom_models(models): """Returns CustomModels for models with a custom `__implementation__`""" if models is None: models = Model.model_class_reverse_map.values() custom_models = OrderedDict() for cls in models: impl = getattr(cls, "__implementation__", None) if impl is not None: model = CustomModel(cls) custom_models[model.full_name] = model if not custom_models: return None return custom_models
python
def _get_custom_models(models): """Returns CustomModels for models with a custom `__implementation__`""" if models is None: models = Model.model_class_reverse_map.values() custom_models = OrderedDict() for cls in models: impl = getattr(cls, "__implementation__", None) if impl is not None: model = CustomModel(cls) custom_models[model.full_name] = model if not custom_models: return None return custom_models
[ "def", "_get_custom_models", "(", "models", ")", ":", "if", "models", "is", "None", ":", "models", "=", "Model", ".", "model_class_reverse_map", ".", "values", "(", ")", "custom_models", "=", "OrderedDict", "(", ")", "for", "cls", "in", "models", ":", "impl", "=", "getattr", "(", "cls", ",", "\"__implementation__\"", ",", "None", ")", "if", "impl", "is", "not", "None", ":", "model", "=", "CustomModel", "(", "cls", ")", "custom_models", "[", "model", ".", "full_name", "]", "=", "model", "if", "not", "custom_models", ":", "return", "None", "return", "custom_models" ]
Returns CustomModels for models with a custom `__implementation__`
[ "Returns", "CustomModels", "for", "models", "with", "a", "custom", "__implementation__" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L501-L516
train
bokeh/bokeh
bokeh/util/compiler.py
_compile_models
def _compile_models(custom_models): """Returns the compiled implementation of supplied `models`. """ ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name) custom_impls = {} dependencies = [] for model in ordered_models: dependencies.extend(list(model.dependencies.items())) if dependencies: dependencies = sorted(dependencies, key=lambda name_version: name_version[0]) _run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ]) for model in ordered_models: impl = model.implementation compiled = _CACHING_IMPLEMENTATION(model, impl) if compiled is None: compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) custom_impls[model.full_name] = compiled return custom_impls
python
def _compile_models(custom_models): """Returns the compiled implementation of supplied `models`. """ ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name) custom_impls = {} dependencies = [] for model in ordered_models: dependencies.extend(list(model.dependencies.items())) if dependencies: dependencies = sorted(dependencies, key=lambda name_version: name_version[0]) _run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ]) for model in ordered_models: impl = model.implementation compiled = _CACHING_IMPLEMENTATION(model, impl) if compiled is None: compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) custom_impls[model.full_name] = compiled return custom_impls
[ "def", "_compile_models", "(", "custom_models", ")", ":", "ordered_models", "=", "sorted", "(", "custom_models", ".", "values", "(", ")", ",", "key", "=", "lambda", "model", ":", "model", ".", "full_name", ")", "custom_impls", "=", "{", "}", "dependencies", "=", "[", "]", "for", "model", "in", "ordered_models", ":", "dependencies", ".", "extend", "(", "list", "(", "model", ".", "dependencies", ".", "items", "(", ")", ")", ")", "if", "dependencies", ":", "dependencies", "=", "sorted", "(", "dependencies", ",", "key", "=", "lambda", "name_version", ":", "name_version", "[", "0", "]", ")", "_run_npmjs", "(", "[", "\"install\"", ",", "\"--no-progress\"", "]", "+", "[", "name", "+", "\"@\"", "+", "version", "for", "(", "name", ",", "version", ")", "in", "dependencies", "]", ")", "for", "model", "in", "ordered_models", ":", "impl", "=", "model", ".", "implementation", "compiled", "=", "_CACHING_IMPLEMENTATION", "(", "model", ",", "impl", ")", "if", "compiled", "is", "None", ":", "compiled", "=", "nodejs_compile", "(", "impl", ".", "code", ",", "lang", "=", "impl", ".", "lang", ",", "file", "=", "impl", ".", "file", ")", "if", "\"error\"", "in", "compiled", ":", "raise", "CompilationError", "(", "compiled", ".", "error", ")", "custom_impls", "[", "model", ".", "full_name", "]", "=", "compiled", "return", "custom_impls" ]
Returns the compiled implementation of supplied `models`.
[ "Returns", "the", "compiled", "implementation", "of", "supplied", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L518-L542
train
bokeh/bokeh
bokeh/util/compiler.py
_bundle_models
def _bundle_models(custom_models): """ Create a JavaScript bundle with selected `models`. """ exports = [] modules = [] def read_json(name): with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f: return json.loads(f.read()) bundles = ["bokeh", "bokeh-api", "bokeh-widgets", "bokeh-tables", "bokeh-gl"] known_modules = set(sum([ read_json(name) for name in bundles ], [])) custom_impls = _compile_models(custom_models) extra_modules = {} def resolve_modules(to_resolve, root): resolved = {} for module in to_resolve: if module.startswith(("./", "../")): def mkpath(module, ext=""): return abspath(join(root, *module.split("/")) + ext) if module.endswith(exts): path = mkpath(module) if not exists(path): raise RuntimeError("no such module: %s" % module) else: for ext in exts: path = mkpath(module, ext) if exists(path): break else: raise RuntimeError("no such module: %s" % module) impl = FromFile(path) compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) if impl.lang == "less": code = _style_template % dict(css=json.dumps(compiled.code)) deps = [] else: code = compiled.code deps = compiled.deps sig = hashlib.sha256(code.encode('utf-8')).hexdigest() resolved[module] = sig deps_map = resolve_deps(deps, dirname(path)) if sig not in extra_modules: extra_modules[sig] = True modules.append((sig, code, deps_map)) else: index = module + ("" if module.endswith("/") else "/") + "index" if index not in known_modules: raise RuntimeError("no such module: %s" % module) return resolved def resolve_deps(deps, root): custom_modules = set(model.module for model in custom_models.values()) missing = set(deps) - known_modules - custom_modules return resolve_modules(missing, root) for model in custom_models.values(): compiled = custom_impls[model.full_name] deps_map = resolve_deps(compiled.deps, model.path) exports.append((model.name, model.module)) modules.append((model.module, compiled.code, deps_map)) # sort everything by module name exports = sorted(exports, key=lambda spec: spec[1]) modules = sorted(modules, key=lambda spec: spec[0]) for i, (module, code, deps) in enumerate(modules): for name, ref in deps.items(): code = code.replace("""require("%s")""" % name, """require("%s")""" % ref) code = code.replace("""require('%s')""" % name, """require('%s')""" % ref) modules[i] = (module, code) sep = ",\n" exports = sep.join(_export_template % dict(name=name, module=module) for (name, module) in exports) modules = sep.join(_module_template % dict(module=module, source=code) for (module, code) in modules) content = _plugin_template % dict(prelude=_plugin_prelude, exports=exports, modules=modules) return _plugin_umd % dict(content=content)
python
def _bundle_models(custom_models): """ Create a JavaScript bundle with selected `models`. """ exports = [] modules = [] def read_json(name): with io.open(join(bokehjs_dir, "js", name + ".json"), encoding="utf-8") as f: return json.loads(f.read()) bundles = ["bokeh", "bokeh-api", "bokeh-widgets", "bokeh-tables", "bokeh-gl"] known_modules = set(sum([ read_json(name) for name in bundles ], [])) custom_impls = _compile_models(custom_models) extra_modules = {} def resolve_modules(to_resolve, root): resolved = {} for module in to_resolve: if module.startswith(("./", "../")): def mkpath(module, ext=""): return abspath(join(root, *module.split("/")) + ext) if module.endswith(exts): path = mkpath(module) if not exists(path): raise RuntimeError("no such module: %s" % module) else: for ext in exts: path = mkpath(module, ext) if exists(path): break else: raise RuntimeError("no such module: %s" % module) impl = FromFile(path) compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file) if "error" in compiled: raise CompilationError(compiled.error) if impl.lang == "less": code = _style_template % dict(css=json.dumps(compiled.code)) deps = [] else: code = compiled.code deps = compiled.deps sig = hashlib.sha256(code.encode('utf-8')).hexdigest() resolved[module] = sig deps_map = resolve_deps(deps, dirname(path)) if sig not in extra_modules: extra_modules[sig] = True modules.append((sig, code, deps_map)) else: index = module + ("" if module.endswith("/") else "/") + "index" if index not in known_modules: raise RuntimeError("no such module: %s" % module) return resolved def resolve_deps(deps, root): custom_modules = set(model.module for model in custom_models.values()) missing = set(deps) - known_modules - custom_modules return resolve_modules(missing, root) for model in custom_models.values(): compiled = custom_impls[model.full_name] deps_map = resolve_deps(compiled.deps, model.path) exports.append((model.name, model.module)) modules.append((model.module, compiled.code, deps_map)) # sort everything by module name exports = sorted(exports, key=lambda spec: spec[1]) modules = sorted(modules, key=lambda spec: spec[0]) for i, (module, code, deps) in enumerate(modules): for name, ref in deps.items(): code = code.replace("""require("%s")""" % name, """require("%s")""" % ref) code = code.replace("""require('%s')""" % name, """require('%s')""" % ref) modules[i] = (module, code) sep = ",\n" exports = sep.join(_export_template % dict(name=name, module=module) for (name, module) in exports) modules = sep.join(_module_template % dict(module=module, source=code) for (module, code) in modules) content = _plugin_template % dict(prelude=_plugin_prelude, exports=exports, modules=modules) return _plugin_umd % dict(content=content)
[ "def", "_bundle_models", "(", "custom_models", ")", ":", "exports", "=", "[", "]", "modules", "=", "[", "]", "def", "read_json", "(", "name", ")", ":", "with", "io", ".", "open", "(", "join", "(", "bokehjs_dir", ",", "\"js\"", ",", "name", "+", "\".json\"", ")", ",", "encoding", "=", "\"utf-8\"", ")", "as", "f", ":", "return", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "bundles", "=", "[", "\"bokeh\"", ",", "\"bokeh-api\"", ",", "\"bokeh-widgets\"", ",", "\"bokeh-tables\"", ",", "\"bokeh-gl\"", "]", "known_modules", "=", "set", "(", "sum", "(", "[", "read_json", "(", "name", ")", "for", "name", "in", "bundles", "]", ",", "[", "]", ")", ")", "custom_impls", "=", "_compile_models", "(", "custom_models", ")", "extra_modules", "=", "{", "}", "def", "resolve_modules", "(", "to_resolve", ",", "root", ")", ":", "resolved", "=", "{", "}", "for", "module", "in", "to_resolve", ":", "if", "module", ".", "startswith", "(", "(", "\"./\"", ",", "\"../\"", ")", ")", ":", "def", "mkpath", "(", "module", ",", "ext", "=", "\"\"", ")", ":", "return", "abspath", "(", "join", "(", "root", ",", "*", "module", ".", "split", "(", "\"/\"", ")", ")", "+", "ext", ")", "if", "module", ".", "endswith", "(", "exts", ")", ":", "path", "=", "mkpath", "(", "module", ")", "if", "not", "exists", "(", "path", ")", ":", "raise", "RuntimeError", "(", "\"no such module: %s\"", "%", "module", ")", "else", ":", "for", "ext", "in", "exts", ":", "path", "=", "mkpath", "(", "module", ",", "ext", ")", "if", "exists", "(", "path", ")", ":", "break", "else", ":", "raise", "RuntimeError", "(", "\"no such module: %s\"", "%", "module", ")", "impl", "=", "FromFile", "(", "path", ")", "compiled", "=", "nodejs_compile", "(", "impl", ".", "code", ",", "lang", "=", "impl", ".", "lang", ",", "file", "=", "impl", ".", "file", ")", "if", "\"error\"", "in", "compiled", ":", "raise", "CompilationError", "(", "compiled", ".", "error", ")", "if", "impl", ".", "lang", "==", "\"less\"", ":", "code", "=", "_style_template", "%", "dict", "(", "css", "=", "json", ".", "dumps", "(", "compiled", ".", "code", ")", ")", "deps", "=", "[", "]", "else", ":", "code", "=", "compiled", ".", "code", "deps", "=", "compiled", ".", "deps", "sig", "=", "hashlib", ".", "sha256", "(", "code", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "resolved", "[", "module", "]", "=", "sig", "deps_map", "=", "resolve_deps", "(", "deps", ",", "dirname", "(", "path", ")", ")", "if", "sig", "not", "in", "extra_modules", ":", "extra_modules", "[", "sig", "]", "=", "True", "modules", ".", "append", "(", "(", "sig", ",", "code", ",", "deps_map", ")", ")", "else", ":", "index", "=", "module", "+", "(", "\"\"", "if", "module", ".", "endswith", "(", "\"/\"", ")", "else", "\"/\"", ")", "+", "\"index\"", "if", "index", "not", "in", "known_modules", ":", "raise", "RuntimeError", "(", "\"no such module: %s\"", "%", "module", ")", "return", "resolved", "def", "resolve_deps", "(", "deps", ",", "root", ")", ":", "custom_modules", "=", "set", "(", "model", ".", "module", "for", "model", "in", "custom_models", ".", "values", "(", ")", ")", "missing", "=", "set", "(", "deps", ")", "-", "known_modules", "-", "custom_modules", "return", "resolve_modules", "(", "missing", ",", "root", ")", "for", "model", "in", "custom_models", ".", "values", "(", ")", ":", "compiled", "=", "custom_impls", "[", "model", ".", "full_name", "]", "deps_map", "=", "resolve_deps", "(", "compiled", ".", "deps", ",", "model", ".", "path", ")", "exports", ".", "append", "(", "(", "model", ".", "name", ",", "model", ".", "module", ")", ")", "modules", ".", "append", "(", "(", "model", ".", "module", ",", "compiled", ".", "code", ",", "deps_map", ")", ")", "# sort everything by module name", "exports", "=", "sorted", "(", "exports", ",", "key", "=", "lambda", "spec", ":", "spec", "[", "1", "]", ")", "modules", "=", "sorted", "(", "modules", ",", "key", "=", "lambda", "spec", ":", "spec", "[", "0", "]", ")", "for", "i", ",", "(", "module", ",", "code", ",", "deps", ")", "in", "enumerate", "(", "modules", ")", ":", "for", "name", ",", "ref", "in", "deps", ".", "items", "(", ")", ":", "code", "=", "code", ".", "replace", "(", "\"\"\"require(\"%s\")\"\"\"", "%", "name", ",", "\"\"\"require(\"%s\")\"\"\"", "%", "ref", ")", "code", "=", "code", ".", "replace", "(", "\"\"\"require('%s')\"\"\"", "%", "name", ",", "\"\"\"require('%s')\"\"\"", "%", "ref", ")", "modules", "[", "i", "]", "=", "(", "module", ",", "code", ")", "sep", "=", "\",\\n\"", "exports", "=", "sep", ".", "join", "(", "_export_template", "%", "dict", "(", "name", "=", "name", ",", "module", "=", "module", ")", "for", "(", "name", ",", "module", ")", "in", "exports", ")", "modules", "=", "sep", ".", "join", "(", "_module_template", "%", "dict", "(", "module", "=", "module", ",", "source", "=", "code", ")", "for", "(", "module", ",", "code", ")", "in", "modules", ")", "content", "=", "_plugin_template", "%", "dict", "(", "prelude", "=", "_plugin_prelude", ",", "exports", "=", "exports", ",", "modules", "=", "modules", ")", "return", "_plugin_umd", "%", "dict", "(", "content", "=", "content", ")" ]
Create a JavaScript bundle with selected `models`.
[ "Create", "a", "JavaScript", "bundle", "with", "selected", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L544-L634
train
bokeh/bokeh
bokeh/command/util.py
die
def die(message, status=1): ''' Print an error message and exit. This function will call ``sys.exit`` with the given ``status`` and the process will terminate. Args: message (str) : error message to print status (int) : the exit status to pass to ``sys.exit`` ''' print(message, file=sys.stderr) sys.exit(status)
python
def die(message, status=1): ''' Print an error message and exit. This function will call ``sys.exit`` with the given ``status`` and the process will terminate. Args: message (str) : error message to print status (int) : the exit status to pass to ``sys.exit`` ''' print(message, file=sys.stderr) sys.exit(status)
[ "def", "die", "(", "message", ",", "status", "=", "1", ")", ":", "print", "(", "message", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "status", ")" ]
Print an error message and exit. This function will call ``sys.exit`` with the given ``status`` and the process will terminate. Args: message (str) : error message to print status (int) : the exit status to pass to ``sys.exit``
[ "Print", "an", "error", "message", "and", "exit", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L52-L65
train
bokeh/bokeh
bokeh/command/util.py
build_single_handler_application
def build_single_handler_application(path, argv=None): ''' Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize :class:`~bokeh.document.Document` objects for new client sessions. However, in many cases only a single handler is needed. This function examines the ``path`` provided, and returns an ``Application`` initialized with one of the following handlers: * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path`` is to a ``.py`` script. * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when ``path`` is to an ``.ipynb`` Jupyter notebook. * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when ``path`` is to a directory containing a ``main.py`` script. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: :class:`~bokeh.application.application.Application` Raises: RuntimeError Notes: If ``path`` ends with a file ``main.py`` then a warning will be printed regarding running directory-style apps by passing the directory instead. ''' argv = argv or [] path = os.path.abspath(path) # There are certainly race conditions here if the file/directory is deleted # in between the isdir/isfile tests and subsequent code. But it would be a # failure if they were not there to begin with, too (just a different error) if os.path.isdir(path): handler = DirectoryHandler(filename=path, argv=argv) elif os.path.isfile(path): if path.endswith(".ipynb"): handler = NotebookHandler(filename=path, argv=argv) elif path.endswith(".py"): if path.endswith("main.py"): warnings.warn(DIRSTYLE_MAIN_WARNING) handler = ScriptHandler(filename=path, argv=argv) else: raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) else: raise ValueError("Path for Bokeh server application does not exist: %s" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
python
def build_single_handler_application(path, argv=None): ''' Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize :class:`~bokeh.document.Document` objects for new client sessions. However, in many cases only a single handler is needed. This function examines the ``path`` provided, and returns an ``Application`` initialized with one of the following handlers: * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path`` is to a ``.py`` script. * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when ``path`` is to an ``.ipynb`` Jupyter notebook. * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when ``path`` is to a directory containing a ``main.py`` script. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: :class:`~bokeh.application.application.Application` Raises: RuntimeError Notes: If ``path`` ends with a file ``main.py`` then a warning will be printed regarding running directory-style apps by passing the directory instead. ''' argv = argv or [] path = os.path.abspath(path) # There are certainly race conditions here if the file/directory is deleted # in between the isdir/isfile tests and subsequent code. But it would be a # failure if they were not there to begin with, too (just a different error) if os.path.isdir(path): handler = DirectoryHandler(filename=path, argv=argv) elif os.path.isfile(path): if path.endswith(".ipynb"): handler = NotebookHandler(filename=path, argv=argv) elif path.endswith(".py"): if path.endswith("main.py"): warnings.warn(DIRSTYLE_MAIN_WARNING) handler = ScriptHandler(filename=path, argv=argv) else: raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path) else: raise ValueError("Path for Bokeh server application does not exist: %s" % path) if handler.failed: raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail)) application = Application(handler) return application
[ "def", "build_single_handler_application", "(", "path", ",", "argv", "=", "None", ")", ":", "argv", "=", "argv", "or", "[", "]", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "# There are certainly race conditions here if the file/directory is deleted", "# in between the isdir/isfile tests and subsequent code. But it would be a", "# failure if they were not there to begin with, too (just a different error)", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "handler", "=", "DirectoryHandler", "(", "filename", "=", "path", ",", "argv", "=", "argv", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "if", "path", ".", "endswith", "(", "\".ipynb\"", ")", ":", "handler", "=", "NotebookHandler", "(", "filename", "=", "path", ",", "argv", "=", "argv", ")", "elif", "path", ".", "endswith", "(", "\".py\"", ")", ":", "if", "path", ".", "endswith", "(", "\"main.py\"", ")", ":", "warnings", ".", "warn", "(", "DIRSTYLE_MAIN_WARNING", ")", "handler", "=", "ScriptHandler", "(", "filename", "=", "path", ",", "argv", "=", "argv", ")", "else", ":", "raise", "ValueError", "(", "\"Expected a '.py' script or '.ipynb' notebook, got: '%s'\"", "%", "path", ")", "else", ":", "raise", "ValueError", "(", "\"Path for Bokeh server application does not exist: %s\"", "%", "path", ")", "if", "handler", ".", "failed", ":", "raise", "RuntimeError", "(", "\"Error loading %s:\\n\\n%s\\n%s \"", "%", "(", "path", ",", "handler", ".", "error", ",", "handler", ".", "error_detail", ")", ")", "application", "=", "Application", "(", "handler", ")", "return", "application" ]
Return a Bokeh application built using a single handler for a script, notebook, or directory. In general a Bokeh :class:`~bokeh.application.application.Application` may have any number of handlers to initialize :class:`~bokeh.document.Document` objects for new client sessions. However, in many cases only a single handler is needed. This function examines the ``path`` provided, and returns an ``Application`` initialized with one of the following handlers: * :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path`` is to a ``.py`` script. * :class:`~bokeh.application.handlers.notebook.NotebookHandler` when ``path`` is to an ``.ipynb`` Jupyter notebook. * :class:`~bokeh.application.handlers.directory.DirectoryHandler` when ``path`` is to a directory containing a ``main.py`` script. Args: path (str) : path to a file or directory for creating a Bokeh application. argv (seq[str], optional) : command line arguments to pass to the application handler Returns: :class:`~bokeh.application.application.Application` Raises: RuntimeError Notes: If ``path`` ends with a file ``main.py`` then a warning will be printed regarding running directory-style apps by passing the directory instead.
[ "Return", "a", "Bokeh", "application", "built", "using", "a", "single", "handler", "for", "a", "script", "notebook", "or", "directory", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L77-L139
train
bokeh/bokeh
bokeh/command/util.py
build_single_handler_applications
def build_single_handler_applications(paths, argvs=None): ''' Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_application` on each to generate the mapping. Args: path (seq[str]) : paths to files or directories for creating Bokeh applications. argvs (dict[str, list[str]], optional) : mapping of paths to command line arguments to pass to the handler for each path Returns: dict[str, Application] Raises: RuntimeError ''' applications = {} argvs = {} or argvs for path in paths: application = build_single_handler_application(path, argvs.get(path, [])) route = application.handlers[0].url_path() if not route: if '/' in applications: raise RuntimeError("Don't know the URL path to use for %s" % (path)) route = '/' applications[route] = application return applications
python
def build_single_handler_applications(paths, argvs=None): ''' Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_application` on each to generate the mapping. Args: path (seq[str]) : paths to files or directories for creating Bokeh applications. argvs (dict[str, list[str]], optional) : mapping of paths to command line arguments to pass to the handler for each path Returns: dict[str, Application] Raises: RuntimeError ''' applications = {} argvs = {} or argvs for path in paths: application = build_single_handler_application(path, argvs.get(path, [])) route = application.handlers[0].url_path() if not route: if '/' in applications: raise RuntimeError("Don't know the URL path to use for %s" % (path)) route = '/' applications[route] = application return applications
[ "def", "build_single_handler_applications", "(", "paths", ",", "argvs", "=", "None", ")", ":", "applications", "=", "{", "}", "argvs", "=", "{", "}", "or", "argvs", "for", "path", "in", "paths", ":", "application", "=", "build_single_handler_application", "(", "path", ",", "argvs", ".", "get", "(", "path", ",", "[", "]", ")", ")", "route", "=", "application", ".", "handlers", "[", "0", "]", ".", "url_path", "(", ")", "if", "not", "route", ":", "if", "'/'", "in", "applications", ":", "raise", "RuntimeError", "(", "\"Don't know the URL path to use for %s\"", "%", "(", "path", ")", ")", "route", "=", "'/'", "applications", "[", "route", "]", "=", "application", "return", "applications" ]
Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_application` on each to generate the mapping. Args: path (seq[str]) : paths to files or directories for creating Bokeh applications. argvs (dict[str, list[str]], optional) : mapping of paths to command line arguments to pass to the handler for each path Returns: dict[str, Application] Raises: RuntimeError
[ "Return", "a", "dictionary", "mapping", "routes", "to", "Bokeh", "applications", "built", "using", "single", "handlers", "for", "specified", "files", "or", "directories", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L141-L177
train
bokeh/bokeh
bokeh/command/util.py
report_server_init_errors
def report_server_init_errors(address=None, port=None, **kwargs): ''' A context manager to help print more informative error messages when a ``Server`` cannot be started due to a network problem. Args: address (str) : network address that the server will be listening on port (int) : network address that the server will be listening on Example: .. code-block:: python with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) If there are any errors (e.g. port or address in already in use) then a critical error will be logged and the process will terminate with a call to ``sys.exit(1)`` ''' try: yield except EnvironmentError as e: if e.errno == errno.EADDRINUSE: log.critical("Cannot start Bokeh server, port %s is already in use", port) elif e.errno == errno.EADDRNOTAVAIL: log.critical("Cannot start Bokeh server, address '%s' not available", address) else: codename = errno.errorcode[e.errno] log.critical("Cannot start Bokeh server [%s]: %r", codename, e) sys.exit(1)
python
def report_server_init_errors(address=None, port=None, **kwargs): ''' A context manager to help print more informative error messages when a ``Server`` cannot be started due to a network problem. Args: address (str) : network address that the server will be listening on port (int) : network address that the server will be listening on Example: .. code-block:: python with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) If there are any errors (e.g. port or address in already in use) then a critical error will be logged and the process will terminate with a call to ``sys.exit(1)`` ''' try: yield except EnvironmentError as e: if e.errno == errno.EADDRINUSE: log.critical("Cannot start Bokeh server, port %s is already in use", port) elif e.errno == errno.EADDRNOTAVAIL: log.critical("Cannot start Bokeh server, address '%s' not available", address) else: codename = errno.errorcode[e.errno] log.critical("Cannot start Bokeh server [%s]: %r", codename, e) sys.exit(1)
[ "def", "report_server_init_errors", "(", "address", "=", "None", ",", "port", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "yield", "except", "EnvironmentError", "as", "e", ":", "if", "e", ".", "errno", "==", "errno", ".", "EADDRINUSE", ":", "log", ".", "critical", "(", "\"Cannot start Bokeh server, port %s is already in use\"", ",", "port", ")", "elif", "e", ".", "errno", "==", "errno", ".", "EADDRNOTAVAIL", ":", "log", ".", "critical", "(", "\"Cannot start Bokeh server, address '%s' not available\"", ",", "address", ")", "else", ":", "codename", "=", "errno", ".", "errorcode", "[", "e", ".", "errno", "]", "log", ".", "critical", "(", "\"Cannot start Bokeh server [%s]: %r\"", ",", "codename", ",", "e", ")", "sys", ".", "exit", "(", "1", ")" ]
A context manager to help print more informative error messages when a ``Server`` cannot be started due to a network problem. Args: address (str) : network address that the server will be listening on port (int) : network address that the server will be listening on Example: .. code-block:: python with report_server_init_errors(**server_kwargs): server = Server(applications, **server_kwargs) If there are any errors (e.g. port or address in already in use) then a critical error will be logged and the process will terminate with a call to ``sys.exit(1)``
[ "A", "context", "manager", "to", "help", "print", "more", "informative", "error", "messages", "when", "a", "Server", "cannot", "be", "started", "due", "to", "a", "network", "problem", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L181-L212
train
bokeh/bokeh
examples/models/file/trail.py
distance
def distance(p1, p2): """Distance between (lat1, lon1) and (lat2, lon2). """ R = 6371 lat1, lon1 = p1 lat2, lon2 = p2 phi1 = radians(lat1) phi2 = radians(lat2) delta_lat = radians(lat2 - lat1) delta_lon = radians(lon2 - lon1) a = haversin(delta_lat) + cos(phi1) * cos(phi2) * haversin(delta_lon) return 2 * R * atan2(sqrt(a), sqrt(1 - a))
python
def distance(p1, p2): """Distance between (lat1, lon1) and (lat2, lon2). """ R = 6371 lat1, lon1 = p1 lat2, lon2 = p2 phi1 = radians(lat1) phi2 = radians(lat2) delta_lat = radians(lat2 - lat1) delta_lon = radians(lon2 - lon1) a = haversin(delta_lat) + cos(phi1) * cos(phi2) * haversin(delta_lon) return 2 * R * atan2(sqrt(a), sqrt(1 - a))
[ "def", "distance", "(", "p1", ",", "p2", ")", ":", "R", "=", "6371", "lat1", ",", "lon1", "=", "p1", "lat2", ",", "lon2", "=", "p2", "phi1", "=", "radians", "(", "lat1", ")", "phi2", "=", "radians", "(", "lat2", ")", "delta_lat", "=", "radians", "(", "lat2", "-", "lat1", ")", "delta_lon", "=", "radians", "(", "lon2", "-", "lon1", ")", "a", "=", "haversin", "(", "delta_lat", ")", "+", "cos", "(", "phi1", ")", "*", "cos", "(", "phi2", ")", "*", "haversin", "(", "delta_lon", ")", "return", "2", "*", "R", "*", "atan2", "(", "sqrt", "(", "a", ")", ",", "sqrt", "(", "1", "-", "a", ")", ")" ]
Distance between (lat1, lon1) and (lat2, lon2).
[ "Distance", "between", "(", "lat1", "lon1", ")", "and", "(", "lat2", "lon2", ")", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/models/file/trail.py#L29-L42
train
bokeh/bokeh
bokeh/sphinxext/bokeh_plot.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' # These two are deprecated and no longer have any effect, to be removed 2.0 app.add_config_value('bokeh_plot_pyfile_include_dirs', [], 'html') app.add_config_value('bokeh_plot_use_relative_paths', False, 'html') app.add_directive('bokeh-plot', BokehPlotDirective) app.add_config_value('bokeh_missing_google_api_key_ok', True, 'html') app.connect('builder-inited', builder_inited) app.connect('build-finished', build_finished)
python
def setup(app): ''' Required Sphinx extension setup function. ''' # These two are deprecated and no longer have any effect, to be removed 2.0 app.add_config_value('bokeh_plot_pyfile_include_dirs', [], 'html') app.add_config_value('bokeh_plot_use_relative_paths', False, 'html') app.add_directive('bokeh-plot', BokehPlotDirective) app.add_config_value('bokeh_missing_google_api_key_ok', True, 'html') app.connect('builder-inited', builder_inited) app.connect('build-finished', build_finished)
[ "def", "setup", "(", "app", ")", ":", "# These two are deprecated and no longer have any effect, to be removed 2.0", "app", ".", "add_config_value", "(", "'bokeh_plot_pyfile_include_dirs'", ",", "[", "]", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'bokeh_plot_use_relative_paths'", ",", "False", ",", "'html'", ")", "app", ".", "add_directive", "(", "'bokeh-plot'", ",", "BokehPlotDirective", ")", "app", ".", "add_config_value", "(", "'bokeh_missing_google_api_key_ok'", ",", "True", ",", "'html'", ")", "app", ".", "connect", "(", "'builder-inited'", ",", "builder_inited", ")", "app", ".", "connect", "(", "'build-finished'", ",", "build_finished", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_plot.py#L212-L222
train
bokeh/bokeh
bokeh/server/util.py
bind_sockets
def bind_sockets(address, port): ''' Bind a socket to a port on an address. Args: address (str) : An address to bind a port on, e.g. ``"localhost"`` port (int) : A port number to bind. Pass 0 to have the OS automatically choose a free port. This function returns a 2-tuple with the new socket as the first element, and the port that was bound as the second. (Useful when passing 0 as a port number to bind any free port.) Returns: (socket, port) ''' ss = netutil.bind_sockets(port=port or 0, address=address) assert len(ss) ports = {s.getsockname()[1] for s in ss} assert len(ports) == 1, "Multiple ports assigned??" actual_port = ports.pop() if port: assert actual_port == port return ss, actual_port
python
def bind_sockets(address, port): ''' Bind a socket to a port on an address. Args: address (str) : An address to bind a port on, e.g. ``"localhost"`` port (int) : A port number to bind. Pass 0 to have the OS automatically choose a free port. This function returns a 2-tuple with the new socket as the first element, and the port that was bound as the second. (Useful when passing 0 as a port number to bind any free port.) Returns: (socket, port) ''' ss = netutil.bind_sockets(port=port or 0, address=address) assert len(ss) ports = {s.getsockname()[1] for s in ss} assert len(ports) == 1, "Multiple ports assigned??" actual_port = ports.pop() if port: assert actual_port == port return ss, actual_port
[ "def", "bind_sockets", "(", "address", ",", "port", ")", ":", "ss", "=", "netutil", ".", "bind_sockets", "(", "port", "=", "port", "or", "0", ",", "address", "=", "address", ")", "assert", "len", "(", "ss", ")", "ports", "=", "{", "s", ".", "getsockname", "(", ")", "[", "1", "]", "for", "s", "in", "ss", "}", "assert", "len", "(", "ports", ")", "==", "1", ",", "\"Multiple ports assigned??\"", "actual_port", "=", "ports", ".", "pop", "(", ")", "if", "port", ":", "assert", "actual_port", "==", "port", "return", "ss", ",", "actual_port" ]
Bind a socket to a port on an address. Args: address (str) : An address to bind a port on, e.g. ``"localhost"`` port (int) : A port number to bind. Pass 0 to have the OS automatically choose a free port. This function returns a 2-tuple with the new socket as the first element, and the port that was bound as the second. (Useful when passing 0 as a port number to bind any free port.) Returns: (socket, port)
[ "Bind", "a", "socket", "to", "a", "port", "on", "an", "address", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L46-L73
train
bokeh/bokeh
bokeh/server/util.py
check_whitelist
def check_whitelist(host, whitelist): ''' Check a given request host against a whitelist. Args: host (str) : A host string to compare against a whitelist. If the host does not specify a port, then ``":80"`` is implicitly assumed. whitelist (seq[str]) : A list of host patterns to match against Returns: ``True``, if ``host`` matches any pattern in ``whitelist``, otherwise ``False`` ''' if ':' not in host: host = host + ':80' if host in whitelist: return True return any(match_host(host, pattern) for pattern in whitelist)
python
def check_whitelist(host, whitelist): ''' Check a given request host against a whitelist. Args: host (str) : A host string to compare against a whitelist. If the host does not specify a port, then ``":80"`` is implicitly assumed. whitelist (seq[str]) : A list of host patterns to match against Returns: ``True``, if ``host`` matches any pattern in ``whitelist``, otherwise ``False`` ''' if ':' not in host: host = host + ':80' if host in whitelist: return True return any(match_host(host, pattern) for pattern in whitelist)
[ "def", "check_whitelist", "(", "host", ",", "whitelist", ")", ":", "if", "':'", "not", "in", "host", ":", "host", "=", "host", "+", "':80'", "if", "host", "in", "whitelist", ":", "return", "True", "return", "any", "(", "match_host", "(", "host", ",", "pattern", ")", "for", "pattern", "in", "whitelist", ")" ]
Check a given request host against a whitelist. Args: host (str) : A host string to compare against a whitelist. If the host does not specify a port, then ``":80"`` is implicitly assumed. whitelist (seq[str]) : A list of host patterns to match against Returns: ``True``, if ``host`` matches any pattern in ``whitelist``, otherwise ``False``
[ "Check", "a", "given", "request", "host", "against", "a", "whitelist", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L75-L99
train
bokeh/bokeh
bokeh/server/util.py
match_host
def match_host(host, pattern): ''' Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. This function will return ``True`` if the hostname matches the pattern, including any wildcards. If the pattern contains a port, the host string must also contain a matching port. Returns: bool Examples: >>> match_host('192.168.0.1:80', '192.168.0.1:80') True >>> match_host('192.168.0.1:80', '192.168.0.1') True >>> match_host('192.168.0.1:80', '192.168.0.1:8080') False >>> match_host('192.168.0.1', '192.168.0.2') False >>> match_host('192.168.0.1', '192.168.*.*') True >>> match_host('alice', 'alice') True >>> match_host('alice:80', 'alice') True >>> match_host('alice', 'bob') False >>> match_host('foo.example.com', 'foo.example.com.net') False >>> match_host('alice', '*') True >>> match_host('alice', '*:*') True >>> match_host('alice:80', '*') True >>> match_host('alice:80', '*:80') True >>> match_host('alice:8080', '*:80') False ''' if ':' in host: host, host_port = host.rsplit(':', 1) else: host_port = None if ':' in pattern: pattern, pattern_port = pattern.rsplit(':', 1) if pattern_port == '*': pattern_port = None else: pattern_port = None if pattern_port is not None and host_port != pattern_port: return False host = host.split('.') pattern = pattern.split('.') if len(pattern) > len(host): return False for h, p in zip(host, pattern): if h == p or p == '*': continue else: return False return True
python
def match_host(host, pattern): ''' Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. This function will return ``True`` if the hostname matches the pattern, including any wildcards. If the pattern contains a port, the host string must also contain a matching port. Returns: bool Examples: >>> match_host('192.168.0.1:80', '192.168.0.1:80') True >>> match_host('192.168.0.1:80', '192.168.0.1') True >>> match_host('192.168.0.1:80', '192.168.0.1:8080') False >>> match_host('192.168.0.1', '192.168.0.2') False >>> match_host('192.168.0.1', '192.168.*.*') True >>> match_host('alice', 'alice') True >>> match_host('alice:80', 'alice') True >>> match_host('alice', 'bob') False >>> match_host('foo.example.com', 'foo.example.com.net') False >>> match_host('alice', '*') True >>> match_host('alice', '*:*') True >>> match_host('alice:80', '*') True >>> match_host('alice:80', '*:80') True >>> match_host('alice:8080', '*:80') False ''' if ':' in host: host, host_port = host.rsplit(':', 1) else: host_port = None if ':' in pattern: pattern, pattern_port = pattern.rsplit(':', 1) if pattern_port == '*': pattern_port = None else: pattern_port = None if pattern_port is not None and host_port != pattern_port: return False host = host.split('.') pattern = pattern.split('.') if len(pattern) > len(host): return False for h, p in zip(host, pattern): if h == p or p == '*': continue else: return False return True
[ "def", "match_host", "(", "host", ",", "pattern", ")", ":", "if", "':'", "in", "host", ":", "host", ",", "host_port", "=", "host", ".", "rsplit", "(", "':'", ",", "1", ")", "else", ":", "host_port", "=", "None", "if", "':'", "in", "pattern", ":", "pattern", ",", "pattern_port", "=", "pattern", ".", "rsplit", "(", "':'", ",", "1", ")", "if", "pattern_port", "==", "'*'", ":", "pattern_port", "=", "None", "else", ":", "pattern_port", "=", "None", "if", "pattern_port", "is", "not", "None", "and", "host_port", "!=", "pattern_port", ":", "return", "False", "host", "=", "host", ".", "split", "(", "'.'", ")", "pattern", "=", "pattern", ".", "split", "(", "'.'", ")", "if", "len", "(", "pattern", ")", ">", "len", "(", "host", ")", ":", "return", "False", "for", "h", ",", "p", "in", "zip", "(", "host", ",", "pattern", ")", ":", "if", "h", "==", "p", "or", "p", "==", "'*'", ":", "continue", "else", ":", "return", "False", "return", "True" ]
Match a host string against a pattern Args: host (str) A hostname to compare to the given pattern pattern (str) A string representing a hostname pattern, possibly including wildcards for ip address octets or ports. This function will return ``True`` if the hostname matches the pattern, including any wildcards. If the pattern contains a port, the host string must also contain a matching port. Returns: bool Examples: >>> match_host('192.168.0.1:80', '192.168.0.1:80') True >>> match_host('192.168.0.1:80', '192.168.0.1') True >>> match_host('192.168.0.1:80', '192.168.0.1:8080') False >>> match_host('192.168.0.1', '192.168.0.2') False >>> match_host('192.168.0.1', '192.168.*.*') True >>> match_host('alice', 'alice') True >>> match_host('alice:80', 'alice') True >>> match_host('alice', 'bob') False >>> match_host('foo.example.com', 'foo.example.com.net') False >>> match_host('alice', '*') True >>> match_host('alice', '*:*') True >>> match_host('alice:80', '*') True >>> match_host('alice:80', '*:80') True >>> match_host('alice:8080', '*:80') False
[ "Match", "a", "host", "string", "against", "a", "pattern" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L164-L240
train
bokeh/bokeh
bokeh/io/state.py
State.notebook_type
def notebook_type(self, notebook_type): ''' Notebook type, acceptable values are 'jupyter' as well as any names defined by external notebook hooks that have been installed. ''' if notebook_type is None or not isinstance(notebook_type, string_types): raise ValueError("Notebook type must be a string") self._notebook_type = notebook_type.lower()
python
def notebook_type(self, notebook_type): ''' Notebook type, acceptable values are 'jupyter' as well as any names defined by external notebook hooks that have been installed. ''' if notebook_type is None or not isinstance(notebook_type, string_types): raise ValueError("Notebook type must be a string") self._notebook_type = notebook_type.lower()
[ "def", "notebook_type", "(", "self", ",", "notebook_type", ")", ":", "if", "notebook_type", "is", "None", "or", "not", "isinstance", "(", "notebook_type", ",", "string_types", ")", ":", "raise", "ValueError", "(", "\"Notebook type must be a string\"", ")", "self", ".", "_notebook_type", "=", "notebook_type", ".", "lower", "(", ")" ]
Notebook type, acceptable values are 'jupyter' as well as any names defined by external notebook hooks that have been installed.
[ "Notebook", "type", "acceptable", "values", "are", "jupyter", "as", "well", "as", "any", "names", "defined", "by", "external", "notebook", "hooks", "that", "have", "been", "installed", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/state.py#L124-L131
train
bokeh/bokeh
bokeh/io/state.py
State.output_file
def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None): ''' Configure output to a standalone HTML file. Calling ``output_file`` not clear the effects of any other calls to ``output_notebook``, etc. It adds an additional output destination (publishing to HTML files). Any other active output modes continue to be active. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources` for more details. root_dir (str, optional) : root dir to use for absolute resources (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. .. warning:: The specified output file will be overwritten on every save, e.g., every time ``show()`` or ``save()`` is called. ''' self._file = { 'filename' : filename, 'resources' : Resources(mode=mode, root_dir=root_dir), 'title' : title } if os.path.isfile(filename): log.info("Session output file '%s' already exists, will be overwritten." % filename)
python
def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None): ''' Configure output to a standalone HTML file. Calling ``output_file`` not clear the effects of any other calls to ``output_notebook``, etc. It adds an additional output destination (publishing to HTML files). Any other active output modes continue to be active. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources` for more details. root_dir (str, optional) : root dir to use for absolute resources (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. .. warning:: The specified output file will be overwritten on every save, e.g., every time ``show()`` or ``save()`` is called. ''' self._file = { 'filename' : filename, 'resources' : Resources(mode=mode, root_dir=root_dir), 'title' : title } if os.path.isfile(filename): log.info("Session output file '%s' already exists, will be overwritten." % filename)
[ "def", "output_file", "(", "self", ",", "filename", ",", "title", "=", "\"Bokeh Plot\"", ",", "mode", "=", "\"cdn\"", ",", "root_dir", "=", "None", ")", ":", "self", ".", "_file", "=", "{", "'filename'", ":", "filename", ",", "'resources'", ":", "Resources", "(", "mode", "=", "mode", ",", "root_dir", "=", "root_dir", ")", ",", "'title'", ":", "title", "}", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "log", ".", "info", "(", "\"Session output file '%s' already exists, will be overwritten.\"", "%", "filename", ")" ]
Configure output to a standalone HTML file. Calling ``output_file`` not clear the effects of any other calls to ``output_notebook``, etc. It adds an additional output destination (publishing to HTML files). Any other active output modes continue to be active. Args: filename (str) : a filename for saving the HTML document title (str, optional) : a title for the HTML document mode (str, optional) : how to include BokehJS (default: ``'cdn'``) One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or ``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources` for more details. root_dir (str, optional) : root dir to use for absolute resources (default: None) This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``. .. warning:: The specified output file will be overwritten on every save, e.g., every time ``show()`` or ``save()`` is called.
[ "Configure", "output", "to", "a", "standalone", "HTML", "file", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/state.py#L135-L171
train
bokeh/bokeh
bokeh/io/saving.py
save
def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs): ''' Save an HTML file with the data for the current document. Will fall back to the default output state (or an explicitly provided :class:`State` object) for ``filename``, ``resources``, or ``title`` if they are not provided. If the filename is not given and not provided via output state, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.html``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, use the default state configuration. resources (Resources, optional) : A Resources config to use (default: None) If None, use the default state configuration, if there is one. otherwise use ``resources.INLINE``. title (str, optional) : a title for the HTML document (default: None) If None, use the default state title value, if there is one. Otherwise, use "Bokeh Plot" state (State, optional) : A :class:`State` object. If None, then the current default implicit state is used. (default: None). Returns: str: the filename where the HTML file is saved. ''' if state is None: state = curstate() filename, resources, title = _get_save_args(state, filename, resources, title) _save_helper(obj, filename, resources, title, template) return abspath(filename)
python
def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs): ''' Save an HTML file with the data for the current document. Will fall back to the default output state (or an explicitly provided :class:`State` object) for ``filename``, ``resources``, or ``title`` if they are not provided. If the filename is not given and not provided via output state, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.html``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, use the default state configuration. resources (Resources, optional) : A Resources config to use (default: None) If None, use the default state configuration, if there is one. otherwise use ``resources.INLINE``. title (str, optional) : a title for the HTML document (default: None) If None, use the default state title value, if there is one. Otherwise, use "Bokeh Plot" state (State, optional) : A :class:`State` object. If None, then the current default implicit state is used. (default: None). Returns: str: the filename where the HTML file is saved. ''' if state is None: state = curstate() filename, resources, title = _get_save_args(state, filename, resources, title) _save_helper(obj, filename, resources, title, template) return abspath(filename)
[ "def", "save", "(", "obj", ",", "filename", "=", "None", ",", "resources", "=", "None", ",", "title", "=", "None", ",", "template", "=", "None", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "state", "is", "None", ":", "state", "=", "curstate", "(", ")", "filename", ",", "resources", ",", "title", "=", "_get_save_args", "(", "state", ",", "filename", ",", "resources", ",", "title", ")", "_save_helper", "(", "obj", ",", "filename", ",", "resources", ",", "title", ",", "template", ")", "return", "abspath", "(", "filename", ")" ]
Save an HTML file with the data for the current document. Will fall back to the default output state (or an explicitly provided :class:`State` object) for ``filename``, ``resources``, or ``title`` if they are not provided. If the filename is not given and not provided via output state, it is derived from the script name (e.g. ``/foo/myplot.py`` will create ``/foo/myplot.html``) Args: obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display filename (str, optional) : filename to save document under (default: None) If None, use the default state configuration. resources (Resources, optional) : A Resources config to use (default: None) If None, use the default state configuration, if there is one. otherwise use ``resources.INLINE``. title (str, optional) : a title for the HTML document (default: None) If None, use the default state title value, if there is one. Otherwise, use "Bokeh Plot" state (State, optional) : A :class:`State` object. If None, then the current default implicit state is used. (default: None). Returns: str: the filename where the HTML file is saved.
[ "Save", "an", "HTML", "file", "with", "the", "data", "for", "the", "current", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/saving.py#L50-L87
train
bokeh/bokeh
bokeh/sphinxext/bokeh_sitemap.py
html_page_context
def html_page_context(app, pagename, templatename, context, doctree): ''' Collect page names for the sitemap as HTML pages are built. ''' site = context['SITEMAP_BASE_URL'] version = context['version'] app.sitemap_links.add(site + version + '/' + pagename + ".html")
python
def html_page_context(app, pagename, templatename, context, doctree): ''' Collect page names for the sitemap as HTML pages are built. ''' site = context['SITEMAP_BASE_URL'] version = context['version'] app.sitemap_links.add(site + version + '/' + pagename + ".html")
[ "def", "html_page_context", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "site", "=", "context", "[", "'SITEMAP_BASE_URL'", "]", "version", "=", "context", "[", "'version'", "]", "app", ".", "sitemap_links", ".", "add", "(", "site", "+", "version", "+", "'/'", "+", "pagename", "+", "\".html\"", ")" ]
Collect page names for the sitemap as HTML pages are built.
[ "Collect", "page", "names", "for", "the", "sitemap", "as", "HTML", "pages", "are", "built", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_sitemap.py#L58-L64
train
bokeh/bokeh
bokeh/sphinxext/bokeh_sitemap.py
build_finished
def build_finished(app, exception): ''' Generate a ``sitemap.txt`` from the collected HTML page links. ''' filename = join(app.outdir, "sitemap.txt") links_iter = status_iterator(sorted(app.sitemap_links), 'adding links to sitemap... ', 'brown', len(app.sitemap_links), app.verbosity) try: with open(filename, 'w') as f: for link in links_iter: f.write("%s\n" % link) except OSError as e: raise SphinxError('cannot write sitemap.txt, reason: %s' % e)
python
def build_finished(app, exception): ''' Generate a ``sitemap.txt`` from the collected HTML page links. ''' filename = join(app.outdir, "sitemap.txt") links_iter = status_iterator(sorted(app.sitemap_links), 'adding links to sitemap... ', 'brown', len(app.sitemap_links), app.verbosity) try: with open(filename, 'w') as f: for link in links_iter: f.write("%s\n" % link) except OSError as e: raise SphinxError('cannot write sitemap.txt, reason: %s' % e)
[ "def", "build_finished", "(", "app", ",", "exception", ")", ":", "filename", "=", "join", "(", "app", ".", "outdir", ",", "\"sitemap.txt\"", ")", "links_iter", "=", "status_iterator", "(", "sorted", "(", "app", ".", "sitemap_links", ")", ",", "'adding links to sitemap... '", ",", "'brown'", ",", "len", "(", "app", ".", "sitemap_links", ")", ",", "app", ".", "verbosity", ")", "try", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "for", "link", "in", "links_iter", ":", "f", ".", "write", "(", "\"%s\\n\"", "%", "link", ")", "except", "OSError", "as", "e", ":", "raise", "SphinxError", "(", "'cannot write sitemap.txt, reason: %s'", "%", "e", ")" ]
Generate a ``sitemap.txt`` from the collected HTML page links.
[ "Generate", "a", "sitemap", ".", "txt", "from", "the", "collected", "HTML", "page", "links", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_sitemap.py#L66-L83
train
bokeh/bokeh
bokeh/sphinxext/bokeh_sitemap.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.connect('html-page-context', html_page_context) app.connect('build-finished', build_finished) app.sitemap_links = set()
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.connect('html-page-context', html_page_context) app.connect('build-finished', build_finished) app.sitemap_links = set()
[ "def", "setup", "(", "app", ")", ":", "app", ".", "connect", "(", "'html-page-context'", ",", "html_page_context", ")", "app", ".", "connect", "(", "'build-finished'", ",", "build_finished", ")", "app", ".", "sitemap_links", "=", "set", "(", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_sitemap.py#L85-L89
train
bokeh/bokeh
bokeh/server/tornado.py
BokehTornado.initialize
def initialize(self, io_loop): ''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop. ''' self._loop = io_loop for app_context in self._applications.values(): app_context._loop = self._loop self._clients = set() self._stats_job = PeriodicCallback(self._log_stats, self._stats_log_frequency_milliseconds) if self._mem_log_frequency_milliseconds > 0: self._mem_job = PeriodicCallback(self._log_mem, self._mem_log_frequency_milliseconds) else: self._mem_job = None self._cleanup_job = PeriodicCallback(self._cleanup_sessions, self._check_unused_sessions_milliseconds) if self._keep_alive_milliseconds > 0: self._ping_job = PeriodicCallback(self._keep_alive, self._keep_alive_milliseconds) else: self._ping_job = None
python
def initialize(self, io_loop): ''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop. ''' self._loop = io_loop for app_context in self._applications.values(): app_context._loop = self._loop self._clients = set() self._stats_job = PeriodicCallback(self._log_stats, self._stats_log_frequency_milliseconds) if self._mem_log_frequency_milliseconds > 0: self._mem_job = PeriodicCallback(self._log_mem, self._mem_log_frequency_milliseconds) else: self._mem_job = None self._cleanup_job = PeriodicCallback(self._cleanup_sessions, self._check_unused_sessions_milliseconds) if self._keep_alive_milliseconds > 0: self._ping_job = PeriodicCallback(self._keep_alive, self._keep_alive_milliseconds) else: self._ping_job = None
[ "def", "initialize", "(", "self", ",", "io_loop", ")", ":", "self", ".", "_loop", "=", "io_loop", "for", "app_context", "in", "self", ".", "_applications", ".", "values", "(", ")", ":", "app_context", ".", "_loop", "=", "self", ".", "_loop", "self", ".", "_clients", "=", "set", "(", ")", "self", ".", "_stats_job", "=", "PeriodicCallback", "(", "self", ".", "_log_stats", ",", "self", ".", "_stats_log_frequency_milliseconds", ")", "if", "self", ".", "_mem_log_frequency_milliseconds", ">", "0", ":", "self", ".", "_mem_job", "=", "PeriodicCallback", "(", "self", ".", "_log_mem", ",", "self", ".", "_mem_log_frequency_milliseconds", ")", "else", ":", "self", ".", "_mem_job", "=", "None", "self", ".", "_cleanup_job", "=", "PeriodicCallback", "(", "self", ".", "_cleanup_sessions", ",", "self", ".", "_check_unused_sessions_milliseconds", ")", "if", "self", ".", "_keep_alive_milliseconds", ">", "0", ":", "self", ".", "_ping_job", "=", "PeriodicCallback", "(", "self", ".", "_keep_alive", ",", "self", ".", "_keep_alive_milliseconds", ")", "else", ":", "self", ".", "_ping_job", "=", "None" ]
Start a Bokeh Server Tornado Application on a given Tornado IOLoop.
[ "Start", "a", "Bokeh", "Server", "Tornado", "Application", "on", "a", "given", "Tornado", "IOLoop", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L319-L346
train
bokeh/bokeh
bokeh/server/tornado.py
BokehTornado.resources
def resources(self, absolute_url=None): ''' Provide a :class:`~bokeh.resources.Resources` that specifies where Bokeh application sessions should load BokehJS resources from. Args: absolute_url (bool): An absolute URL prefix to use for locating resources. If None, relative URLs are used (default: None) ''' if absolute_url: return Resources(mode="server", root_url=absolute_url + self._prefix, path_versioner=StaticHandler.append_version) return Resources(mode="server", root_url=self._prefix, path_versioner=StaticHandler.append_version)
python
def resources(self, absolute_url=None): ''' Provide a :class:`~bokeh.resources.Resources` that specifies where Bokeh application sessions should load BokehJS resources from. Args: absolute_url (bool): An absolute URL prefix to use for locating resources. If None, relative URLs are used (default: None) ''' if absolute_url: return Resources(mode="server", root_url=absolute_url + self._prefix, path_versioner=StaticHandler.append_version) return Resources(mode="server", root_url=self._prefix, path_versioner=StaticHandler.append_version)
[ "def", "resources", "(", "self", ",", "absolute_url", "=", "None", ")", ":", "if", "absolute_url", ":", "return", "Resources", "(", "mode", "=", "\"server\"", ",", "root_url", "=", "absolute_url", "+", "self", ".", "_prefix", ",", "path_versioner", "=", "StaticHandler", ".", "append_version", ")", "return", "Resources", "(", "mode", "=", "\"server\"", ",", "root_url", "=", "self", ".", "_prefix", ",", "path_versioner", "=", "StaticHandler", ".", "append_version", ")" ]
Provide a :class:`~bokeh.resources.Resources` that specifies where Bokeh application sessions should load BokehJS resources from. Args: absolute_url (bool): An absolute URL prefix to use for locating resources. If None, relative URLs are used (default: None)
[ "Provide", "a", ":", "class", ":", "~bokeh", ".", "resources", ".", "Resources", "that", "specifies", "where", "Bokeh", "application", "sessions", "should", "load", "BokehJS", "resources", "from", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L411-L423
train