id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
25,500
pyGrowler/Growler
growler/http/response.py
HTTPResponse.send_headers
def send_headers(self): """ Sends the headers to the client """ self.events.sync_emit('headers') self._set_default_headers() header_str = self.status_line + self.EOL + str(self.headers) self.stream.write(header_str.encode()) self.events.sync_emit('after_headers')
python
def send_headers(self): self.events.sync_emit('headers') self._set_default_headers() header_str = self.status_line + self.EOL + str(self.headers) self.stream.write(header_str.encode()) self.events.sync_emit('after_headers')
[ "def", "send_headers", "(", "self", ")", ":", "self", ".", "events", ".", "sync_emit", "(", "'headers'", ")", "self", ".", "_set_default_headers", "(", ")", "header_str", "=", "self", ".", "status_line", "+", "self", ".", "EOL", "+", "str", "(", "self", ...
Sends the headers to the client
[ "Sends", "the", "headers", "to", "the", "client" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L76-L84
25,501
pyGrowler/Growler
growler/http/response.py
HTTPResponse.end
def end(self): """ Ends the response. Useful for quickly ending connection with no data sent """ self.send_headers() self.write() self.write_eof() self.has_ended = True
python
def end(self): self.send_headers() self.write() self.write_eof() self.has_ended = True
[ "def", "end", "(", "self", ")", ":", "self", ".", "send_headers", "(", ")", "self", ".", "write", "(", ")", "self", ".", "write_eof", "(", ")", "self", ".", "has_ended", "=", "True" ]
Ends the response. Useful for quickly ending connection with no data sent
[ "Ends", "the", "response", ".", "Useful", "for", "quickly", "ending", "connection", "with", "no", "data", "sent" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L110-L118
25,502
pyGrowler/Growler
growler/http/response.py
HTTPResponse.redirect
def redirect(self, url, status=None): """ Redirect to the specified url, optional status code defaults to 302. """ self.status_code = 302 if status is None else status self.headers = Headers([('location', url)]) self.message = '' self.end()
python
def redirect(self, url, status=None): self.status_code = 302 if status is None else status self.headers = Headers([('location', url)]) self.message = '' self.end()
[ "def", "redirect", "(", "self", ",", "url", ",", "status", "=", "None", ")", ":", "self", ".", "status_code", "=", "302", "if", "status", "is", "None", "else", "status", "self", ".", "headers", "=", "Headers", "(", "[", "(", "'location'", ",", "url",...
Redirect to the specified url, optional status code defaults to 302.
[ "Redirect", "to", "the", "specified", "url", "optional", "status", "code", "defaults", "to", "302", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L120-L127
25,503
pyGrowler/Growler
growler/http/response.py
HTTPResponse.set
def set(self, header, value=None): """Set header to the value""" if value is None: for k, v in header.items(): self.headers[k] = v else: self.headers[header] = value
python
def set(self, header, value=None): if value is None: for k, v in header.items(): self.headers[k] = v else: self.headers[header] = value
[ "def", "set", "(", "self", ",", "header", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "for", "k", ",", "v", "in", "header", ".", "items", "(", ")", ":", "self", ".", "headers", "[", "k", "]", "=", "v", "else", ":", ...
Set header to the value
[ "Set", "header", "to", "the", "value" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L129-L135
25,504
pyGrowler/Growler
growler/http/response.py
HTTPResponse.links
def links(self, links): """Sets the Link """ s = ['<{}>; rel="{}"'.format(link, rel) for link, rel in links.items()] self.headers['Link'] = ','.join(s)
python
def links(self, links): s = ['<{}>; rel="{}"'.format(link, rel) for link, rel in links.items()] self.headers['Link'] = ','.join(s)
[ "def", "links", "(", "self", ",", "links", ")", ":", "s", "=", "[", "'<{}>; rel=\"{}\"'", ".", "format", "(", "link", ",", "rel", ")", "for", "link", ",", "rel", "in", "links", ".", "items", "(", ")", "]", "self", ".", "headers", "[", "'Link'", "...
Sets the Link
[ "Sets", "the", "Link" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L161-L165
25,505
pyGrowler/Growler
growler/http/response.py
HTTPResponse.send_file
def send_file(self, filename, status=200): """ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) """ if isinstance(filename, Path) and sys.version_info >= (3, 5): self.message = filename.read_bytes() else: with io.FileIO(str(filename)) as f: self.message = f.read() self.status_code = status self.send_headers() self.write() self.write_eof()
python
def send_file(self, filename, status=200): if isinstance(filename, Path) and sys.version_info >= (3, 5): self.message = filename.read_bytes() else: with io.FileIO(str(filename)) as f: self.message = f.read() self.status_code = status self.send_headers() self.write() self.write_eof()
[ "def", "send_file", "(", "self", ",", "filename", ",", "status", "=", "200", ")", ":", "if", "isinstance", "(", "filename", ",", "Path", ")", "and", "sys", ".", "version_info", ">=", "(", "3", ",", "5", ")", ":", "self", ".", "message", "=", "filen...
Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK)
[ "Reads", "in", "the", "file", "filename", "and", "sends", "bytes", "to", "client" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L228-L247
25,506
pyGrowler/Growler
growler/http/response.py
Headers.update
def update(self, *args, **kwargs): """ Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header directly Returns: None """ for next_dict in chain(args, (kwargs, )): for k, v in next_dict.items(): self[k] = v
python
def update(self, *args, **kwargs): for next_dict in chain(args, (kwargs, )): for k, v in next_dict.items(): self[k] = v
[ "def", "update", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "next_dict", "in", "chain", "(", "args", ",", "(", "kwargs", ",", ")", ")", ":", "for", "k", ",", "v", "in", "next_dict", ".", "items", "(", ")", ":", "...
Equivalent to the python dict update method. Update the dictionary with the key/value pairs from other, overwriting existing keys. Args: other (dict): The source of key value pairs to add to headers Keyword Args: All keyword arguments are stored in header directly Returns: None
[ "Equivalent", "to", "the", "python", "dict", "update", "method", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L328-L345
25,507
pyGrowler/Growler
growler/http/response.py
Headers.add_header
def add_header(self, key, value, **params): """ Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, automatically formatting them in a standard way """ key = self.escape(key) ci_key = key.casefold() def quoted_params(items): for p in items: param_name = self.escape(p[0]) param_val = self.de_quote(self.escape(p[1])) yield param_name, param_val sorted_items = sorted(params.items()) quoted_iter = ('%s="%s"' % p for p in quoted_params(sorted_items)) param_str = ' '.join(quoted_iter) if param_str: value = "%s; %s" % (value, param_str) self._header_data[ci_key] = (key, value)
python
def add_header(self, key, value, **params): key = self.escape(key) ci_key = key.casefold() def quoted_params(items): for p in items: param_name = self.escape(p[0]) param_val = self.de_quote(self.escape(p[1])) yield param_name, param_val sorted_items = sorted(params.items()) quoted_iter = ('%s="%s"' % p for p in quoted_params(sorted_items)) param_str = ' '.join(quoted_iter) if param_str: value = "%s; %s" % (value, param_str) self._header_data[ci_key] = (key, value)
[ "def", "add_header", "(", "self", ",", "key", ",", "value", ",", "*", "*", "params", ")", ":", "key", "=", "self", ".", "escape", "(", "key", ")", "ci_key", "=", "key", ".", "casefold", "(", ")", "def", "quoted_params", "(", "items", ")", ":", "f...
Add a header to the collection, including potential parameters. Args: key (str): The name of the header value (str): The value to store under that key params: Option parameters to be appended to the value, automatically formatting them in a standard way
[ "Add", "a", "header", "to", "the", "collection", "including", "potential", "parameters", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/response.py#L347-L375
25,508
pyGrowler/Growler
examples/sessions.py
index
def index(req, res): """ Return root page of website. """ number = req.session.get('counter', -1) req.session['counter'] = int(number) + 1 print(" -- Session '{id}' returned {counter} times".format(**req.session)) msg = "Hello!! You've been here [[%s]] times" % (req.session['counter']) res.send_text(msg) req.session.save()
python
def index(req, res): number = req.session.get('counter', -1) req.session['counter'] = int(number) + 1 print(" -- Session '{id}' returned {counter} times".format(**req.session)) msg = "Hello!! You've been here [[%s]] times" % (req.session['counter']) res.send_text(msg) req.session.save()
[ "def", "index", "(", "req", ",", "res", ")", ":", "number", "=", "req", ".", "session", ".", "get", "(", "'counter'", ",", "-", "1", ")", "req", ".", "session", "[", "'counter'", "]", "=", "int", "(", "number", ")", "+", "1", "print", "(", "\" ...
Return root page of website.
[ "Return", "root", "page", "of", "website", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/examples/sessions.py#L21-L30
25,509
pyGrowler/Growler
growler/http/request.py
HTTPRequest.body
async def body(self): """ A helper function which blocks until the body has been read completely. Returns the bytes of the body which the user should decode. If the request does not have a body part (i.e. it is a GET request) this function returns None. """ if not isinstance(self._body, bytes): self._body = await self._body return self._body
python
async def body(self): if not isinstance(self._body, bytes): self._body = await self._body return self._body
[ "async", "def", "body", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "_body", ",", "bytes", ")", ":", "self", ".", "_body", "=", "await", "self", ".", "_body", "return", "self", ".", "_body" ]
A helper function which blocks until the body has been read completely. Returns the bytes of the body which the user should decode. If the request does not have a body part (i.e. it is a GET request) this function returns None.
[ "A", "helper", "function", "which", "blocks", "until", "the", "body", "has", "been", "read", "completely", ".", "Returns", "the", "bytes", "of", "the", "body", "which", "the", "user", "should", "decode", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/request.py#L63-L74
25,510
pyGrowler/Growler
growler/utils/event_manager.py
event_emitter
def event_emitter(cls_=None, *, events=('*', )): """ A class-decorator which will add the specified events and the methods 'on' and 'emit' to the class. """ # create a dictionary from items in the 'events' parameter and with empty # lists as values event_dict = dict.fromkeys(events, []) # if '*' was in the events tuple - then pop it out of the event_dict # and store the fact that we may allow any event name to be added to the # event emitter. allow_any_eventname = event_dict.pop('*', False) == [] def _event_emitter(cls): def on(self, name, callback): """ Add a callback to the event named 'name'. Returns the object for chained 'on' calls. """ if not (callable(callback) or isawaitable(callback)): raise ValueError("Callback not callable: %r" % callback) try: event_dict[name].append(callback) except KeyError: if allow_any_eventname: event_dict[name] = [callback] else: msg = "Event Emitter has no event {!r}".format(name) raise KeyError(msg) return self async def emit(self, name): """ Coroutine which executes each of the callbacks added to the event identified by 'name' """ for cb in event_dict[name]: if isawaitable(cb): await cb else: cb() cls.on = on cls.emit = emit return cls if cls_ is None: return _event_emitter else: return _event_emitter(cls_)
python
def event_emitter(cls_=None, *, events=('*', )): # create a dictionary from items in the 'events' parameter and with empty # lists as values event_dict = dict.fromkeys(events, []) # if '*' was in the events tuple - then pop it out of the event_dict # and store the fact that we may allow any event name to be added to the # event emitter. allow_any_eventname = event_dict.pop('*', False) == [] def _event_emitter(cls): def on(self, name, callback): """ Add a callback to the event named 'name'. Returns the object for chained 'on' calls. """ if not (callable(callback) or isawaitable(callback)): raise ValueError("Callback not callable: %r" % callback) try: event_dict[name].append(callback) except KeyError: if allow_any_eventname: event_dict[name] = [callback] else: msg = "Event Emitter has no event {!r}".format(name) raise KeyError(msg) return self async def emit(self, name): """ Coroutine which executes each of the callbacks added to the event identified by 'name' """ for cb in event_dict[name]: if isawaitable(cb): await cb else: cb() cls.on = on cls.emit = emit return cls if cls_ is None: return _event_emitter else: return _event_emitter(cls_)
[ "def", "event_emitter", "(", "cls_", "=", "None", ",", "*", ",", "events", "=", "(", "'*'", ",", ")", ")", ":", "# create a dictionary from items in the 'events' parameter and with empty", "# lists as values", "event_dict", "=", "dict", ".", "fromkeys", "(", "events...
A class-decorator which will add the specified events and the methods 'on' and 'emit' to the class.
[ "A", "class", "-", "decorator", "which", "will", "add", "the", "specified", "events", "and", "the", "methods", "on", "and", "emit", "to", "the", "class", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/event_manager.py#L9-L64
25,511
pyGrowler/Growler
growler/utils/event_manager.py
Events.on
def on(self, name, _callback=None): """ Add a callback to the event named 'name'. Returns callback object for decorationable calls. """ # this is being used as a decorator if _callback is None: return lambda cb: self.on(name, cb) if not (callable(_callback) or isawaitable(_callback)): msg = "Callback not callable: {0!r}".format(_callback) raise ValueError(msg) self._event_list[name].append(_callback) return _callback
python
def on(self, name, _callback=None): # this is being used as a decorator if _callback is None: return lambda cb: self.on(name, cb) if not (callable(_callback) or isawaitable(_callback)): msg = "Callback not callable: {0!r}".format(_callback) raise ValueError(msg) self._event_list[name].append(_callback) return _callback
[ "def", "on", "(", "self", ",", "name", ",", "_callback", "=", "None", ")", ":", "# this is being used as a decorator", "if", "_callback", "is", "None", ":", "return", "lambda", "cb", ":", "self", ".", "on", "(", "name", ",", "cb", ")", "if", "not", "("...
Add a callback to the event named 'name'. Returns callback object for decorationable calls.
[ "Add", "a", "callback", "to", "the", "event", "named", "name", ".", "Returns", "callback", "object", "for", "decorationable", "calls", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/event_manager.py#L109-L124
25,512
pyGrowler/Growler
growler/utils/event_manager.py
Events.emit
async def emit(self, name): """ Add a callback to the event named 'name'. Returns this object for chained 'on' calls. """ for cb in self._event_list[name]: if isawaitable(cb): await cb else: cb()
python
async def emit(self, name): for cb in self._event_list[name]: if isawaitable(cb): await cb else: cb()
[ "async", "def", "emit", "(", "self", ",", "name", ")", ":", "for", "cb", "in", "self", ".", "_event_list", "[", "name", "]", ":", "if", "isawaitable", "(", "cb", ")", ":", "await", "cb", "else", ":", "cb", "(", ")" ]
Add a callback to the event named 'name'. Returns this object for chained 'on' calls.
[ "Add", "a", "callback", "to", "the", "event", "named", "name", ".", "Returns", "this", "object", "for", "chained", "on", "calls", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/utils/event_manager.py#L126-L135
25,513
pyGrowler/Growler
growler/core/router.py
routerify
def routerify(obj): """ Scan through attributes of object parameter looking for any which match a route signature. A router will be created and added to the object with parameter. Args: obj (object): The object (with attributes) from which to setup a router Returns: Router: The router created from attributes in the object. """ router = Router() for info in get_routing_attributes(obj): router.add_route(*info) obj.__growler_router = router return router
python
def routerify(obj): router = Router() for info in get_routing_attributes(obj): router.add_route(*info) obj.__growler_router = router return router
[ "def", "routerify", "(", "obj", ")", ":", "router", "=", "Router", "(", ")", "for", "info", "in", "get_routing_attributes", "(", "obj", ")", ":", "router", ".", "add_route", "(", "*", "info", ")", "obj", ".", "__growler_router", "=", "router", "return", ...
Scan through attributes of object parameter looking for any which match a route signature. A router will be created and added to the object with parameter. Args: obj (object): The object (with attributes) from which to setup a router Returns: Router: The router created from attributes in the object.
[ "Scan", "through", "attributes", "of", "object", "parameter", "looking", "for", "any", "which", "match", "a", "route", "signature", ".", "A", "router", "will", "be", "created", "and", "added", "to", "the", "object", "with", "parameter", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/router.py#L281-L298
25,514
pyGrowler/Growler
growler/core/router.py
Router._add_route
def _add_route(self, method, path, middleware=None): """The implementation of adding a route""" if middleware is not None: self.add(method, path, middleware) return self else: # return a lambda that will return the 'func' argument return lambda func: ( self.add(method, path, func), func )[1]
python
def _add_route(self, method, path, middleware=None): if middleware is not None: self.add(method, path, middleware) return self else: # return a lambda that will return the 'func' argument return lambda func: ( self.add(method, path, func), func )[1]
[ "def", "_add_route", "(", "self", ",", "method", ",", "path", ",", "middleware", "=", "None", ")", ":", "if", "middleware", "is", "not", "None", ":", "self", ".", "add", "(", "method", ",", "path", ",", "middleware", ")", "return", "self", "else", ":...
The implementation of adding a route
[ "The", "implementation", "of", "adding", "a", "route" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/router.py#L68-L78
25,515
pyGrowler/Growler
growler/core/router.py
Router.use
def use(self, middleware, path=None): """ Call the provided middleware upon requests matching the path. If path is not provided or None, all requests will match. Args: middleware (callable): Callable with the signature ``(res, req) -> None`` path (Optional[str or regex]): a specific path the request must match for the middleware to be called. Returns: This router """ self.log.info(" Using middleware {}", middleware) if path is None: path = MiddlewareChain.ROOT_PATTERN self.add(HTTPMethod.ALL, path, middleware) return self
python
def use(self, middleware, path=None): self.log.info(" Using middleware {}", middleware) if path is None: path = MiddlewareChain.ROOT_PATTERN self.add(HTTPMethod.ALL, path, middleware) return self
[ "def", "use", "(", "self", ",", "middleware", ",", "path", "=", "None", ")", ":", "self", ".", "log", ".", "info", "(", "\" Using middleware {}\"", ",", "middleware", ")", "if", "path", "is", "None", ":", "path", "=", "MiddlewareChain", ".", "ROOT_PATTER...
Call the provided middleware upon requests matching the path. If path is not provided or None, all requests will match. Args: middleware (callable): Callable with the signature ``(res, req) -> None`` path (Optional[str or regex]): a specific path the request must match for the middleware to be called. Returns: This router
[ "Call", "the", "provided", "middleware", "upon", "requests", "matching", "the", "path", ".", "If", "path", "is", "not", "provided", "or", "None", "all", "requests", "will", "match", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/router.py#L86-L103
25,516
pyGrowler/Growler
growler/core/router.py
Router.sinatra_path_to_regex
def sinatra_path_to_regex(cls, path): """ Converts a sinatra-style path to a regex with named parameters. """ # Return the path if already a (compiled) regex if type(path) is cls.regex_type: return path # Build a regular expression string which is split on the '/' character regex = [ "(?P<{}>\w+)".format(segment[1:]) if cls.sinatra_param_regex.match(segment) else segment for segment in path.split('/') ] return re.compile('/'.join(regex))
python
def sinatra_path_to_regex(cls, path): # Return the path if already a (compiled) regex if type(path) is cls.regex_type: return path # Build a regular expression string which is split on the '/' character regex = [ "(?P<{}>\w+)".format(segment[1:]) if cls.sinatra_param_regex.match(segment) else segment for segment in path.split('/') ] return re.compile('/'.join(regex))
[ "def", "sinatra_path_to_regex", "(", "cls", ",", "path", ")", ":", "# Return the path if already a (compiled) regex", "if", "type", "(", "path", ")", "is", "cls", ".", "regex_type", ":", "return", "path", "# Build a regular expression string which is split on the '/' charac...
Converts a sinatra-style path to a regex with named parameters.
[ "Converts", "a", "sinatra", "-", "style", "path", "to", "a", "regex", "with", "named", "parameters", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/router.py#L137-L153
25,517
pyGrowler/Growler
growler/http/parser.py
Parser._parse_and_store_headers
def _parse_and_store_headers(self): """ Coroutine used retrieve header data and parse each header until the body is found. """ header_storage = self._store_header() header_storage.send(None) for header_line in self._next_header_line(): if header_line is None: self._buffer += yield continue else: header_storage.send(header_line) self.headers = header_storage.send(None)
python
def _parse_and_store_headers(self): header_storage = self._store_header() header_storage.send(None) for header_line in self._next_header_line(): if header_line is None: self._buffer += yield continue else: header_storage.send(header_line) self.headers = header_storage.send(None)
[ "def", "_parse_and_store_headers", "(", "self", ")", ":", "header_storage", "=", "self", ".", "_store_header", "(", ")", "header_storage", ".", "send", "(", "None", ")", "for", "header_line", "in", "self", ".", "_next_header_line", "(", ")", ":", "if", "head...
Coroutine used retrieve header data and parse each header until the body is found.
[ "Coroutine", "used", "retrieve", "header", "data", "and", "parse", "each", "header", "until", "the", "body", "is", "found", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/parser.py#L140-L156
25,518
pyGrowler/Growler
growler/http/parser.py
Parser._store_header
def _store_header(self): """ Logic & state behind storing headers. This is a coroutine that should be sent header lines in the usual fashion. Sending it None will indicate there are no more lines, and the dictionary of headers will be returned. """ key, value = None, None headers = [] header_line = yield while header_line is not None: if not header_line.startswith((b' ', b'\t')): if key: headers.append((key, value)) key, value = self.split_header_key_value(header_line) key = key.upper() else: next_val = header_line.strip().decode() if isinstance(value, list): value.append(next_val) else: value = [value, next_val] header_line = yield if key is not None: headers.append((key, value)) yield dict(headers)
python
def _store_header(self): key, value = None, None headers = [] header_line = yield while header_line is not None: if not header_line.startswith((b' ', b'\t')): if key: headers.append((key, value)) key, value = self.split_header_key_value(header_line) key = key.upper() else: next_val = header_line.strip().decode() if isinstance(value, list): value.append(next_val) else: value = [value, next_val] header_line = yield if key is not None: headers.append((key, value)) yield dict(headers)
[ "def", "_store_header", "(", "self", ")", ":", "key", ",", "value", "=", "None", ",", "None", "headers", "=", "[", "]", "header_line", "=", "yield", "while", "header_line", "is", "not", "None", ":", "if", "not", "header_line", ".", "startswith", "(", "...
Logic & state behind storing headers. This is a coroutine that should be sent header lines in the usual fashion. Sending it None will indicate there are no more lines, and the dictionary of headers will be returned.
[ "Logic", "&", "state", "behind", "storing", "headers", ".", "This", "is", "a", "coroutine", "that", "should", "be", "sent", "header", "lines", "in", "the", "usual", "fashion", ".", "Sending", "it", "None", "will", "indicate", "there", "are", "no", "more", ...
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/parser.py#L158-L185
25,519
pyGrowler/Growler
growler/http/parser.py
Parser._store_request_line
def _store_request_line(self, req_line): """ Splits the request line given into three components. Ensures that the version and method are valid for this server, and uses the urllib.parse function to parse the request URI. Note: This method has the additional side effect of updating all request line related attributes of the parser. Returns: tuple: Tuple containing the parsed (method, parsed_url, version) Raises: HTTPErrorBadRequest: If request line is invalid HTTPErrorNotImplemented: If HTTP method is not recognized HTTPErrorVersionNotSupported: If HTTP version is not recognized. """ if not isinstance(req_line, str): try: req_line = self.raw_request_line = req_line.decode() except UnicodeDecodeError: raise HTTPErrorBadRequest try: self.method_str, self.original_url, self.version = req_line.split() except ValueError: raise HTTPErrorBadRequest() if self.version not in ('HTTP/1.1', 'HTTP/1.0'): raise HTTPErrorVersionNotSupported(self.version) # allow lowercase methodname? # self.method_str = self.method_str.upper() # save 'method' and get the correct function to finish processing try: self.method = HTTPMethod[self.method_str] except KeyError: # Method not found err = "Unknown HTTP Method '{}'".format(self.method_str) raise HTTPErrorNotImplemented(err) self._process_headers = { HTTPMethod.GET: self.process_get_headers, HTTPMethod.POST: self.process_post_headers }.get(self.method, lambda data: True) _, num_str = self.version.split('/', 1) self.HTTP_VERSION = tuple(num_str.split('.')) self.version_number = float(num_str) self.parsed_url = urlparse(self.original_url) self.path = unquote(self.parsed_url.path) self.query = parse_qs(self.parsed_url.query) return self.method, self.parsed_url, self.version
python
def _store_request_line(self, req_line): if not isinstance(req_line, str): try: req_line = self.raw_request_line = req_line.decode() except UnicodeDecodeError: raise HTTPErrorBadRequest try: self.method_str, self.original_url, self.version = req_line.split() except ValueError: raise HTTPErrorBadRequest() if self.version not in ('HTTP/1.1', 'HTTP/1.0'): raise HTTPErrorVersionNotSupported(self.version) # allow lowercase methodname? # self.method_str = self.method_str.upper() # save 'method' and get the correct function to finish processing try: self.method = HTTPMethod[self.method_str] except KeyError: # Method not found err = "Unknown HTTP Method '{}'".format(self.method_str) raise HTTPErrorNotImplemented(err) self._process_headers = { HTTPMethod.GET: self.process_get_headers, HTTPMethod.POST: self.process_post_headers }.get(self.method, lambda data: True) _, num_str = self.version.split('/', 1) self.HTTP_VERSION = tuple(num_str.split('.')) self.version_number = float(num_str) self.parsed_url = urlparse(self.original_url) self.path = unquote(self.parsed_url.path) self.query = parse_qs(self.parsed_url.query) return self.method, self.parsed_url, self.version
[ "def", "_store_request_line", "(", "self", ",", "req_line", ")", ":", "if", "not", "isinstance", "(", "req_line", ",", "str", ")", ":", "try", ":", "req_line", "=", "self", ".", "raw_request_line", "=", "req_line", ".", "decode", "(", ")", "except", "Uni...
Splits the request line given into three components. Ensures that the version and method are valid for this server, and uses the urllib.parse function to parse the request URI. Note: This method has the additional side effect of updating all request line related attributes of the parser. Returns: tuple: Tuple containing the parsed (method, parsed_url, version) Raises: HTTPErrorBadRequest: If request line is invalid HTTPErrorNotImplemented: If HTTP method is not recognized HTTPErrorVersionNotSupported: If HTTP version is not recognized.
[ "Splits", "the", "request", "line", "given", "into", "three", "components", ".", "Ensures", "that", "the", "version", "and", "method", "are", "valid", "for", "this", "server", "and", "uses", "the", "urllib", ".", "parse", "function", "to", "parse", "the", ...
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/parser.py#L219-L277
25,520
pyGrowler/Growler
growler/http/parser.py
Parser.determine_newline
def determine_newline(data): """ Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data (bytes): The data to be searched Returns: None: If no-newline is found One of '\n', '\r\n': whichever is found first """ line_end_pos = data.find(b'\n') if line_end_pos == -1: return None elif line_end_pos == 0: return b'\n' prev_char = data[line_end_pos - 1] return b'\r\n' if (prev_char is b'\r'[0]) else b'\n'
python
def determine_newline(data): line_end_pos = data.find(b'\n') if line_end_pos == -1: return None elif line_end_pos == 0: return b'\n' prev_char = data[line_end_pos - 1] return b'\r\n' if (prev_char is b'\r'[0]) else b'\n'
[ "def", "determine_newline", "(", "data", ")", ":", "line_end_pos", "=", "data", ".", "find", "(", "b'\\n'", ")", "if", "line_end_pos", "==", "-", "1", ":", "return", "None", "elif", "line_end_pos", "==", "0", ":", "return", "b'\\n'", "prev_char", "=", "d...
Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data (bytes): The data to be searched Returns: None: If no-newline is found One of '\n', '\r\n': whichever is found first
[ "Looks", "for", "a", "newline", "character", "in", "bytestring", "parameter", "data", ".", "Currently", "only", "looks", "for", "strings", "\\", "r", "\\", "n", "\\", "n", ".", "If", "\\", "n", "is", "found", "at", "the", "first", "position", "of", "th...
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/http/parser.py#L280-L303
25,521
pyGrowler/Growler
growler/core/middleware_chain.py
MiddlewareNode.path_split
def path_split(self, path): """ Splits a path into the part matching this middleware and the part remaining. If path does not exist, it returns a pair of None values. If the regex matches the entire pair, the second item in returned tuple is None. Args: path (str): The url to split Returns: Tuple matching_path (str or None): The beginning of the path which matches this middleware or None if it does not match remaining_path (str or None): The 'rest' of the path, following the matching part """ match = self.path.match(path) if match is None: return None, None # split string at position the_rest = path[match.end():] # ensure we split at a '/' character if the_rest: if match.group().endswith('/'): pass elif the_rest.startswith('/'): pass else: return None, None if self.IGNORE_TRAILING_SLASH and the_rest == '/': the_rest = '' return match, the_rest
python
def path_split(self, path): match = self.path.match(path) if match is None: return None, None # split string at position the_rest = path[match.end():] # ensure we split at a '/' character if the_rest: if match.group().endswith('/'): pass elif the_rest.startswith('/'): pass else: return None, None if self.IGNORE_TRAILING_SLASH and the_rest == '/': the_rest = '' return match, the_rest
[ "def", "path_split", "(", "self", ",", "path", ")", ":", "match", "=", "self", ".", "path", ".", "match", "(", "path", ")", "if", "match", "is", "None", ":", "return", "None", ",", "None", "# split string at position", "the_rest", "=", "path", "[", "ma...
Splits a path into the part matching this middleware and the part remaining. If path does not exist, it returns a pair of None values. If the regex matches the entire pair, the second item in returned tuple is None. Args: path (str): The url to split Returns: Tuple matching_path (str or None): The beginning of the path which matches this middleware or None if it does not match remaining_path (str or None): The 'rest' of the path, following the matching part
[ "Splits", "a", "path", "into", "the", "part", "matching", "this", "middleware", "and", "the", "part", "remaining", ".", "If", "path", "does", "not", "exist", "it", "returns", "a", "pair", "of", "None", "values", ".", "If", "the", "regex", "matches", "the...
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/middleware_chain.py#L66-L101
25,522
pyGrowler/Growler
growler/core/middleware_chain.py
MiddlewareChain.find_matching_middleware
def find_matching_middleware(self, method, path): """ Iterator handling the matching of middleware against a method+path pair. Yields the middleware, and the """ for mw in self.mw_list: if not mw.matches_method(method): continue # get the path matching this middleware and the 'rest' of the url # (i.e. the part that comes AFTER the match) to be potentially # matched later by a subchain path_match, rest_url = mw.path_split(path) if self.should_skip_middleware(mw, path_match, rest_url): continue yield mw, path_match, rest_url
python
def find_matching_middleware(self, method, path): for mw in self.mw_list: if not mw.matches_method(method): continue # get the path matching this middleware and the 'rest' of the url # (i.e. the part that comes AFTER the match) to be potentially # matched later by a subchain path_match, rest_url = mw.path_split(path) if self.should_skip_middleware(mw, path_match, rest_url): continue yield mw, path_match, rest_url
[ "def", "find_matching_middleware", "(", "self", ",", "method", ",", "path", ")", ":", "for", "mw", "in", "self", ".", "mw_list", ":", "if", "not", "mw", ".", "matches_method", "(", "method", ")", ":", "continue", "# get the path matching this middleware and the ...
Iterator handling the matching of middleware against a method+path pair. Yields the middleware, and the
[ "Iterator", "handling", "the", "matching", "of", "middleware", "against", "a", "method", "+", "path", "pair", ".", "Yields", "the", "middleware", "and", "the" ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/middleware_chain.py#L183-L199
25,523
pyGrowler/Growler
growler/core/middleware_chain.py
MiddlewareChain.add
def add(self, method_mask, path, func): """ Add a function to the middleware chain. This function is returned when iterating over the chain with matching method and path. Args: method_mask (growler.http.HTTPMethod): A bitwise mask intended to match specific request methods. path (str or regex): An object with which to compare request urls func (callable): The function to be yieled from the generator upon a request matching the method_mask and path """ is_err = len(signature(func).parameters) == 3 is_subchain = isinstance(func, MiddlewareChain) tup = MiddlewareNode(func=func, mask=method_mask, path=path, is_errorhandler=is_err, is_subchain=is_subchain,) self.mw_list.append(tup)
python
def add(self, method_mask, path, func): is_err = len(signature(func).parameters) == 3 is_subchain = isinstance(func, MiddlewareChain) tup = MiddlewareNode(func=func, mask=method_mask, path=path, is_errorhandler=is_err, is_subchain=is_subchain,) self.mw_list.append(tup)
[ "def", "add", "(", "self", ",", "method_mask", ",", "path", ",", "func", ")", ":", "is_err", "=", "len", "(", "signature", "(", "func", ")", ".", "parameters", ")", "==", "3", "is_subchain", "=", "isinstance", "(", "func", ",", "MiddlewareChain", ")", ...
Add a function to the middleware chain. This function is returned when iterating over the chain with matching method and path. Args: method_mask (growler.http.HTTPMethod): A bitwise mask intended to match specific request methods. path (str or regex): An object with which to compare request urls func (callable): The function to be yieled from the generator upon a request matching the method_mask and path
[ "Add", "a", "function", "to", "the", "middleware", "chain", ".", "This", "function", "is", "returned", "when", "iterating", "over", "the", "chain", "with", "matching", "method", "and", "path", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/middleware_chain.py#L232-L251
25,524
pyGrowler/Growler
growler/core/middleware_chain.py
MiddlewareChain.count_all
def count_all(self): """ Returns the total number of middleware in this chain and subchains. """ return sum(x.func.count_all() if x.is_subchain else 1 for x in self)
python
def count_all(self): return sum(x.func.count_all() if x.is_subchain else 1 for x in self)
[ "def", "count_all", "(", "self", ")", ":", "return", "sum", "(", "x", ".", "func", ".", "count_all", "(", ")", "if", "x", ".", "is_subchain", "else", "1", "for", "x", "in", "self", ")" ]
Returns the total number of middleware in this chain and subchains.
[ "Returns", "the", "total", "number", "of", "middleware", "in", "this", "chain", "and", "subchains", "." ]
90c923ff204f28b86a01d741224987a22f69540f
https://github.com/pyGrowler/Growler/blob/90c923ff204f28b86a01d741224987a22f69540f/growler/core/middleware_chain.py#L268-L272
25,525
coleifer/django-relationships
relationships/templatetags/relationship_tags.py
if_relationship
def if_relationship(parser, token): """ Determine if a certain type of relationship exists between two users. The ``status`` parameter must be a slug matching either the from_slug, to_slug or symmetrical_slug of a RelationshipStatus. Example:: {% if_relationship from_user to_user "friends" %} Here are pictures of me drinking alcohol {% else %} Sorry coworkers {% endif_relationship %} {% if_relationship from_user to_user "blocking" %} damn seo experts {% endif_relationship %} """ bits = list(token.split_contents()) if len(bits) != 4: raise TemplateSyntaxError("%r takes 3 arguments:\n%s" % (bits[0], if_relationship.__doc__)) end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = template.NodeList() return IfRelationshipNode(nodelist_true, nodelist_false, *bits[1:])
python
def if_relationship(parser, token): bits = list(token.split_contents()) if len(bits) != 4: raise TemplateSyntaxError("%r takes 3 arguments:\n%s" % (bits[0], if_relationship.__doc__)) end_tag = 'end' + bits[0] nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = template.NodeList() return IfRelationshipNode(nodelist_true, nodelist_false, *bits[1:])
[ "def", "if_relationship", "(", "parser", ",", "token", ")", ":", "bits", "=", "list", "(", "token", ".", "split_contents", "(", ")", ")", "if", "len", "(", "bits", ")", "!=", "4", ":", "raise", "TemplateSyntaxError", "(", "\"%r takes 3 arguments:\\n%s\"", ...
Determine if a certain type of relationship exists between two users. The ``status`` parameter must be a slug matching either the from_slug, to_slug or symmetrical_slug of a RelationshipStatus. Example:: {% if_relationship from_user to_user "friends" %} Here are pictures of me drinking alcohol {% else %} Sorry coworkers {% endif_relationship %} {% if_relationship from_user to_user "blocking" %} damn seo experts {% endif_relationship %}
[ "Determine", "if", "a", "certain", "type", "of", "relationship", "exists", "between", "two", "users", ".", "The", "status", "parameter", "must", "be", "a", "slug", "matching", "either", "the", "from_slug", "to_slug", "or", "symmetrical_slug", "of", "a", "Relat...
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/templatetags/relationship_tags.py#L45-L74
25,526
coleifer/django-relationships
relationships/templatetags/relationship_tags.py
add_relationship_url
def add_relationship_url(user, status): """ Generate a url for adding a relationship on a given user. ``user`` is a User object, and ``status`` is either a relationship_status object or a string denoting a RelationshipStatus Usage:: href="{{ user|add_relationship_url:"following" }}" """ if isinstance(status, RelationshipStatus): status = status.from_slug return reverse('relationship_add', args=[user.username, status])
python
def add_relationship_url(user, status): if isinstance(status, RelationshipStatus): status = status.from_slug return reverse('relationship_add', args=[user.username, status])
[ "def", "add_relationship_url", "(", "user", ",", "status", ")", ":", "if", "isinstance", "(", "status", ",", "RelationshipStatus", ")", ":", "status", "=", "status", ".", "from_slug", "return", "reverse", "(", "'relationship_add'", ",", "args", "=", "[", "us...
Generate a url for adding a relationship on a given user. ``user`` is a User object, and ``status`` is either a relationship_status object or a string denoting a RelationshipStatus Usage:: href="{{ user|add_relationship_url:"following" }}"
[ "Generate", "a", "url", "for", "adding", "a", "relationship", "on", "a", "given", "user", ".", "user", "is", "a", "User", "object", "and", "status", "is", "either", "a", "relationship_status", "object", "or", "a", "string", "denoting", "a", "RelationshipStat...
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/templatetags/relationship_tags.py#L78-L90
25,527
googlefonts/ufo2ft
Lib/ufo2ft/postProcessor.py
PostProcessor._rename_glyphs_from_ufo
def _rename_glyphs_from_ufo(self): """Rename glyphs using ufo.lib.public.postscriptNames in UFO.""" rename_map = self._build_production_names() otf = self.otf otf.setGlyphOrder([rename_map.get(n, n) for n in otf.getGlyphOrder()]) # we need to compile format 2 'post' table so that the 'extraNames' # attribute is updated with the list of the names outside the # standard Macintosh glyph order; otherwise, if one dumps the font # to TTX directly before compiling first, the post table will not # contain the extraNames. if 'post' in otf and otf['post'].formatType == 2.0: otf['post'].compile(self.otf) if 'CFF ' in otf: cff = otf['CFF '].cff.topDictIndex[0] char_strings = cff.CharStrings.charStrings cff.CharStrings.charStrings = { rename_map.get(n, n): v for n, v in char_strings.items()} cff.charset = [rename_map.get(n, n) for n in cff.charset]
python
def _rename_glyphs_from_ufo(self): rename_map = self._build_production_names() otf = self.otf otf.setGlyphOrder([rename_map.get(n, n) for n in otf.getGlyphOrder()]) # we need to compile format 2 'post' table so that the 'extraNames' # attribute is updated with the list of the names outside the # standard Macintosh glyph order; otherwise, if one dumps the font # to TTX directly before compiling first, the post table will not # contain the extraNames. if 'post' in otf and otf['post'].formatType == 2.0: otf['post'].compile(self.otf) if 'CFF ' in otf: cff = otf['CFF '].cff.topDictIndex[0] char_strings = cff.CharStrings.charStrings cff.CharStrings.charStrings = { rename_map.get(n, n): v for n, v in char_strings.items()} cff.charset = [rename_map.get(n, n) for n in cff.charset]
[ "def", "_rename_glyphs_from_ufo", "(", "self", ")", ":", "rename_map", "=", "self", ".", "_build_production_names", "(", ")", "otf", "=", "self", ".", "otf", "otf", ".", "setGlyphOrder", "(", "[", "rename_map", ".", "get", "(", "n", ",", "n", ")", "for",...
Rename glyphs using ufo.lib.public.postscriptNames in UFO.
[ "Rename", "glyphs", "using", "ufo", ".", "lib", ".", "public", ".", "postscriptNames", "in", "UFO", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/postProcessor.py#L73-L93
25,528
googlefonts/ufo2ft
Lib/ufo2ft/postProcessor.py
PostProcessor._unique_name
def _unique_name(name, seen): """Append incremental '.N' suffix if glyph is a duplicate.""" if name in seen: n = seen[name] while (name + ".%d" % n) in seen: n += 1 seen[name] = n + 1 name += ".%d" % n seen[name] = 1 return name
python
def _unique_name(name, seen): if name in seen: n = seen[name] while (name + ".%d" % n) in seen: n += 1 seen[name] = n + 1 name += ".%d" % n seen[name] = 1 return name
[ "def", "_unique_name", "(", "name", ",", "seen", ")", ":", "if", "name", "in", "seen", ":", "n", "=", "seen", "[", "name", "]", "while", "(", "name", "+", "\".%d\"", "%", "n", ")", "in", "seen", ":", "n", "+=", "1", "seen", "[", "name", "]", ...
Append incremental '.N' suffix if glyph is a duplicate.
[ "Append", "incremental", ".", "N", "suffix", "if", "glyph", "is", "a", "duplicate", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/postProcessor.py#L124-L133
25,529
googlefonts/ufo2ft
Lib/ufo2ft/postProcessor.py
PostProcessor._build_production_name
def _build_production_name(self, glyph): """Build a production name for a single glyph.""" # use PostScript names from UFO lib if available if self._postscriptNames: production_name = self._postscriptNames.get(glyph.name) return production_name if production_name else glyph.name # use name derived from unicode value unicode_val = glyph.unicode if glyph.unicode is not None: return '%s%04X' % ( 'u' if unicode_val > 0xffff else 'uni', unicode_val) # use production name + last (non-script) suffix if possible parts = glyph.name.rsplit('.', 1) if len(parts) == 2 and parts[0] in self.glyphSet: return '%s.%s' % ( self._build_production_name(self.glyphSet[parts[0]]), parts[1]) # use ligature name, making sure to look up components with suffixes parts = glyph.name.split('.', 1) if len(parts) == 2: liga_parts = ['%s.%s' % (n, parts[1]) for n in parts[0].split('_')] else: liga_parts = glyph.name.split('_') if len(liga_parts) > 1 and all(n in self.glyphSet for n in liga_parts): unicode_vals = [self.glyphSet[n].unicode for n in liga_parts] if all(v and v <= 0xffff for v in unicode_vals): return 'uni' + ''.join('%04X' % v for v in unicode_vals) return '_'.join( self._build_production_name(self.glyphSet[n]) for n in liga_parts) return glyph.name
python
def _build_production_name(self, glyph): # use PostScript names from UFO lib if available if self._postscriptNames: production_name = self._postscriptNames.get(glyph.name) return production_name if production_name else glyph.name # use name derived from unicode value unicode_val = glyph.unicode if glyph.unicode is not None: return '%s%04X' % ( 'u' if unicode_val > 0xffff else 'uni', unicode_val) # use production name + last (non-script) suffix if possible parts = glyph.name.rsplit('.', 1) if len(parts) == 2 and parts[0] in self.glyphSet: return '%s.%s' % ( self._build_production_name(self.glyphSet[parts[0]]), parts[1]) # use ligature name, making sure to look up components with suffixes parts = glyph.name.split('.', 1) if len(parts) == 2: liga_parts = ['%s.%s' % (n, parts[1]) for n in parts[0].split('_')] else: liga_parts = glyph.name.split('_') if len(liga_parts) > 1 and all(n in self.glyphSet for n in liga_parts): unicode_vals = [self.glyphSet[n].unicode for n in liga_parts] if all(v and v <= 0xffff for v in unicode_vals): return 'uni' + ''.join('%04X' % v for v in unicode_vals) return '_'.join( self._build_production_name(self.glyphSet[n]) for n in liga_parts) return glyph.name
[ "def", "_build_production_name", "(", "self", ",", "glyph", ")", ":", "# use PostScript names from UFO lib if available", "if", "self", ".", "_postscriptNames", ":", "production_name", "=", "self", ".", "_postscriptNames", ".", "get", "(", "glyph", ".", "name", ")",...
Build a production name for a single glyph.
[ "Build", "a", "production", "name", "for", "a", "single", "glyph", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/postProcessor.py#L135-L168
25,530
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/ast.py
makeFeaClassName
def makeFeaClassName(name, existingClassNames=None): """Make a glyph class name which is legal to use in feature text. Ensures the name only includes characters in "A-Za-z0-9._", and isn't already defined. """ name = re.sub(r"[^A-Za-z0-9._]", r"", name) if existingClassNames is None: return name i = 1 origName = name while name in existingClassNames: name = "%s_%d" % (origName, i) i += 1 return name
python
def makeFeaClassName(name, existingClassNames=None): name = re.sub(r"[^A-Za-z0-9._]", r"", name) if existingClassNames is None: return name i = 1 origName = name while name in existingClassNames: name = "%s_%d" % (origName, i) i += 1 return name
[ "def", "makeFeaClassName", "(", "name", ",", "existingClassNames", "=", "None", ")", ":", "name", "=", "re", ".", "sub", "(", "r\"[^A-Za-z0-9._]\"", ",", "r\"\"", ",", "name", ")", "if", "existingClassNames", "is", "None", ":", "return", "name", "i", "=", ...
Make a glyph class name which is legal to use in feature text. Ensures the name only includes characters in "A-Za-z0-9._", and isn't already defined.
[ "Make", "a", "glyph", "class", "name", "which", "is", "legal", "to", "use", "in", "feature", "text", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/ast.py#L128-L142
25,531
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/ast.py
addLookupReference
def addLookupReference( feature, lookup, script=None, languages=None, exclude_dflt=False ): """Shortcut for addLookupReferences, but for a single lookup. """ return addLookupReferences( feature, (lookup,), script=script, languages=languages, exclude_dflt=exclude_dflt, )
python
def addLookupReference( feature, lookup, script=None, languages=None, exclude_dflt=False ): return addLookupReferences( feature, (lookup,), script=script, languages=languages, exclude_dflt=exclude_dflt, )
[ "def", "addLookupReference", "(", "feature", ",", "lookup", ",", "script", "=", "None", ",", "languages", "=", "None", ",", "exclude_dflt", "=", "False", ")", ":", "return", "addLookupReferences", "(", "feature", ",", "(", "lookup", ",", ")", ",", "script"...
Shortcut for addLookupReferences, but for a single lookup.
[ "Shortcut", "for", "addLookupReferences", "but", "for", "a", "single", "lookup", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/ast.py#L184-L195
25,532
googlefonts/ufo2ft
Lib/ufo2ft/fontInfoData.py
openTypeHeadCreatedFallback
def openTypeHeadCreatedFallback(info): """ Fallback to the environment variable SOURCE_DATE_EPOCH if set, otherwise now. """ if "SOURCE_DATE_EPOCH" in os.environ: t = datetime.utcfromtimestamp(int(os.environ["SOURCE_DATE_EPOCH"])) return t.strftime(_date_format) else: return dateStringForNow()
python
def openTypeHeadCreatedFallback(info): if "SOURCE_DATE_EPOCH" in os.environ: t = datetime.utcfromtimestamp(int(os.environ["SOURCE_DATE_EPOCH"])) return t.strftime(_date_format) else: return dateStringForNow()
[ "def", "openTypeHeadCreatedFallback", "(", "info", ")", ":", "if", "\"SOURCE_DATE_EPOCH\"", "in", "os", ".", "environ", ":", "t", "=", "datetime", ".", "utcfromtimestamp", "(", "int", "(", "os", ".", "environ", "[", "\"SOURCE_DATE_EPOCH\"", "]", ")", ")", "r...
Fallback to the environment variable SOURCE_DATE_EPOCH if set, otherwise now.
[ "Fallback", "to", "the", "environment", "variable", "SOURCE_DATE_EPOCH", "if", "set", "otherwise", "now", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/fontInfoData.py#L79-L88
25,533
googlefonts/ufo2ft
Lib/ufo2ft/fontInfoData.py
preflightInfo
def preflightInfo(info): """ Returns a dict containing two items. The value for each item will be a list of info attribute names. ================== === missingRequired Required data that is missing. missingRecommended Recommended data that is missing. ================== === """ missingRequired = set() missingRecommended = set() for attr in requiredAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRequired.add(attr) for attr in recommendedAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRecommended.add(attr) return dict(missingRequired=missingRequired, missingRecommended=missingRecommended)
python
def preflightInfo(info): missingRequired = set() missingRecommended = set() for attr in requiredAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRequired.add(attr) for attr in recommendedAttributes: if not hasattr(info, attr) or getattr(info, attr) is None: missingRecommended.add(attr) return dict(missingRequired=missingRequired, missingRecommended=missingRecommended)
[ "def", "preflightInfo", "(", "info", ")", ":", "missingRequired", "=", "set", "(", ")", "missingRecommended", "=", "set", "(", ")", "for", "attr", "in", "requiredAttributes", ":", "if", "not", "hasattr", "(", "info", ",", "attr", ")", "or", "getattr", "(...
Returns a dict containing two items. The value for each item will be a list of info attribute names. ================== === missingRequired Required data that is missing. missingRecommended Recommended data that is missing. ================== ===
[ "Returns", "a", "dict", "containing", "two", "items", ".", "The", "value", "for", "each", "item", "will", "be", "a", "list", "of", "info", "attribute", "names", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/fontInfoData.py#L466-L484
25,534
coleifer/django-relationships
relationships/models.py
RelationshipManager.add
def add(self, user, status=None, symmetrical=False): """ Add a relationship from one user to another with the given status, which defaults to "following". Adding a relationship is by default asymmetrical (akin to following someone on twitter). Specify a symmetrical relationship (akin to being friends on facebook) by passing in :param:`symmetrical` = True .. note:: If :param:`symmetrical` is set, the function will return a tuple containing the two relationship objects created """ if not status: status = RelationshipStatus.objects.following() relationship, created = Relationship.objects.get_or_create( from_user=self.instance, to_user=user, status=status, site=Site.objects.get_current() ) if symmetrical: return (relationship, user.relationships.add(self.instance, status, False)) else: return relationship
python
def add(self, user, status=None, symmetrical=False): if not status: status = RelationshipStatus.objects.following() relationship, created = Relationship.objects.get_or_create( from_user=self.instance, to_user=user, status=status, site=Site.objects.get_current() ) if symmetrical: return (relationship, user.relationships.add(self.instance, status, False)) else: return relationship
[ "def", "add", "(", "self", ",", "user", ",", "status", "=", "None", ",", "symmetrical", "=", "False", ")", ":", "if", "not", "status", ":", "status", "=", "RelationshipStatus", ".", "objects", ".", "following", "(", ")", "relationship", ",", "created", ...
Add a relationship from one user to another with the given status, which defaults to "following". Adding a relationship is by default asymmetrical (akin to following someone on twitter). Specify a symmetrical relationship (akin to being friends on facebook) by passing in :param:`symmetrical` = True .. note:: If :param:`symmetrical` is set, the function will return a tuple containing the two relationship objects created
[ "Add", "a", "relationship", "from", "one", "user", "to", "another", "with", "the", "given", "status", "which", "defaults", "to", "following", "." ]
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/models.py#L83-L110
25,535
coleifer/django-relationships
relationships/models.py
RelationshipManager.remove
def remove(self, user, status=None, symmetrical=False): """ Remove a relationship from one user to another, with the same caveats and behavior as adding a relationship. """ if not status: status = RelationshipStatus.objects.following() res = Relationship.objects.filter( from_user=self.instance, to_user=user, status=status, site__pk=settings.SITE_ID ).delete() if symmetrical: return (res, user.relationships.remove(self.instance, status, False)) else: return res
python
def remove(self, user, status=None, symmetrical=False): if not status: status = RelationshipStatus.objects.following() res = Relationship.objects.filter( from_user=self.instance, to_user=user, status=status, site__pk=settings.SITE_ID ).delete() if symmetrical: return (res, user.relationships.remove(self.instance, status, False)) else: return res
[ "def", "remove", "(", "self", ",", "user", ",", "status", "=", "None", ",", "symmetrical", "=", "False", ")", ":", "if", "not", "status", ":", "status", "=", "RelationshipStatus", ".", "objects", ".", "following", "(", ")", "res", "=", "Relationship", ...
Remove a relationship from one user to another, with the same caveats and behavior as adding a relationship.
[ "Remove", "a", "relationship", "from", "one", "user", "to", "another", "with", "the", "same", "caveats", "and", "behavior", "as", "adding", "a", "relationship", "." ]
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/models.py#L112-L130
25,536
coleifer/django-relationships
relationships/models.py
RelationshipManager.get_relationships
def get_relationships(self, status, symmetrical=False): """ Returns a QuerySet of user objects with which the given user has established a relationship. """ query = self._get_from_query(status) if symmetrical: query.update(self._get_to_query(status)) return User.objects.filter(**query)
python
def get_relationships(self, status, symmetrical=False): query = self._get_from_query(status) if symmetrical: query.update(self._get_to_query(status)) return User.objects.filter(**query)
[ "def", "get_relationships", "(", "self", ",", "status", ",", "symmetrical", "=", "False", ")", ":", "query", "=", "self", ".", "_get_from_query", "(", "status", ")", "if", "symmetrical", ":", "query", ".", "update", "(", "self", ".", "_get_to_query", "(", ...
Returns a QuerySet of user objects with which the given user has established a relationship.
[ "Returns", "a", "QuerySet", "of", "user", "objects", "with", "which", "the", "given", "user", "has", "established", "a", "relationship", "." ]
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/models.py#L146-L156
25,537
coleifer/django-relationships
relationships/models.py
RelationshipManager.only_to
def only_to(self, status): """ Returns a QuerySet of user objects who have created a relationship to the given user, but which the given user has not reciprocated """ from_relationships = self.get_relationships(status) to_relationships = self.get_related_to(status) return to_relationships.exclude(pk__in=from_relationships.values_list('pk'))
python
def only_to(self, status): from_relationships = self.get_relationships(status) to_relationships = self.get_related_to(status) return to_relationships.exclude(pk__in=from_relationships.values_list('pk'))
[ "def", "only_to", "(", "self", ",", "status", ")", ":", "from_relationships", "=", "self", ".", "get_relationships", "(", "status", ")", "to_relationships", "=", "self", ".", "get_related_to", "(", "status", ")", "return", "to_relationships", ".", "exclude", "...
Returns a QuerySet of user objects who have created a relationship to the given user, but which the given user has not reciprocated
[ "Returns", "a", "QuerySet", "of", "user", "objects", "who", "have", "created", "a", "relationship", "to", "the", "given", "user", "but", "which", "the", "given", "user", "has", "not", "reciprocated" ]
f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805
https://github.com/coleifer/django-relationships/blob/f15d0a186d9cc5cc2ca3fb2b6ec4b498df951805/relationships/models.py#L165-L172
25,538
googlefonts/ufo2ft
Lib/ufo2ft/util.py
makeOfficialGlyphOrder
def makeOfficialGlyphOrder(font, glyphOrder=None): """ Make the final glyph order for 'font'. If glyphOrder is None, try getting the font.glyphOrder list. If not explicit glyphOrder is defined, sort glyphs alphabetically. If ".notdef" glyph is present in the font, force this to always be the first glyph (at index 0). """ if glyphOrder is None: glyphOrder = getattr(font, "glyphOrder", ()) names = set(font.keys()) order = [] if ".notdef" in names: names.remove(".notdef") order.append(".notdef") for name in glyphOrder: if name not in names: continue names.remove(name) order.append(name) order.extend(sorted(names)) return order
python
def makeOfficialGlyphOrder(font, glyphOrder=None): if glyphOrder is None: glyphOrder = getattr(font, "glyphOrder", ()) names = set(font.keys()) order = [] if ".notdef" in names: names.remove(".notdef") order.append(".notdef") for name in glyphOrder: if name not in names: continue names.remove(name) order.append(name) order.extend(sorted(names)) return order
[ "def", "makeOfficialGlyphOrder", "(", "font", ",", "glyphOrder", "=", "None", ")", ":", "if", "glyphOrder", "is", "None", ":", "glyphOrder", "=", "getattr", "(", "font", ",", "\"glyphOrder\"", ",", "(", ")", ")", "names", "=", "set", "(", "font", ".", ...
Make the final glyph order for 'font'. If glyphOrder is None, try getting the font.glyphOrder list. If not explicit glyphOrder is defined, sort glyphs alphabetically. If ".notdef" glyph is present in the font, force this to always be the first glyph (at index 0).
[ "Make", "the", "final", "glyph", "order", "for", "font", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/util.py#L27-L49
25,539
googlefonts/ufo2ft
Lib/ufo2ft/util.py
_GlyphSet.from_layer
def from_layer(cls, font, layerName=None, copy=False, skipExportGlyphs=None): """Return a mapping of glyph names to glyph objects from `font`.""" if layerName is not None: layer = font.layers[layerName] else: layer = font.layers.defaultLayer if copy: self = _copyLayer(layer, obj_type=cls) self.lib = deepcopy(layer.lib) else: self = cls((g.name, g) for g in layer) self.lib = layer.lib # If any glyphs in the skipExportGlyphs list are used as components, decompose # them in the containing glyphs... if skipExportGlyphs: for glyph in self.values(): if any(c.baseGlyph in skipExportGlyphs for c in glyph.components): deepCopyContours(self, glyph, glyph, Transform(), skipExportGlyphs) if hasattr(glyph, "removeComponent"): # defcon for c in [ component for component in glyph.components if component.baseGlyph in skipExportGlyphs ]: glyph.removeComponent(c) else: # ufoLib2 glyph.components[:] = [ c for c in glyph.components if c.baseGlyph not in skipExportGlyphs ] # ... and then remove them from the glyph set, if even present. for glyph_name in skipExportGlyphs: if glyph_name in self: del self[glyph_name] self.name = layer.name if layerName is not None else None return self
python
def from_layer(cls, font, layerName=None, copy=False, skipExportGlyphs=None): if layerName is not None: layer = font.layers[layerName] else: layer = font.layers.defaultLayer if copy: self = _copyLayer(layer, obj_type=cls) self.lib = deepcopy(layer.lib) else: self = cls((g.name, g) for g in layer) self.lib = layer.lib # If any glyphs in the skipExportGlyphs list are used as components, decompose # them in the containing glyphs... if skipExportGlyphs: for glyph in self.values(): if any(c.baseGlyph in skipExportGlyphs for c in glyph.components): deepCopyContours(self, glyph, glyph, Transform(), skipExportGlyphs) if hasattr(glyph, "removeComponent"): # defcon for c in [ component for component in glyph.components if component.baseGlyph in skipExportGlyphs ]: glyph.removeComponent(c) else: # ufoLib2 glyph.components[:] = [ c for c in glyph.components if c.baseGlyph not in skipExportGlyphs ] # ... and then remove them from the glyph set, if even present. for glyph_name in skipExportGlyphs: if glyph_name in self: del self[glyph_name] self.name = layer.name if layerName is not None else None return self
[ "def", "from_layer", "(", "cls", ",", "font", ",", "layerName", "=", "None", ",", "copy", "=", "False", ",", "skipExportGlyphs", "=", "None", ")", ":", "if", "layerName", "is", "not", "None", ":", "layer", "=", "font", ".", "layers", "[", "layerName", ...
Return a mapping of glyph names to glyph objects from `font`.
[ "Return", "a", "mapping", "of", "glyph", "names", "to", "glyph", "objects", "from", "font", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/util.py#L54-L93
25,540
googlefonts/ufo2ft
Lib/ufo2ft/featureCompiler.py
parseLayoutFeatures
def parseLayoutFeatures(font): """ Parse OpenType layout features in the UFO and return a feaLib.ast.FeatureFile instance. """ featxt = tounicode(font.features.text or "", "utf-8") if not featxt: return ast.FeatureFile() buf = UnicodeIO(featxt) # the path is used by the lexer to resolve 'include' statements # and print filename in error messages. For the UFO spec, this # should be the path of the UFO, not the inner features.fea: # https://github.com/unified-font-object/ufo-spec/issues/55 ufoPath = font.path if ufoPath is not None: buf.name = ufoPath glyphNames = set(font.keys()) try: parser = Parser(buf, glyphNames) doc = parser.parse() except IncludedFeaNotFound as e: if ufoPath and os.path.exists(os.path.join(ufoPath, e.args[0])): logger.warning( "Please change the file name in the include(...); " "statement to be relative to the UFO itself, " "instead of relative to the 'features.fea' file " "contained in it." ) raise return doc
python
def parseLayoutFeatures(font): featxt = tounicode(font.features.text or "", "utf-8") if not featxt: return ast.FeatureFile() buf = UnicodeIO(featxt) # the path is used by the lexer to resolve 'include' statements # and print filename in error messages. For the UFO spec, this # should be the path of the UFO, not the inner features.fea: # https://github.com/unified-font-object/ufo-spec/issues/55 ufoPath = font.path if ufoPath is not None: buf.name = ufoPath glyphNames = set(font.keys()) try: parser = Parser(buf, glyphNames) doc = parser.parse() except IncludedFeaNotFound as e: if ufoPath and os.path.exists(os.path.join(ufoPath, e.args[0])): logger.warning( "Please change the file name in the include(...); " "statement to be relative to the UFO itself, " "instead of relative to the 'features.fea' file " "contained in it." ) raise return doc
[ "def", "parseLayoutFeatures", "(", "font", ")", ":", "featxt", "=", "tounicode", "(", "font", ".", "features", ".", "text", "or", "\"\"", ",", "\"utf-8\"", ")", "if", "not", "featxt", ":", "return", "ast", ".", "FeatureFile", "(", ")", "buf", "=", "Uni...
Parse OpenType layout features in the UFO and return a feaLib.ast.FeatureFile instance.
[ "Parse", "OpenType", "layout", "features", "in", "the", "UFO", "and", "return", "a", "feaLib", ".", "ast", ".", "FeatureFile", "instance", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureCompiler.py#L30-L58
25,541
googlefonts/ufo2ft
Lib/ufo2ft/featureCompiler.py
FeatureCompiler.setupFeatures
def setupFeatures(self): """ Make the features source. **This should not be called externally.** Subclasses may override this method to handle the file creation in a different way if desired. """ if self.featureWriters: featureFile = parseLayoutFeatures(self.ufo) for writer in self.featureWriters: writer.write(self.ufo, featureFile, compiler=self) # stringify AST to get correct line numbers in error messages self.features = featureFile.asFea() else: # no featureWriters, simply read existing features' text self.features = tounicode(self.ufo.features.text or "", "utf-8")
python
def setupFeatures(self): if self.featureWriters: featureFile = parseLayoutFeatures(self.ufo) for writer in self.featureWriters: writer.write(self.ufo, featureFile, compiler=self) # stringify AST to get correct line numbers in error messages self.features = featureFile.asFea() else: # no featureWriters, simply read existing features' text self.features = tounicode(self.ufo.features.text or "", "utf-8")
[ "def", "setupFeatures", "(", "self", ")", ":", "if", "self", ".", "featureWriters", ":", "featureFile", "=", "parseLayoutFeatures", "(", "self", ".", "ufo", ")", "for", "writer", "in", "self", ".", "featureWriters", ":", "writer", ".", "write", "(", "self"...
Make the features source. **This should not be called externally.** Subclasses may override this method to handle the file creation in a different way if desired.
[ "Make", "the", "features", "source", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureCompiler.py#L213-L231
25,542
googlefonts/ufo2ft
Lib/ufo2ft/featureCompiler.py
FeatureCompiler.buildTables
def buildTables(self): """ Compile OpenType feature tables from the source. Raises a FeaLibError if the feature compilation was unsuccessful. **This should not be called externally.** Subclasses may override this method to handle the table compilation in a different way if desired. """ if not self.features: return # the path is used by the lexer to follow 'include' statements; # if we generated some automatic features, includes have already been # resolved, and we work from a string which does't exist on disk path = self.ufo.path if not self.featureWriters else None try: addOpenTypeFeaturesFromString( self.ttFont, self.features, filename=path ) except FeatureLibError: if path is None: # if compilation fails, create temporary file for inspection data = tobytes(self.features, encoding="utf-8") with NamedTemporaryFile(delete=False) as tmp: tmp.write(data) logger.error( "Compilation failed! Inspect temporary file: %r", tmp.name ) raise
python
def buildTables(self): if not self.features: return # the path is used by the lexer to follow 'include' statements; # if we generated some automatic features, includes have already been # resolved, and we work from a string which does't exist on disk path = self.ufo.path if not self.featureWriters else None try: addOpenTypeFeaturesFromString( self.ttFont, self.features, filename=path ) except FeatureLibError: if path is None: # if compilation fails, create temporary file for inspection data = tobytes(self.features, encoding="utf-8") with NamedTemporaryFile(delete=False) as tmp: tmp.write(data) logger.error( "Compilation failed! Inspect temporary file: %r", tmp.name ) raise
[ "def", "buildTables", "(", "self", ")", ":", "if", "not", "self", ".", "features", ":", "return", "# the path is used by the lexer to follow 'include' statements;", "# if we generated some automatic features, includes have already been", "# resolved, and we work from a string which doe...
Compile OpenType feature tables from the source. Raises a FeaLibError if the feature compilation was unsuccessful. **This should not be called externally.** Subclasses may override this method to handle the table compilation in a different way if desired.
[ "Compile", "OpenType", "feature", "tables", "from", "the", "source", ".", "Raises", "a", "FeaLibError", "if", "the", "feature", "compilation", "was", "unsuccessful", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureCompiler.py#L233-L263
25,543
googlefonts/ufo2ft
Lib/ufo2ft/maxContextCalc.py
maxCtxFont
def maxCtxFont(font): """Calculate the usMaxContext value for an entire font.""" maxCtx = 0 for tag in ('GSUB', 'GPOS'): if tag not in font: continue table = font[tag].table if table.LookupList is None: continue for lookup in table.LookupList.Lookup: for st in lookup.SubTable: maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st) return maxCtx
python
def maxCtxFont(font): maxCtx = 0 for tag in ('GSUB', 'GPOS'): if tag not in font: continue table = font[tag].table if table.LookupList is None: continue for lookup in table.LookupList.Lookup: for st in lookup.SubTable: maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st) return maxCtx
[ "def", "maxCtxFont", "(", "font", ")", ":", "maxCtx", "=", "0", "for", "tag", "in", "(", "'GSUB'", ",", "'GPOS'", ")", ":", "if", "tag", "not", "in", "font", ":", "continue", "table", "=", "font", "[", "tag", "]", ".", "table", "if", "table", "."...
Calculate the usMaxContext value for an entire font.
[ "Calculate", "the", "usMaxContext", "value", "for", "an", "entire", "font", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/maxContextCalc.py#L6-L19
25,544
googlefonts/ufo2ft
Lib/ufo2ft/maxContextCalc.py
maxCtxContextualSubtable
def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=''): """Calculate usMaxContext based on a contextual feature subtable.""" if st.Format == 1: for ruleset in getattr(st, '%s%sRuleSet' % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, '%s%sRule' % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain) elif st.Format == 2: for ruleset in getattr(st, '%s%sClassSet' % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, '%s%sClassRule' % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain) elif st.Format == 3: maxCtx = maxCtxContextualRule(maxCtx, st, chain) return maxCtx
python
def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=''): if st.Format == 1: for ruleset in getattr(st, '%s%sRuleSet' % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, '%s%sRule' % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain) elif st.Format == 2: for ruleset in getattr(st, '%s%sClassSet' % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, '%s%sClassRule' % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain) elif st.Format == 3: maxCtx = maxCtxContextualRule(maxCtx, st, chain) return maxCtx
[ "def", "maxCtxContextualSubtable", "(", "maxCtx", ",", "st", ",", "ruleType", ",", "chain", "=", "''", ")", ":", "if", "st", ".", "Format", "==", "1", ":", "for", "ruleset", "in", "getattr", "(", "st", ",", "'%s%sRuleSet'", "%", "(", "chain", ",", "r...
Calculate usMaxContext based on a contextual feature subtable.
[ "Calculate", "usMaxContext", "based", "on", "a", "contextual", "feature", "subtable", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/maxContextCalc.py#L67-L91
25,545
googlefonts/ufo2ft
Lib/ufo2ft/maxContextCalc.py
maxCtxContextualRule
def maxCtxContextualRule(maxCtx, st, chain): """Calculate usMaxContext based on a contextual feature rule.""" if not chain: return max(maxCtx, st.GlyphCount) elif chain == 'Reverse': return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount) return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount)
python
def maxCtxContextualRule(maxCtx, st, chain): if not chain: return max(maxCtx, st.GlyphCount) elif chain == 'Reverse': return max(maxCtx, st.GlyphCount + st.LookAheadGlyphCount) return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount)
[ "def", "maxCtxContextualRule", "(", "maxCtx", ",", "st", ",", "chain", ")", ":", "if", "not", "chain", ":", "return", "max", "(", "maxCtx", ",", "st", ".", "GlyphCount", ")", "elif", "chain", "==", "'Reverse'", ":", "return", "max", "(", "maxCtx", ",",...
Calculate usMaxContext based on a contextual feature rule.
[ "Calculate", "usMaxContext", "based", "on", "a", "contextual", "feature", "rule", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/maxContextCalc.py#L94-L101
25,546
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileOTF
def compileOTF( ufo, preProcessorClass=OTFPreProcessor, outlineCompilerClass=OutlineOTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, optimizeCFF=CFFOptimization.SUBROUTINIZE, roundTolerance=None, removeOverlaps=False, overlapsBackend=None, inplace=False, layerName=None, skipExportGlyphs=None, _tables=None, ): """Create FontTools CFF font from a UFO. *removeOverlaps* performs a union operation on all the glyphs' contours. *optimizeCFF* (int) defines whether the CFF charstrings should be specialized and subroutinized. By default both optimization are enabled. A value of 0 disables both; 1 only enables the specialization; 2 (default) does both specialization and subroutinization. *roundTolerance* (float) controls the rounding of point coordinates. It is defined as the maximum absolute difference between the original float and the rounded integer value. By default, all floats are rounded to integer (tolerance 0.5); a value of 0 completely disables rounding; values in between only round floats which are close to their integral part within the tolerated range. *featureWriters* argument is a list of BaseFeatureWriter subclasses or pre-initialized instances. Features will be written by each feature writer in the given order. If featureWriters is None, the default feature writers [KernFeatureWriter, MarkFeatureWriter] are used. *useProductionNames* renames glyphs in TrueType 'post' or OpenType 'CFF ' tables based on the 'public.postscriptNames' mapping in the UFO lib, if present. Otherwise, uniXXXX names are generated from the glyphs' unicode values. The default value (None) will first check if the UFO lib has the 'com.github.googlei18n.ufo2ft.useProductionNames' key. If this is missing or True (default), the glyphs are renamed. Set to False to keep the original names. **inplace** (bool) specifies whether the filters should modify the input UFO's glyphs, a copy should be made first. *layerName* specifies which layer should be compiled. When compiling something other than the default layer, feature compilation is skipped. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the UFO's "public.skipExportGlyphs" lib key will be consulted. If it doesn't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs. """ logger.info("Pre-processing glyphs") if skipExportGlyphs is None: skipExportGlyphs = ufo.lib.get("public.skipExportGlyphs", []) preProcessor = preProcessorClass( ufo, inplace=inplace, removeOverlaps=removeOverlaps, overlapsBackend=overlapsBackend, layerName=layerName, skipExportGlyphs=skipExportGlyphs, ) glyphSet = preProcessor.process() logger.info("Building OpenType tables") optimizeCFF = CFFOptimization(optimizeCFF) outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder, roundTolerance=roundTolerance, optimizeCFF=optimizeCFF >= CFFOptimization.SPECIALIZE, tables=_tables, ) otf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature code. if layerName is None: compileFeatures( ufo, otf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(otf, ufo, glyphSet=glyphSet) otf = postProcessor.process( useProductionNames, optimizeCFF=optimizeCFF >= CFFOptimization.SUBROUTINIZE, ) return otf
python
def compileOTF( ufo, preProcessorClass=OTFPreProcessor, outlineCompilerClass=OutlineOTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, optimizeCFF=CFFOptimization.SUBROUTINIZE, roundTolerance=None, removeOverlaps=False, overlapsBackend=None, inplace=False, layerName=None, skipExportGlyphs=None, _tables=None, ): logger.info("Pre-processing glyphs") if skipExportGlyphs is None: skipExportGlyphs = ufo.lib.get("public.skipExportGlyphs", []) preProcessor = preProcessorClass( ufo, inplace=inplace, removeOverlaps=removeOverlaps, overlapsBackend=overlapsBackend, layerName=layerName, skipExportGlyphs=skipExportGlyphs, ) glyphSet = preProcessor.process() logger.info("Building OpenType tables") optimizeCFF = CFFOptimization(optimizeCFF) outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder, roundTolerance=roundTolerance, optimizeCFF=optimizeCFF >= CFFOptimization.SPECIALIZE, tables=_tables, ) otf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature code. if layerName is None: compileFeatures( ufo, otf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(otf, ufo, glyphSet=glyphSet) otf = postProcessor.process( useProductionNames, optimizeCFF=optimizeCFF >= CFFOptimization.SUBROUTINIZE, ) return otf
[ "def", "compileOTF", "(", "ufo", ",", "preProcessorClass", "=", "OTFPreProcessor", ",", "outlineCompilerClass", "=", "OutlineOTFCompiler", ",", "featureCompilerClass", "=", "None", ",", "featureWriters", "=", "None", ",", "glyphOrder", "=", "None", ",", "useProducti...
Create FontTools CFF font from a UFO. *removeOverlaps* performs a union operation on all the glyphs' contours. *optimizeCFF* (int) defines whether the CFF charstrings should be specialized and subroutinized. By default both optimization are enabled. A value of 0 disables both; 1 only enables the specialization; 2 (default) does both specialization and subroutinization. *roundTolerance* (float) controls the rounding of point coordinates. It is defined as the maximum absolute difference between the original float and the rounded integer value. By default, all floats are rounded to integer (tolerance 0.5); a value of 0 completely disables rounding; values in between only round floats which are close to their integral part within the tolerated range. *featureWriters* argument is a list of BaseFeatureWriter subclasses or pre-initialized instances. Features will be written by each feature writer in the given order. If featureWriters is None, the default feature writers [KernFeatureWriter, MarkFeatureWriter] are used. *useProductionNames* renames glyphs in TrueType 'post' or OpenType 'CFF ' tables based on the 'public.postscriptNames' mapping in the UFO lib, if present. Otherwise, uniXXXX names are generated from the glyphs' unicode values. The default value (None) will first check if the UFO lib has the 'com.github.googlei18n.ufo2ft.useProductionNames' key. If this is missing or True (default), the glyphs are renamed. Set to False to keep the original names. **inplace** (bool) specifies whether the filters should modify the input UFO's glyphs, a copy should be made first. *layerName* specifies which layer should be compiled. When compiling something other than the default layer, feature compilation is skipped. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the UFO's "public.skipExportGlyphs" lib key will be consulted. If it doesn't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs.
[ "Create", "FontTools", "CFF", "font", "from", "a", "UFO", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L38-L140
25,547
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileTTF
def compileTTF( ufo, preProcessorClass=TTFPreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, convertCubics=True, cubicConversionError=None, reverseDirection=True, rememberCurveType=True, removeOverlaps=False, overlapsBackend=None, inplace=False, layerName=None, skipExportGlyphs=None, ): """Create FontTools TrueType font from a UFO. *removeOverlaps* performs a union operation on all the glyphs' contours. *convertCubics* and *cubicConversionError* specify how the conversion from cubic to quadratic curves should be handled. *layerName* specifies which layer should be compiled. When compiling something other than the default layer, feature compilation is skipped. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the UFO's "public.skipExportGlyphs" lib key will be consulted. If it doesn't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs. """ logger.info("Pre-processing glyphs") if skipExportGlyphs is None: skipExportGlyphs = ufo.lib.get("public.skipExportGlyphs", []) preProcessor = preProcessorClass( ufo, inplace=inplace, removeOverlaps=removeOverlaps, overlapsBackend=overlapsBackend, convertCubics=convertCubics, conversionError=cubicConversionError, reverseDirection=reverseDirection, rememberCurveType=rememberCurveType, layerName=layerName, skipExportGlyphs=skipExportGlyphs, ) glyphSet = preProcessor.process() logger.info("Building OpenType tables") outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder ) otf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature code. if layerName is None: compileFeatures( ufo, otf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(otf, ufo, glyphSet=glyphSet) otf = postProcessor.process(useProductionNames) return otf
python
def compileTTF( ufo, preProcessorClass=TTFPreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, convertCubics=True, cubicConversionError=None, reverseDirection=True, rememberCurveType=True, removeOverlaps=False, overlapsBackend=None, inplace=False, layerName=None, skipExportGlyphs=None, ): logger.info("Pre-processing glyphs") if skipExportGlyphs is None: skipExportGlyphs = ufo.lib.get("public.skipExportGlyphs", []) preProcessor = preProcessorClass( ufo, inplace=inplace, removeOverlaps=removeOverlaps, overlapsBackend=overlapsBackend, convertCubics=convertCubics, conversionError=cubicConversionError, reverseDirection=reverseDirection, rememberCurveType=rememberCurveType, layerName=layerName, skipExportGlyphs=skipExportGlyphs, ) glyphSet = preProcessor.process() logger.info("Building OpenType tables") outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder ) otf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature code. if layerName is None: compileFeatures( ufo, otf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(otf, ufo, glyphSet=glyphSet) otf = postProcessor.process(useProductionNames) return otf
[ "def", "compileTTF", "(", "ufo", ",", "preProcessorClass", "=", "TTFPreProcessor", ",", "outlineCompilerClass", "=", "OutlineTTFCompiler", ",", "featureCompilerClass", "=", "None", ",", "featureWriters", "=", "None", ",", "glyphOrder", "=", "None", ",", "useProducti...
Create FontTools TrueType font from a UFO. *removeOverlaps* performs a union operation on all the glyphs' contours. *convertCubics* and *cubicConversionError* specify how the conversion from cubic to quadratic curves should be handled. *layerName* specifies which layer should be compiled. When compiling something other than the default layer, feature compilation is skipped. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the UFO's "public.skipExportGlyphs" lib key will be consulted. If it doesn't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs.
[ "Create", "FontTools", "TrueType", "font", "from", "a", "UFO", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L143-L216
25,548
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileInterpolatableTTFs
def compileInterpolatableTTFs( ufos, preProcessorClass=TTFInterpolatablePreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, cubicConversionError=None, reverseDirection=True, inplace=False, layerNames=None, skipExportGlyphs=None, ): """Create FontTools TrueType fonts from a list of UFOs with interpolatable outlines. Cubic curves are converted compatibly to quadratic curves using the Cu2Qu conversion algorithm. Return an iterator object that yields a TTFont instance for each UFO. *layerNames* refers to the layer names to use glyphs from in the order of the UFOs in *ufos*. By default, this is a list of `[None]` times the number of UFOs, i.e. using the default layer from all the UFOs. When the layerName is not None for a given UFO, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "glyf", "loca", "maxp", "post" and "vmtx"), and no OpenType layout tables. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the union of all UFO's "public.skipExportGlyphs" lib keys will be used. If they don't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs. """ from ufo2ft.util import _LazyFontName if layerNames is None: layerNames = [None] * len(ufos) assert len(ufos) == len(layerNames) if skipExportGlyphs is None: skipExportGlyphs = set() for ufo in ufos: skipExportGlyphs.update(ufo.lib.get("public.skipExportGlyphs", [])) logger.info("Pre-processing glyphs") preProcessor = preProcessorClass( ufos, inplace=inplace, conversionError=cubicConversionError, reverseDirection=reverseDirection, layerNames=layerNames, skipExportGlyphs=skipExportGlyphs, ) glyphSets = preProcessor.process() for ufo, glyphSet, layerName in zip(ufos, glyphSets, layerNames): fontName = _LazyFontName(ufo) if layerName is not None: logger.info("Building OpenType tables for %s-%s", fontName, layerName) else: logger.info("Building OpenType tables for %s", fontName) outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder, tables=SPARSE_TTF_MASTER_TABLES if layerName else None, ) ttf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature # code. if layerName is None: compileFeatures( ufo, ttf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(ttf, ufo, glyphSet=glyphSet) ttf = postProcessor.process(useProductionNames) if layerName is not None: # for sparse masters (i.e. containing only a subset of the glyphs), we # need to include the post table in order to store glyph names, so that # fontTools.varLib can interpolate glyphs with same name across masters. # However we want to prevent the underlinePosition/underlineThickness # fields in such sparse masters to be included when computing the deltas # for the MVAR table. Thus, we set them to this unlikely, limit value # (-36768) which is a signal varLib should ignore them when building MVAR. ttf["post"].underlinePosition = -0x8000 ttf["post"].underlineThickness = -0x8000 yield ttf
python
def compileInterpolatableTTFs( ufos, preProcessorClass=TTFInterpolatablePreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, cubicConversionError=None, reverseDirection=True, inplace=False, layerNames=None, skipExportGlyphs=None, ): from ufo2ft.util import _LazyFontName if layerNames is None: layerNames = [None] * len(ufos) assert len(ufos) == len(layerNames) if skipExportGlyphs is None: skipExportGlyphs = set() for ufo in ufos: skipExportGlyphs.update(ufo.lib.get("public.skipExportGlyphs", [])) logger.info("Pre-processing glyphs") preProcessor = preProcessorClass( ufos, inplace=inplace, conversionError=cubicConversionError, reverseDirection=reverseDirection, layerNames=layerNames, skipExportGlyphs=skipExportGlyphs, ) glyphSets = preProcessor.process() for ufo, glyphSet, layerName in zip(ufos, glyphSets, layerNames): fontName = _LazyFontName(ufo) if layerName is not None: logger.info("Building OpenType tables for %s-%s", fontName, layerName) else: logger.info("Building OpenType tables for %s", fontName) outlineCompiler = outlineCompilerClass( ufo, glyphSet=glyphSet, glyphOrder=glyphOrder, tables=SPARSE_TTF_MASTER_TABLES if layerName else None, ) ttf = outlineCompiler.compile() # Only the default layer is likely to have all glyphs used in feature # code. if layerName is None: compileFeatures( ufo, ttf, glyphSet=glyphSet, featureWriters=featureWriters, featureCompilerClass=featureCompilerClass, ) postProcessor = PostProcessor(ttf, ufo, glyphSet=glyphSet) ttf = postProcessor.process(useProductionNames) if layerName is not None: # for sparse masters (i.e. containing only a subset of the glyphs), we # need to include the post table in order to store glyph names, so that # fontTools.varLib can interpolate glyphs with same name across masters. # However we want to prevent the underlinePosition/underlineThickness # fields in such sparse masters to be included when computing the deltas # for the MVAR table. Thus, we set them to this unlikely, limit value # (-36768) which is a signal varLib should ignore them when building MVAR. ttf["post"].underlinePosition = -0x8000 ttf["post"].underlineThickness = -0x8000 yield ttf
[ "def", "compileInterpolatableTTFs", "(", "ufos", ",", "preProcessorClass", "=", "TTFInterpolatablePreProcessor", ",", "outlineCompilerClass", "=", "OutlineTTFCompiler", ",", "featureCompilerClass", "=", "None", ",", "featureWriters", "=", "None", ",", "glyphOrder", "=", ...
Create FontTools TrueType fonts from a list of UFOs with interpolatable outlines. Cubic curves are converted compatibly to quadratic curves using the Cu2Qu conversion algorithm. Return an iterator object that yields a TTFont instance for each UFO. *layerNames* refers to the layer names to use glyphs from in the order of the UFOs in *ufos*. By default, this is a list of `[None]` times the number of UFOs, i.e. using the default layer from all the UFOs. When the layerName is not None for a given UFO, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "glyf", "loca", "maxp", "post" and "vmtx"), and no OpenType layout tables. *skipExportGlyphs* is a list or set of glyph names to not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the parameter is not passed in, the union of all UFO's "public.skipExportGlyphs" lib keys will be used. If they don't exist, all glyphs are exported. UFO groups and kerning will be pruned of skipped glyphs.
[ "Create", "FontTools", "TrueType", "fonts", "from", "a", "list", "of", "UFOs", "with", "interpolatable", "outlines", ".", "Cubic", "curves", "are", "converted", "compatibly", "to", "quadratic", "curves", "using", "the", "Cu2Qu", "conversion", "algorithm", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L219-L316
25,549
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileInterpolatableTTFsFromDS
def compileInterpolatableTTFsFromDS( designSpaceDoc, preProcessorClass=TTFInterpolatablePreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, cubicConversionError=None, reverseDirection=True, inplace=False, ): """Create FontTools TrueType fonts from the DesignSpaceDocument UFO sources with interpolatable outlines. Cubic curves are converted compatibly to quadratic curves using the Cu2Qu conversion algorithm. If the Designspace contains a "public.skipExportGlyphs" lib key, these glyphs will not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the lib key doesn't exist in the Designspace, all glyphs are exported (keys in individual UFOs are ignored). UFO groups and kerning will be pruned of skipped glyphs. The DesignSpaceDocument should contain SourceDescriptor objects with 'font' attribute set to an already loaded defcon.Font object (or compatible UFO Font class). If 'font' attribute is unset or None, an AttributeError exception is thrown. Return a copy of the DesignSpaceDocument object (or the same one if inplace=True) with the source's 'font' attribute set to the corresponding TTFont instance. For sources that have the 'layerName' attribute defined, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "glyf", "loca", "maxp", "post" and "vmtx"), and no OpenType layout tables. """ ufos, layerNames = [], [] for source in designSpaceDoc.sources: if source.font is None: raise AttributeError( "designspace source '%s' is missing required 'font' attribute" % getattr(source, "name", "<Unknown>") ) ufos.append(source.font) # 'layerName' is None for the default layer layerNames.append(source.layerName) skipExportGlyphs = designSpaceDoc.lib.get("public.skipExportGlyphs", []) ttfs = compileInterpolatableTTFs( ufos, preProcessorClass=preProcessorClass, outlineCompilerClass=outlineCompilerClass, featureCompilerClass=featureCompilerClass, featureWriters=featureWriters, glyphOrder=glyphOrder, useProductionNames=useProductionNames, cubicConversionError=cubicConversionError, reverseDirection=reverseDirection, inplace=inplace, layerNames=layerNames, skipExportGlyphs=skipExportGlyphs, ) if inplace: result = designSpaceDoc else: # TODO try a more efficient copy method that doesn't involve (de)serializing result = designSpaceDoc.__class__.fromstring(designSpaceDoc.tostring()) for source, ttf in zip(result.sources, ttfs): source.font = ttf return result
python
def compileInterpolatableTTFsFromDS( designSpaceDoc, preProcessorClass=TTFInterpolatablePreProcessor, outlineCompilerClass=OutlineTTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, cubicConversionError=None, reverseDirection=True, inplace=False, ): ufos, layerNames = [], [] for source in designSpaceDoc.sources: if source.font is None: raise AttributeError( "designspace source '%s' is missing required 'font' attribute" % getattr(source, "name", "<Unknown>") ) ufos.append(source.font) # 'layerName' is None for the default layer layerNames.append(source.layerName) skipExportGlyphs = designSpaceDoc.lib.get("public.skipExportGlyphs", []) ttfs = compileInterpolatableTTFs( ufos, preProcessorClass=preProcessorClass, outlineCompilerClass=outlineCompilerClass, featureCompilerClass=featureCompilerClass, featureWriters=featureWriters, glyphOrder=glyphOrder, useProductionNames=useProductionNames, cubicConversionError=cubicConversionError, reverseDirection=reverseDirection, inplace=inplace, layerNames=layerNames, skipExportGlyphs=skipExportGlyphs, ) if inplace: result = designSpaceDoc else: # TODO try a more efficient copy method that doesn't involve (de)serializing result = designSpaceDoc.__class__.fromstring(designSpaceDoc.tostring()) for source, ttf in zip(result.sources, ttfs): source.font = ttf return result
[ "def", "compileInterpolatableTTFsFromDS", "(", "designSpaceDoc", ",", "preProcessorClass", "=", "TTFInterpolatablePreProcessor", ",", "outlineCompilerClass", "=", "OutlineTTFCompiler", ",", "featureCompilerClass", "=", "None", ",", "featureWriters", "=", "None", ",", "glyph...
Create FontTools TrueType fonts from the DesignSpaceDocument UFO sources with interpolatable outlines. Cubic curves are converted compatibly to quadratic curves using the Cu2Qu conversion algorithm. If the Designspace contains a "public.skipExportGlyphs" lib key, these glyphs will not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the lib key doesn't exist in the Designspace, all glyphs are exported (keys in individual UFOs are ignored). UFO groups and kerning will be pruned of skipped glyphs. The DesignSpaceDocument should contain SourceDescriptor objects with 'font' attribute set to an already loaded defcon.Font object (or compatible UFO Font class). If 'font' attribute is unset or None, an AttributeError exception is thrown. Return a copy of the DesignSpaceDocument object (or the same one if inplace=True) with the source's 'font' attribute set to the corresponding TTFont instance. For sources that have the 'layerName' attribute defined, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "glyf", "loca", "maxp", "post" and "vmtx"), and no OpenType layout tables.
[ "Create", "FontTools", "TrueType", "fonts", "from", "the", "DesignSpaceDocument", "UFO", "sources", "with", "interpolatable", "outlines", ".", "Cubic", "curves", "are", "converted", "compatibly", "to", "quadratic", "curves", "using", "the", "Cu2Qu", "conversion", "a...
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L319-L390
25,550
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileInterpolatableOTFsFromDS
def compileInterpolatableOTFsFromDS( designSpaceDoc, preProcessorClass=OTFPreProcessor, outlineCompilerClass=OutlineOTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, roundTolerance=None, inplace=False, ): """Create FontTools CFF fonts from the DesignSpaceDocument UFO sources with interpolatable outlines. Interpolatable means without subroutinization and specializer optimizations and no removal of overlaps. If the Designspace contains a "public.skipExportGlyphs" lib key, these glyphs will not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the lib key doesn't exist in the Designspace, all glyphs are exported (keys in individual UFOs are ignored). UFO groups and kerning will be pruned of skipped glyphs. The DesignSpaceDocument should contain SourceDescriptor objects with 'font' attribute set to an already loaded defcon.Font object (or compatible UFO Font class). If 'font' attribute is unset or None, an AttributeError exception is thrown. Return a copy of the DesignSpaceDocument object (or the same one if inplace=True) with the source's 'font' attribute set to the corresponding TTFont instance. For sources that have the 'layerName' attribute defined, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "CFF ", "maxp", "vmtx" and "VORG"), and no OpenType layout tables. """ for source in designSpaceDoc.sources: if source.font is None: raise AttributeError( "designspace source '%s' is missing required 'font' attribute" % getattr(source, "name", "<Unknown>") ) skipExportGlyphs = designSpaceDoc.lib.get("public.skipExportGlyphs", []) otfs = [] for source in designSpaceDoc.sources: otfs.append( compileOTF( ufo=source.font, layerName=source.layerName, preProcessorClass=preProcessorClass, outlineCompilerClass=outlineCompilerClass, featureCompilerClass=featureCompilerClass, featureWriters=featureWriters, glyphOrder=glyphOrder, useProductionNames=useProductionNames, optimizeCFF=CFFOptimization.NONE, roundTolerance=roundTolerance, removeOverlaps=False, overlapsBackend=None, inplace=inplace, skipExportGlyphs=skipExportGlyphs, _tables=SPARSE_OTF_MASTER_TABLES if source.layerName else None, ) ) if inplace: result = designSpaceDoc else: # TODO try a more efficient copy method that doesn't involve (de)serializing result = designSpaceDoc.__class__.fromstring(designSpaceDoc.tostring()) for source, otf in zip(result.sources, otfs): source.font = otf return result
python
def compileInterpolatableOTFsFromDS( designSpaceDoc, preProcessorClass=OTFPreProcessor, outlineCompilerClass=OutlineOTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, roundTolerance=None, inplace=False, ): for source in designSpaceDoc.sources: if source.font is None: raise AttributeError( "designspace source '%s' is missing required 'font' attribute" % getattr(source, "name", "<Unknown>") ) skipExportGlyphs = designSpaceDoc.lib.get("public.skipExportGlyphs", []) otfs = [] for source in designSpaceDoc.sources: otfs.append( compileOTF( ufo=source.font, layerName=source.layerName, preProcessorClass=preProcessorClass, outlineCompilerClass=outlineCompilerClass, featureCompilerClass=featureCompilerClass, featureWriters=featureWriters, glyphOrder=glyphOrder, useProductionNames=useProductionNames, optimizeCFF=CFFOptimization.NONE, roundTolerance=roundTolerance, removeOverlaps=False, overlapsBackend=None, inplace=inplace, skipExportGlyphs=skipExportGlyphs, _tables=SPARSE_OTF_MASTER_TABLES if source.layerName else None, ) ) if inplace: result = designSpaceDoc else: # TODO try a more efficient copy method that doesn't involve (de)serializing result = designSpaceDoc.__class__.fromstring(designSpaceDoc.tostring()) for source, otf in zip(result.sources, otfs): source.font = otf return result
[ "def", "compileInterpolatableOTFsFromDS", "(", "designSpaceDoc", ",", "preProcessorClass", "=", "OTFPreProcessor", ",", "outlineCompilerClass", "=", "OutlineOTFCompiler", ",", "featureCompilerClass", "=", "None", ",", "featureWriters", "=", "None", ",", "glyphOrder", "=",...
Create FontTools CFF fonts from the DesignSpaceDocument UFO sources with interpolatable outlines. Interpolatable means without subroutinization and specializer optimizations and no removal of overlaps. If the Designspace contains a "public.skipExportGlyphs" lib key, these glyphs will not be exported to the final font. If these glyphs are used as components in any other glyph, those components get decomposed. If the lib key doesn't exist in the Designspace, all glyphs are exported (keys in individual UFOs are ignored). UFO groups and kerning will be pruned of skipped glyphs. The DesignSpaceDocument should contain SourceDescriptor objects with 'font' attribute set to an already loaded defcon.Font object (or compatible UFO Font class). If 'font' attribute is unset or None, an AttributeError exception is thrown. Return a copy of the DesignSpaceDocument object (or the same one if inplace=True) with the source's 'font' attribute set to the corresponding TTFont instance. For sources that have the 'layerName' attribute defined, the corresponding TTFont object will contain only a minimum set of tables ("head", "hmtx", "CFF ", "maxp", "vmtx" and "VORG"), and no OpenType layout tables.
[ "Create", "FontTools", "CFF", "fonts", "from", "the", "DesignSpaceDocument", "UFO", "sources", "with", "interpolatable", "outlines", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L393-L470
25,551
googlefonts/ufo2ft
Lib/ufo2ft/__init__.py
compileFeatures
def compileFeatures( ufo, ttFont=None, glyphSet=None, featureWriters=None, featureCompilerClass=None, ): """ Compile OpenType Layout features from `ufo` into FontTools OTL tables. If `ttFont` is None, a new TTFont object is created containing the new tables, else the provided `ttFont` is updated with the new tables. If no explicit `featureCompilerClass` is provided, the one used will depend on whether the ufo contains any MTI feature files in its 'data' directory (thus the `MTIFeatureCompiler` is used) or not (then the default FeatureCompiler for Adobe FDK features is used). If skipExportGlyphs is provided (see description in the ``compile*`` functions), the feature compiler will prune groups (removing them if empty) and kerning of the UFO of these glyphs. The feature file is left untouched. """ if featureCompilerClass is None: if any( fn.startswith(MTI_FEATURES_PREFIX) and fn.endswith(".mti") for fn in ufo.data.fileNames ): featureCompilerClass = MtiFeatureCompiler else: featureCompilerClass = FeatureCompiler featureCompiler = featureCompilerClass( ufo, ttFont, glyphSet=glyphSet, featureWriters=featureWriters ) return featureCompiler.compile()
python
def compileFeatures( ufo, ttFont=None, glyphSet=None, featureWriters=None, featureCompilerClass=None, ): if featureCompilerClass is None: if any( fn.startswith(MTI_FEATURES_PREFIX) and fn.endswith(".mti") for fn in ufo.data.fileNames ): featureCompilerClass = MtiFeatureCompiler else: featureCompilerClass = FeatureCompiler featureCompiler = featureCompilerClass( ufo, ttFont, glyphSet=glyphSet, featureWriters=featureWriters ) return featureCompiler.compile()
[ "def", "compileFeatures", "(", "ufo", ",", "ttFont", "=", "None", ",", "glyphSet", "=", "None", ",", "featureWriters", "=", "None", ",", "featureCompilerClass", "=", "None", ",", ")", ":", "if", "featureCompilerClass", "is", "None", ":", "if", "any", "(", ...
Compile OpenType Layout features from `ufo` into FontTools OTL tables. If `ttFont` is None, a new TTFont object is created containing the new tables, else the provided `ttFont` is updated with the new tables. If no explicit `featureCompilerClass` is provided, the one used will depend on whether the ufo contains any MTI feature files in its 'data' directory (thus the `MTIFeatureCompiler` is used) or not (then the default FeatureCompiler for Adobe FDK features is used). If skipExportGlyphs is provided (see description in the ``compile*`` functions), the feature compiler will prune groups (removing them if empty) and kerning of the UFO of these glyphs. The feature file is left untouched.
[ "Compile", "OpenType", "Layout", "features", "from", "ufo", "into", "FontTools", "OTL", "tables", ".", "If", "ttFont", "is", "None", "a", "new", "TTFont", "object", "is", "created", "containing", "the", "new", "tables", "else", "the", "provided", "ttFont", "...
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/__init__.py#L473-L504
25,552
googlefonts/ufo2ft
Lib/ufo2ft/filters/propagateAnchors.py
_propagate_glyph_anchors
def _propagate_glyph_anchors(glyphSet, composite, processed): """ Propagate anchors from base glyphs to a given composite glyph, and to all composite glyphs used in between. """ if composite.name in processed: return processed.add(composite.name) if not composite.components: return base_components = [] mark_components = [] anchor_names = set() to_add = {} for component in composite.components: try: glyph = glyphSet[component.baseGlyph] except KeyError: logger.warning( 'Anchors not propagated for inexistent component {} ' 'in glyph {}'.format(component.baseGlyph, composite.name)) else: _propagate_glyph_anchors(glyphSet, glyph, processed) if any(a.name.startswith('_') for a in glyph.anchors): mark_components.append(component) else: base_components.append(component) anchor_names |= {a.name for a in glyph.anchors} if mark_components and not base_components and _is_ligature_mark(composite): # The composite is a mark that is composed of other marks (E.g. # "circumflexcomb_tildecomb"). Promote the mark that is positioned closest # to the origin to a base. try: component = _component_closest_to_origin(mark_components, glyphSet) except Exception as e: raise Exception( "Error while determining which component of composite " "'{}' is the lowest: {}".format(composite.name, str(e)) ) mark_components.remove(component) base_components.append(component) glyph = glyphSet[component.baseGlyph] anchor_names |= {a.name for a in glyph.anchors} for anchor_name in anchor_names: # don't add if composite glyph already contains this anchor OR any # associated ligature anchors (e.g. "top_1, top_2" for "top") if not any(a.name.startswith(anchor_name) for a in composite.anchors): _get_anchor_data(to_add, glyphSet, base_components, anchor_name) for component in mark_components: _adjust_anchors(to_add, glyphSet, component) # we sort propagated anchors to append in a deterministic order for name, (x, y) in sorted(to_add.items()): anchor_dict = {'name': name, 'x': x, 'y': y} try: composite.appendAnchor(anchor_dict) except TypeError: # pragma: no cover # fontParts API composite.appendAnchor(name, (x, y))
python
def _propagate_glyph_anchors(glyphSet, composite, processed): if composite.name in processed: return processed.add(composite.name) if not composite.components: return base_components = [] mark_components = [] anchor_names = set() to_add = {} for component in composite.components: try: glyph = glyphSet[component.baseGlyph] except KeyError: logger.warning( 'Anchors not propagated for inexistent component {} ' 'in glyph {}'.format(component.baseGlyph, composite.name)) else: _propagate_glyph_anchors(glyphSet, glyph, processed) if any(a.name.startswith('_') for a in glyph.anchors): mark_components.append(component) else: base_components.append(component) anchor_names |= {a.name for a in glyph.anchors} if mark_components and not base_components and _is_ligature_mark(composite): # The composite is a mark that is composed of other marks (E.g. # "circumflexcomb_tildecomb"). Promote the mark that is positioned closest # to the origin to a base. try: component = _component_closest_to_origin(mark_components, glyphSet) except Exception as e: raise Exception( "Error while determining which component of composite " "'{}' is the lowest: {}".format(composite.name, str(e)) ) mark_components.remove(component) base_components.append(component) glyph = glyphSet[component.baseGlyph] anchor_names |= {a.name for a in glyph.anchors} for anchor_name in anchor_names: # don't add if composite glyph already contains this anchor OR any # associated ligature anchors (e.g. "top_1, top_2" for "top") if not any(a.name.startswith(anchor_name) for a in composite.anchors): _get_anchor_data(to_add, glyphSet, base_components, anchor_name) for component in mark_components: _adjust_anchors(to_add, glyphSet, component) # we sort propagated anchors to append in a deterministic order for name, (x, y) in sorted(to_add.items()): anchor_dict = {'name': name, 'x': x, 'y': y} try: composite.appendAnchor(anchor_dict) except TypeError: # pragma: no cover # fontParts API composite.appendAnchor(name, (x, y))
[ "def", "_propagate_glyph_anchors", "(", "glyphSet", ",", "composite", ",", "processed", ")", ":", "if", "composite", ".", "name", "in", "processed", ":", "return", "processed", ".", "add", "(", "composite", ".", "name", ")", "if", "not", "composite", ".", ...
Propagate anchors from base glyphs to a given composite glyph, and to all composite glyphs used in between.
[ "Propagate", "anchors", "from", "base", "glyphs", "to", "a", "given", "composite", "glyph", "and", "to", "all", "composite", "glyphs", "used", "in", "between", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/filters/propagateAnchors.py#L51-L115
25,553
googlefonts/ufo2ft
Lib/ufo2ft/filters/propagateAnchors.py
_get_anchor_data
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name): """Get data for an anchor from a list of components.""" anchors = [] for component in components: for anchor in glyphSet[component.baseGlyph].anchors: if anchor.name == anchor_name: anchors.append((anchor, component)) break if len(anchors) > 1: for i, (anchor, component) in enumerate(anchors): t = Transform(*component.transformation) name = '%s_%d' % (anchor.name, i + 1) anchor_data[name] = t.transformPoint((anchor.x, anchor.y)) elif anchors: anchor, component = anchors[0] t = Transform(*component.transformation) anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
python
def _get_anchor_data(anchor_data, glyphSet, components, anchor_name): anchors = [] for component in components: for anchor in glyphSet[component.baseGlyph].anchors: if anchor.name == anchor_name: anchors.append((anchor, component)) break if len(anchors) > 1: for i, (anchor, component) in enumerate(anchors): t = Transform(*component.transformation) name = '%s_%d' % (anchor.name, i + 1) anchor_data[name] = t.transformPoint((anchor.x, anchor.y)) elif anchors: anchor, component = anchors[0] t = Transform(*component.transformation) anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
[ "def", "_get_anchor_data", "(", "anchor_data", ",", "glyphSet", ",", "components", ",", "anchor_name", ")", ":", "anchors", "=", "[", "]", "for", "component", "in", "components", ":", "for", "anchor", "in", "glyphSet", "[", "component", ".", "baseGlyph", "]"...
Get data for an anchor from a list of components.
[ "Get", "data", "for", "an", "anchor", "from", "a", "list", "of", "components", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/filters/propagateAnchors.py#L118-L135
25,554
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/baseFeatureWriter.py
BaseFeatureWriter.setContext
def setContext(self, font, feaFile, compiler=None): """ Populate a temporary `self.context` namespace, which is reset after each new call to `_write` method. Subclasses can override this to provide contextual information which depends on other data, or set any temporary attributes. The default implementation sets: - the current font; - the current FeatureFile object; - the current compiler instance (only present when this writer was instantiated from a FeatureCompiler); - a set of features (tags) to be generated. If self.mode is "skip", these are all the features which are _not_ already present. Returns the context namespace instance. """ todo = set(self.features) if self.mode == "skip": existing = ast.findFeatureTags(feaFile) todo.difference_update(existing) self.context = SimpleNamespace( font=font, feaFile=feaFile, compiler=compiler, todo=todo ) return self.context
python
def setContext(self, font, feaFile, compiler=None): todo = set(self.features) if self.mode == "skip": existing = ast.findFeatureTags(feaFile) todo.difference_update(existing) self.context = SimpleNamespace( font=font, feaFile=feaFile, compiler=compiler, todo=todo ) return self.context
[ "def", "setContext", "(", "self", ",", "font", ",", "feaFile", ",", "compiler", "=", "None", ")", ":", "todo", "=", "set", "(", "self", ".", "features", ")", "if", "self", ".", "mode", "==", "\"skip\"", ":", "existing", "=", "ast", ".", "findFeatureT...
Populate a temporary `self.context` namespace, which is reset after each new call to `_write` method. Subclasses can override this to provide contextual information which depends on other data, or set any temporary attributes. The default implementation sets: - the current font; - the current FeatureFile object; - the current compiler instance (only present when this writer was instantiated from a FeatureCompiler); - a set of features (tags) to be generated. If self.mode is "skip", these are all the features which are _not_ already present. Returns the context namespace instance.
[ "Populate", "a", "temporary", "self", ".", "context", "namespace", "which", "is", "reset", "after", "each", "new", "call", "to", "_write", "method", ".", "Subclasses", "can", "override", "this", "to", "provide", "contextual", "information", "which", "depends", ...
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L70-L95
25,555
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/baseFeatureWriter.py
BaseFeatureWriter.write
def write(self, font, feaFile, compiler=None): """Write features and class definitions for this font to a feaLib FeatureFile object. Returns True if feature file was modified, False if no new features were generated. """ self.setContext(font, feaFile, compiler=compiler) try: if self.shouldContinue(): return self._write() else: return False finally: del self.context
python
def write(self, font, feaFile, compiler=None): self.setContext(font, feaFile, compiler=compiler) try: if self.shouldContinue(): return self._write() else: return False finally: del self.context
[ "def", "write", "(", "self", ",", "font", ",", "feaFile", ",", "compiler", "=", "None", ")", ":", "self", ".", "setContext", "(", "font", ",", "feaFile", ",", "compiler", "=", "compiler", ")", "try", ":", "if", "self", ".", "shouldContinue", "(", ")"...
Write features and class definitions for this font to a feaLib FeatureFile object. Returns True if feature file was modified, False if no new features were generated.
[ "Write", "features", "and", "class", "definitions", "for", "this", "font", "to", "a", "feaLib", "FeatureFile", "object", ".", "Returns", "True", "if", "feature", "file", "was", "modified", "False", "if", "no", "new", "features", "were", "generated", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L109-L122
25,556
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/baseFeatureWriter.py
BaseFeatureWriter.makeUnicodeToGlyphNameMapping
def makeUnicodeToGlyphNameMapping(self): """Return the Unicode to glyph name mapping for the current font. """ # Try to get the "best" Unicode cmap subtable if this writer is running # in the context of a FeatureCompiler, else create a new mapping from # the UFO glyphs compiler = self.context.compiler cmap = None if compiler is not None: table = compiler.ttFont.get("cmap") if table is not None: cmap = table.getBestCmap() if cmap is None: from ufo2ft.util import makeUnicodeToGlyphNameMapping if compiler is not None: glyphSet = compiler.glyphSet else: glyphSet = self.context.font cmap = makeUnicodeToGlyphNameMapping(glyphSet) return cmap
python
def makeUnicodeToGlyphNameMapping(self): # Try to get the "best" Unicode cmap subtable if this writer is running # in the context of a FeatureCompiler, else create a new mapping from # the UFO glyphs compiler = self.context.compiler cmap = None if compiler is not None: table = compiler.ttFont.get("cmap") if table is not None: cmap = table.getBestCmap() if cmap is None: from ufo2ft.util import makeUnicodeToGlyphNameMapping if compiler is not None: glyphSet = compiler.glyphSet else: glyphSet = self.context.font cmap = makeUnicodeToGlyphNameMapping(glyphSet) return cmap
[ "def", "makeUnicodeToGlyphNameMapping", "(", "self", ")", ":", "# Try to get the \"best\" Unicode cmap subtable if this writer is running", "# in the context of a FeatureCompiler, else create a new mapping from", "# the UFO glyphs", "compiler", "=", "self", ".", "context", ".", "compil...
Return the Unicode to glyph name mapping for the current font.
[ "Return", "the", "Unicode", "to", "glyph", "name", "mapping", "for", "the", "current", "font", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L128-L148
25,557
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/baseFeatureWriter.py
BaseFeatureWriter.compileGSUB
def compileGSUB(self): """Compile a temporary GSUB table from the current feature file. """ from ufo2ft.util import compileGSUB compiler = self.context.compiler if compiler is not None: # The result is cached in the compiler instance, so if another # writer requests one it is not compiled again. if hasattr(compiler, "_gsub"): return compiler._gsub glyphOrder = compiler.ttFont.getGlyphOrder() else: # the 'real' glyph order doesn't matter because the table is not # compiled to binary, only the glyph names are used glyphOrder = sorted(self.context.font.keys()) gsub = compileGSUB(self.context.feaFile, glyphOrder) if compiler and not hasattr(compiler, "_gsub"): compiler._gsub = gsub return gsub
python
def compileGSUB(self): from ufo2ft.util import compileGSUB compiler = self.context.compiler if compiler is not None: # The result is cached in the compiler instance, so if another # writer requests one it is not compiled again. if hasattr(compiler, "_gsub"): return compiler._gsub glyphOrder = compiler.ttFont.getGlyphOrder() else: # the 'real' glyph order doesn't matter because the table is not # compiled to binary, only the glyph names are used glyphOrder = sorted(self.context.font.keys()) gsub = compileGSUB(self.context.feaFile, glyphOrder) if compiler and not hasattr(compiler, "_gsub"): compiler._gsub = gsub return gsub
[ "def", "compileGSUB", "(", "self", ")", ":", "from", "ufo2ft", ".", "util", "import", "compileGSUB", "compiler", "=", "self", ".", "context", ".", "compiler", "if", "compiler", "is", "not", "None", ":", "# The result is cached in the compiler instance, so if another...
Compile a temporary GSUB table from the current feature file.
[ "Compile", "a", "temporary", "GSUB", "table", "from", "the", "current", "feature", "file", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L163-L185
25,558
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.compile
def compile(self): """ Compile the OpenType binary. """ self.otf = TTFont(sfntVersion=self.sfntVersion) # only compile vertical metrics tables if vhea metrics a defined vertical_metrics = [ "openTypeVheaVertTypoAscender", "openTypeVheaVertTypoDescender", "openTypeVheaVertTypoLineGap", "openTypeVheaCaretSlopeRise", "openTypeVheaCaretSlopeRun", "openTypeVheaCaretOffset", ] self.vertical = all( getAttrWithFallback(self.ufo.info, metric) is not None for metric in vertical_metrics ) # write the glyph order self.otf.setGlyphOrder(self.glyphOrder) # populate basic tables self.setupTable_head() self.setupTable_hmtx() self.setupTable_hhea() self.setupTable_name() self.setupTable_maxp() self.setupTable_cmap() self.setupTable_OS2() self.setupTable_post() if self.vertical: self.setupTable_vmtx() self.setupTable_vhea() self.setupOtherTables() self.importTTX() return self.otf
python
def compile(self): self.otf = TTFont(sfntVersion=self.sfntVersion) # only compile vertical metrics tables if vhea metrics a defined vertical_metrics = [ "openTypeVheaVertTypoAscender", "openTypeVheaVertTypoDescender", "openTypeVheaVertTypoLineGap", "openTypeVheaCaretSlopeRise", "openTypeVheaCaretSlopeRun", "openTypeVheaCaretOffset", ] self.vertical = all( getAttrWithFallback(self.ufo.info, metric) is not None for metric in vertical_metrics ) # write the glyph order self.otf.setGlyphOrder(self.glyphOrder) # populate basic tables self.setupTable_head() self.setupTable_hmtx() self.setupTable_hhea() self.setupTable_name() self.setupTable_maxp() self.setupTable_cmap() self.setupTable_OS2() self.setupTable_post() if self.vertical: self.setupTable_vmtx() self.setupTable_vhea() self.setupOtherTables() self.importTTX() return self.otf
[ "def", "compile", "(", "self", ")", ":", "self", ".", "otf", "=", "TTFont", "(", "sfntVersion", "=", "self", ".", "sfntVersion", ")", "# only compile vertical metrics tables if vhea metrics a defined", "vertical_metrics", "=", "[", "\"openTypeVheaVertTypoAscender\"", ",...
Compile the OpenType binary.
[ "Compile", "the", "OpenType", "binary", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L94-L132
25,559
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.makeFontBoundingBox
def makeFontBoundingBox(self): """ Make a bounding box for the font. **This should not be called externally.** Subclasses may override this method to handle the bounds creation in a different way if desired. """ if not hasattr(self, "glyphBoundingBoxes"): self.glyphBoundingBoxes = self.makeGlyphsBoundingBoxes() fontBox = None for glyphName, glyphBox in self.glyphBoundingBoxes.items(): if glyphBox is None: continue if fontBox is None: fontBox = glyphBox else: fontBox = unionRect(fontBox, glyphBox) if fontBox is None: # unlikely fontBox = BoundingBox(0, 0, 0, 0) return fontBox
python
def makeFontBoundingBox(self): if not hasattr(self, "glyphBoundingBoxes"): self.glyphBoundingBoxes = self.makeGlyphsBoundingBoxes() fontBox = None for glyphName, glyphBox in self.glyphBoundingBoxes.items(): if glyphBox is None: continue if fontBox is None: fontBox = glyphBox else: fontBox = unionRect(fontBox, glyphBox) if fontBox is None: # unlikely fontBox = BoundingBox(0, 0, 0, 0) return fontBox
[ "def", "makeFontBoundingBox", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"glyphBoundingBoxes\"", ")", ":", "self", ".", "glyphBoundingBoxes", "=", "self", ".", "makeGlyphsBoundingBoxes", "(", ")", "fontBox", "=", "None", "for", "glyphNa...
Make a bounding box for the font. **This should not be called externally.** Subclasses may override this method to handle the bounds creation in a different way if desired.
[ "Make", "a", "bounding", "box", "for", "the", "font", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L164-L184
25,560
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.makeMissingRequiredGlyphs
def makeMissingRequiredGlyphs(font, glyphSet): """ Add .notdef to the glyph set if it is not present. **This should not be called externally.** Subclasses may override this method to handle the glyph creation in a different way if desired. """ if ".notdef" in glyphSet: return unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm")) ascender = otRound(getAttrWithFallback(font.info, "ascender")) descender = otRound(getAttrWithFallback(font.info, "descender")) defaultWidth = otRound(unitsPerEm * 0.5) glyphSet[".notdef"] = StubGlyph(name=".notdef", width=defaultWidth, unitsPerEm=unitsPerEm, ascender=ascender, descender=descender)
python
def makeMissingRequiredGlyphs(font, glyphSet): if ".notdef" in glyphSet: return unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm")) ascender = otRound(getAttrWithFallback(font.info, "ascender")) descender = otRound(getAttrWithFallback(font.info, "descender")) defaultWidth = otRound(unitsPerEm * 0.5) glyphSet[".notdef"] = StubGlyph(name=".notdef", width=defaultWidth, unitsPerEm=unitsPerEm, ascender=ascender, descender=descender)
[ "def", "makeMissingRequiredGlyphs", "(", "font", ",", "glyphSet", ")", ":", "if", "\".notdef\"", "in", "glyphSet", ":", "return", "unitsPerEm", "=", "otRound", "(", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"unitsPerEm\"", ")", ")", "ascender", "...
Add .notdef to the glyph set if it is not present. **This should not be called externally.** Subclasses may override this method to handle the glyph creation in a different way if desired.
[ "Add", ".", "notdef", "to", "the", "glyph", "set", "if", "it", "is", "not", "present", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L197-L216
25,561
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_head
def setupTable_head(self): """ Make the head table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "head" not in self.tables: return self.otf["head"] = head = newTable("head") font = self.ufo head.checkSumAdjustment = 0 head.tableVersion = 1.0 head.magicNumber = 0x5F0F3CF5 # version numbers # limit minor version to 3 digits as recommended in OpenType spec: # https://www.microsoft.com/typography/otspec/recom.htm versionMajor = getAttrWithFallback(font.info, "versionMajor") versionMinor = getAttrWithFallback(font.info, "versionMinor") fullFontRevision = float("%d.%03d" % (versionMajor, versionMinor)) head.fontRevision = round(fullFontRevision, 3) if head.fontRevision != fullFontRevision: logger.warning( "Minor version in %s has too many digits and won't fit into " "the head table's fontRevision field; rounded to %s.", fullFontRevision, head.fontRevision) # upm head.unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm")) # times head.created = dateStringToTimeValue(getAttrWithFallback(font.info, "openTypeHeadCreated")) - mac_epoch_diff head.modified = dateStringToTimeValue(dateStringForNow()) - mac_epoch_diff # bounding box xMin, yMin, xMax, yMax = self.fontBoundingBox head.xMin = otRound(xMin) head.yMin = otRound(yMin) head.xMax = otRound(xMax) head.yMax = otRound(yMax) # style mapping styleMapStyleName = getAttrWithFallback(font.info, "styleMapStyleName") macStyle = [] if styleMapStyleName == "bold": macStyle = [0] elif styleMapStyleName == "bold italic": macStyle = [0, 1] elif styleMapStyleName == "italic": macStyle = [1] head.macStyle = intListToNum(macStyle, 0, 16) # misc head.flags = intListToNum(getAttrWithFallback(font.info, "openTypeHeadFlags"), 0, 16) head.lowestRecPPEM = otRound(getAttrWithFallback(font.info, "openTypeHeadLowestRecPPEM")) head.fontDirectionHint = 2 head.indexToLocFormat = 0 head.glyphDataFormat = 0
python
def setupTable_head(self): if "head" not in self.tables: return self.otf["head"] = head = newTable("head") font = self.ufo head.checkSumAdjustment = 0 head.tableVersion = 1.0 head.magicNumber = 0x5F0F3CF5 # version numbers # limit minor version to 3 digits as recommended in OpenType spec: # https://www.microsoft.com/typography/otspec/recom.htm versionMajor = getAttrWithFallback(font.info, "versionMajor") versionMinor = getAttrWithFallback(font.info, "versionMinor") fullFontRevision = float("%d.%03d" % (versionMajor, versionMinor)) head.fontRevision = round(fullFontRevision, 3) if head.fontRevision != fullFontRevision: logger.warning( "Minor version in %s has too many digits and won't fit into " "the head table's fontRevision field; rounded to %s.", fullFontRevision, head.fontRevision) # upm head.unitsPerEm = otRound(getAttrWithFallback(font.info, "unitsPerEm")) # times head.created = dateStringToTimeValue(getAttrWithFallback(font.info, "openTypeHeadCreated")) - mac_epoch_diff head.modified = dateStringToTimeValue(dateStringForNow()) - mac_epoch_diff # bounding box xMin, yMin, xMax, yMax = self.fontBoundingBox head.xMin = otRound(xMin) head.yMin = otRound(yMin) head.xMax = otRound(xMax) head.yMax = otRound(yMax) # style mapping styleMapStyleName = getAttrWithFallback(font.info, "styleMapStyleName") macStyle = [] if styleMapStyleName == "bold": macStyle = [0] elif styleMapStyleName == "bold italic": macStyle = [0, 1] elif styleMapStyleName == "italic": macStyle = [1] head.macStyle = intListToNum(macStyle, 0, 16) # misc head.flags = intListToNum(getAttrWithFallback(font.info, "openTypeHeadFlags"), 0, 16) head.lowestRecPPEM = otRound(getAttrWithFallback(font.info, "openTypeHeadLowestRecPPEM")) head.fontDirectionHint = 2 head.indexToLocFormat = 0 head.glyphDataFormat = 0
[ "def", "setupTable_head", "(", "self", ")", ":", "if", "\"head\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"head\"", "]", "=", "head", "=", "newTable", "(", "\"head\"", ")", "font", "=", "self", ".", "ufo", "head...
Make the head table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "head", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L245-L305
25,562
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_name
def setupTable_name(self): """ Make the name table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "name" not in self.tables: return font = self.ufo self.otf["name"] = name = newTable("name") name.names = [] # Set name records from font.info.openTypeNameRecords for nameRecord in getAttrWithFallback( font.info, "openTypeNameRecords"): nameId = nameRecord["nameID"] platformId = nameRecord["platformID"] platEncId = nameRecord["encodingID"] langId = nameRecord["languageID"] # on Python 2, plistLib (used by ufoLib) returns unicode strings # only when plist data contain non-ascii characters, and returns # ascii-encoded bytes when it can. On the other hand, fontTools's # name table `setName` method wants unicode strings, so we must # decode them first nameVal = tounicode(nameRecord["string"], encoding='ascii') name.setName(nameVal, nameId, platformId, platEncId, langId) # Build name records familyName = getAttrWithFallback(font.info, "styleMapFamilyName") styleName = getAttrWithFallback(font.info, "styleMapStyleName").title() preferredFamilyName = getAttrWithFallback( font.info, "openTypeNamePreferredFamilyName") preferredSubfamilyName = getAttrWithFallback( font.info, "openTypeNamePreferredSubfamilyName") fullName = "%s %s" % (preferredFamilyName, preferredSubfamilyName) nameVals = { 0: getAttrWithFallback(font.info, "copyright"), 1: familyName, 2: styleName, 3: getAttrWithFallback(font.info, "openTypeNameUniqueID"), 4: fullName, 5: getAttrWithFallback(font.info, "openTypeNameVersion"), 6: getAttrWithFallback(font.info, "postscriptFontName"), 7: getAttrWithFallback(font.info, "trademark"), 8: getAttrWithFallback(font.info, "openTypeNameManufacturer"), 9: getAttrWithFallback(font.info, "openTypeNameDesigner"), 10: getAttrWithFallback(font.info, "openTypeNameDescription"), 11: getAttrWithFallback(font.info, "openTypeNameManufacturerURL"), 12: getAttrWithFallback(font.info, "openTypeNameDesignerURL"), 13: getAttrWithFallback(font.info, "openTypeNameLicense"), 14: getAttrWithFallback(font.info, "openTypeNameLicenseURL"), 16: preferredFamilyName, 17: preferredSubfamilyName, } # don't add typographic names if they are the same as the legacy ones if nameVals[1] == nameVals[16]: del nameVals[16] if nameVals[2] == nameVals[17]: del nameVals[17] # postscript font name if nameVals[6]: nameVals[6] = normalizeStringForPostscript(nameVals[6]) for nameId in sorted(nameVals.keys()): nameVal = nameVals[nameId] if not nameVal: continue nameVal = tounicode(nameVal, encoding='ascii') platformId = 3 platEncId = 10 if _isNonBMP(nameVal) else 1 langId = 0x409 # Set built name record if not set yet if name.getName(nameId, platformId, platEncId, langId): continue name.setName(nameVal, nameId, platformId, platEncId, langId)
python
def setupTable_name(self): if "name" not in self.tables: return font = self.ufo self.otf["name"] = name = newTable("name") name.names = [] # Set name records from font.info.openTypeNameRecords for nameRecord in getAttrWithFallback( font.info, "openTypeNameRecords"): nameId = nameRecord["nameID"] platformId = nameRecord["platformID"] platEncId = nameRecord["encodingID"] langId = nameRecord["languageID"] # on Python 2, plistLib (used by ufoLib) returns unicode strings # only when plist data contain non-ascii characters, and returns # ascii-encoded bytes when it can. On the other hand, fontTools's # name table `setName` method wants unicode strings, so we must # decode them first nameVal = tounicode(nameRecord["string"], encoding='ascii') name.setName(nameVal, nameId, platformId, platEncId, langId) # Build name records familyName = getAttrWithFallback(font.info, "styleMapFamilyName") styleName = getAttrWithFallback(font.info, "styleMapStyleName").title() preferredFamilyName = getAttrWithFallback( font.info, "openTypeNamePreferredFamilyName") preferredSubfamilyName = getAttrWithFallback( font.info, "openTypeNamePreferredSubfamilyName") fullName = "%s %s" % (preferredFamilyName, preferredSubfamilyName) nameVals = { 0: getAttrWithFallback(font.info, "copyright"), 1: familyName, 2: styleName, 3: getAttrWithFallback(font.info, "openTypeNameUniqueID"), 4: fullName, 5: getAttrWithFallback(font.info, "openTypeNameVersion"), 6: getAttrWithFallback(font.info, "postscriptFontName"), 7: getAttrWithFallback(font.info, "trademark"), 8: getAttrWithFallback(font.info, "openTypeNameManufacturer"), 9: getAttrWithFallback(font.info, "openTypeNameDesigner"), 10: getAttrWithFallback(font.info, "openTypeNameDescription"), 11: getAttrWithFallback(font.info, "openTypeNameManufacturerURL"), 12: getAttrWithFallback(font.info, "openTypeNameDesignerURL"), 13: getAttrWithFallback(font.info, "openTypeNameLicense"), 14: getAttrWithFallback(font.info, "openTypeNameLicenseURL"), 16: preferredFamilyName, 17: preferredSubfamilyName, } # don't add typographic names if they are the same as the legacy ones if nameVals[1] == nameVals[16]: del nameVals[16] if nameVals[2] == nameVals[17]: del nameVals[17] # postscript font name if nameVals[6]: nameVals[6] = normalizeStringForPostscript(nameVals[6]) for nameId in sorted(nameVals.keys()): nameVal = nameVals[nameId] if not nameVal: continue nameVal = tounicode(nameVal, encoding='ascii') platformId = 3 platEncId = 10 if _isNonBMP(nameVal) else 1 langId = 0x409 # Set built name record if not set yet if name.getName(nameId, platformId, platEncId, langId): continue name.setName(nameVal, nameId, platformId, platEncId, langId)
[ "def", "setupTable_name", "(", "self", ")", ":", "if", "\"name\"", "not", "in", "self", ".", "tables", ":", "return", "font", "=", "self", ".", "ufo", "self", ".", "otf", "[", "\"name\"", "]", "=", "name", "=", "newTable", "(", "\"name\"", ")", "name...
Make the name table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "name", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L307-L386
25,563
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_cmap
def setupTable_cmap(self): """ Make the cmap table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "cmap" not in self.tables: return from fontTools.ttLib.tables._c_m_a_p import cmap_format_4 nonBMP = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k > 65535) if nonBMP: mapping = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k <= 65535) else: mapping = dict(self.unicodeToGlyphNameMapping) # mac cmap4_0_3 = cmap_format_4(4) cmap4_0_3.platformID = 0 cmap4_0_3.platEncID = 3 cmap4_0_3.language = 0 cmap4_0_3.cmap = mapping # windows cmap4_3_1 = cmap_format_4(4) cmap4_3_1.platformID = 3 cmap4_3_1.platEncID = 1 cmap4_3_1.language = 0 cmap4_3_1.cmap = mapping # store self.otf["cmap"] = cmap = newTable("cmap") cmap.tableVersion = 0 cmap.tables = [cmap4_0_3, cmap4_3_1] # If we have glyphs outside Unicode BMP, we must set another # subtable that can hold longer codepoints for them. if nonBMP: from fontTools.ttLib.tables._c_m_a_p import cmap_format_12 nonBMP.update(mapping) # mac cmap12_0_4 = cmap_format_12(12) cmap12_0_4.platformID = 0 cmap12_0_4.platEncID = 4 cmap12_0_4.language = 0 cmap12_0_4.cmap = nonBMP # windows cmap12_3_10 = cmap_format_12(12) cmap12_3_10.platformID = 3 cmap12_3_10.platEncID = 10 cmap12_3_10.language = 0 cmap12_3_10.cmap = nonBMP # update tables registry cmap.tables = [cmap4_0_3, cmap4_3_1, cmap12_0_4, cmap12_3_10]
python
def setupTable_cmap(self): if "cmap" not in self.tables: return from fontTools.ttLib.tables._c_m_a_p import cmap_format_4 nonBMP = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k > 65535) if nonBMP: mapping = dict((k,v) for k,v in self.unicodeToGlyphNameMapping.items() if k <= 65535) else: mapping = dict(self.unicodeToGlyphNameMapping) # mac cmap4_0_3 = cmap_format_4(4) cmap4_0_3.platformID = 0 cmap4_0_3.platEncID = 3 cmap4_0_3.language = 0 cmap4_0_3.cmap = mapping # windows cmap4_3_1 = cmap_format_4(4) cmap4_3_1.platformID = 3 cmap4_3_1.platEncID = 1 cmap4_3_1.language = 0 cmap4_3_1.cmap = mapping # store self.otf["cmap"] = cmap = newTable("cmap") cmap.tableVersion = 0 cmap.tables = [cmap4_0_3, cmap4_3_1] # If we have glyphs outside Unicode BMP, we must set another # subtable that can hold longer codepoints for them. if nonBMP: from fontTools.ttLib.tables._c_m_a_p import cmap_format_12 nonBMP.update(mapping) # mac cmap12_0_4 = cmap_format_12(12) cmap12_0_4.platformID = 0 cmap12_0_4.platEncID = 4 cmap12_0_4.language = 0 cmap12_0_4.cmap = nonBMP # windows cmap12_3_10 = cmap_format_12(12) cmap12_3_10.platformID = 3 cmap12_3_10.platEncID = 10 cmap12_3_10.language = 0 cmap12_3_10.cmap = nonBMP # update tables registry cmap.tables = [cmap4_0_3, cmap4_3_1, cmap12_0_4, cmap12_3_10]
[ "def", "setupTable_cmap", "(", "self", ")", ":", "if", "\"cmap\"", "not", "in", "self", ".", "tables", ":", "return", "from", "fontTools", ".", "ttLib", ".", "tables", ".", "_c_m_a_p", "import", "cmap_format_4", "nonBMP", "=", "dict", "(", "(", "k", ",",...
Make the cmap table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "cmap", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L398-L450
25,564
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_hmtx
def setupTable_hmtx(self): """ Make the hmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "hmtx" not in self.tables: return self.otf["hmtx"] = hmtx = newTable("hmtx") hmtx.metrics = {} for glyphName, glyph in self.allGlyphs.items(): width = otRound(glyph.width) if width < 0: raise ValueError( "The width should not be negative: '%s'" % (glyphName)) bounds = self.glyphBoundingBoxes[glyphName] left = bounds.xMin if bounds else 0 hmtx[glyphName] = (width, left)
python
def setupTable_hmtx(self): if "hmtx" not in self.tables: return self.otf["hmtx"] = hmtx = newTable("hmtx") hmtx.metrics = {} for glyphName, glyph in self.allGlyphs.items(): width = otRound(glyph.width) if width < 0: raise ValueError( "The width should not be negative: '%s'" % (glyphName)) bounds = self.glyphBoundingBoxes[glyphName] left = bounds.xMin if bounds else 0 hmtx[glyphName] = (width, left)
[ "def", "setupTable_hmtx", "(", "self", ")", ":", "if", "\"hmtx\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"hmtx\"", "]", "=", "hmtx", "=", "newTable", "(", "\"hmtx\"", ")", "hmtx", ".", "metrics", "=", "{", "}",...
Make the hmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "hmtx", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L613-L633
25,565
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler._setupTable_hhea_or_vhea
def _setupTable_hhea_or_vhea(self, tag): """ Make the hhea table or the vhea table. This assume the hmtx or the vmtx were respectively made first. """ if tag not in self.tables: return if tag == "hhea": isHhea = True else: isHhea = False self.otf[tag] = table = newTable(tag) mtxTable = self.otf.get(tag[0] + "mtx") font = self.ufo if isHhea: table.tableVersion = 0x00010000 else: table.tableVersion = 0x00011000 # Vertical metrics in hhea, horizontal metrics in vhea # and caret info. # The hhea metrics names are formed as: # "openType" + tag.title() + "Ascender", etc. # While vhea metrics names are formed as: # "openType" + tag.title() + "VertTypo" + "Ascender", etc. # Caret info names only differ by tag.title(). commonPrefix = "openType%s" % tag.title() if isHhea: metricsPrefix = commonPrefix else: metricsPrefix = "openType%sVertTypo" % tag.title() metricsDict = { "ascent": "%sAscender" % metricsPrefix, "descent": "%sDescender" % metricsPrefix, "lineGap": "%sLineGap" % metricsPrefix, "caretSlopeRise": "%sCaretSlopeRise" % commonPrefix, "caretSlopeRun": "%sCaretSlopeRun" % commonPrefix, "caretOffset": "%sCaretOffset" % commonPrefix, } for otfName, ufoName in metricsDict.items(): setattr(table, otfName, otRound(getAttrWithFallback(font.info, ufoName))) # Horizontal metrics in hhea, vertical metrics in vhea advances = [] # width in hhea, height in vhea firstSideBearings = [] # left in hhea, top in vhea secondSideBearings = [] # right in hhea, bottom in vhea extents = [] if mtxTable is not None: for glyphName in self.allGlyphs: advance, firstSideBearing = mtxTable[glyphName] advances.append(advance) bounds = self.glyphBoundingBoxes[glyphName] if bounds is None: continue if isHhea: boundsAdvance = (bounds.xMax - bounds.xMin) # equation from the hhea spec for calculating xMaxExtent: # Max(lsb + (xMax - xMin)) extent = firstSideBearing + boundsAdvance else: boundsAdvance = (bounds.yMax - bounds.yMin) # equation from the vhea spec for calculating yMaxExtent: # Max(tsb + (yMax - yMin)). extent = firstSideBearing + boundsAdvance secondSideBearing = advance - firstSideBearing - boundsAdvance firstSideBearings.append(firstSideBearing) secondSideBearings.append(secondSideBearing) extents.append(extent) setattr(table, "advance%sMax" % ("Width" if isHhea else "Height"), max(advances) if advances else 0) setattr(table, "min%sSideBearing" % ("Left" if isHhea else "Top"), min(firstSideBearings) if firstSideBearings else 0) setattr(table, "min%sSideBearing" % ("Right" if isHhea else "Bottom"), min(secondSideBearings) if secondSideBearings else 0) setattr(table, "%sMaxExtent" % ("x" if isHhea else "y"), max(extents) if extents else 0) if isHhea: reserved = range(4) else: # vhea.reserved0 is caretOffset for legacy reasons reserved = range(1, 5) for i in reserved: setattr(table, "reserved%i" % i, 0) table.metricDataFormat = 0 # glyph count setattr(table, "numberOf%sMetrics" % ("H" if isHhea else "V"), len(self.allGlyphs))
python
def _setupTable_hhea_or_vhea(self, tag): if tag not in self.tables: return if tag == "hhea": isHhea = True else: isHhea = False self.otf[tag] = table = newTable(tag) mtxTable = self.otf.get(tag[0] + "mtx") font = self.ufo if isHhea: table.tableVersion = 0x00010000 else: table.tableVersion = 0x00011000 # Vertical metrics in hhea, horizontal metrics in vhea # and caret info. # The hhea metrics names are formed as: # "openType" + tag.title() + "Ascender", etc. # While vhea metrics names are formed as: # "openType" + tag.title() + "VertTypo" + "Ascender", etc. # Caret info names only differ by tag.title(). commonPrefix = "openType%s" % tag.title() if isHhea: metricsPrefix = commonPrefix else: metricsPrefix = "openType%sVertTypo" % tag.title() metricsDict = { "ascent": "%sAscender" % metricsPrefix, "descent": "%sDescender" % metricsPrefix, "lineGap": "%sLineGap" % metricsPrefix, "caretSlopeRise": "%sCaretSlopeRise" % commonPrefix, "caretSlopeRun": "%sCaretSlopeRun" % commonPrefix, "caretOffset": "%sCaretOffset" % commonPrefix, } for otfName, ufoName in metricsDict.items(): setattr(table, otfName, otRound(getAttrWithFallback(font.info, ufoName))) # Horizontal metrics in hhea, vertical metrics in vhea advances = [] # width in hhea, height in vhea firstSideBearings = [] # left in hhea, top in vhea secondSideBearings = [] # right in hhea, bottom in vhea extents = [] if mtxTable is not None: for glyphName in self.allGlyphs: advance, firstSideBearing = mtxTable[glyphName] advances.append(advance) bounds = self.glyphBoundingBoxes[glyphName] if bounds is None: continue if isHhea: boundsAdvance = (bounds.xMax - bounds.xMin) # equation from the hhea spec for calculating xMaxExtent: # Max(lsb + (xMax - xMin)) extent = firstSideBearing + boundsAdvance else: boundsAdvance = (bounds.yMax - bounds.yMin) # equation from the vhea spec for calculating yMaxExtent: # Max(tsb + (yMax - yMin)). extent = firstSideBearing + boundsAdvance secondSideBearing = advance - firstSideBearing - boundsAdvance firstSideBearings.append(firstSideBearing) secondSideBearings.append(secondSideBearing) extents.append(extent) setattr(table, "advance%sMax" % ("Width" if isHhea else "Height"), max(advances) if advances else 0) setattr(table, "min%sSideBearing" % ("Left" if isHhea else "Top"), min(firstSideBearings) if firstSideBearings else 0) setattr(table, "min%sSideBearing" % ("Right" if isHhea else "Bottom"), min(secondSideBearings) if secondSideBearings else 0) setattr(table, "%sMaxExtent" % ("x" if isHhea else "y"), max(extents) if extents else 0) if isHhea: reserved = range(4) else: # vhea.reserved0 is caretOffset for legacy reasons reserved = range(1, 5) for i in reserved: setattr(table, "reserved%i" % i, 0) table.metricDataFormat = 0 # glyph count setattr(table, "numberOf%sMetrics" % ("H" if isHhea else "V"), len(self.allGlyphs))
[ "def", "_setupTable_hhea_or_vhea", "(", "self", ",", "tag", ")", ":", "if", "tag", "not", "in", "self", ".", "tables", ":", "return", "if", "tag", "==", "\"hhea\"", ":", "isHhea", "=", "True", "else", ":", "isHhea", "=", "False", "self", ".", "otf", ...
Make the hhea table or the vhea table. This assume the hmtx or the vmtx were respectively made first.
[ "Make", "the", "hhea", "table", "or", "the", "vhea", "table", ".", "This", "assume", "the", "hmtx", "or", "the", "vmtx", "were", "respectively", "made", "first", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L635-L727
25,566
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_vmtx
def setupTable_vmtx(self): """ Make the vmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "vmtx" not in self.tables: return self.otf["vmtx"] = vmtx = newTable("vmtx") vmtx.metrics = {} for glyphName, glyph in self.allGlyphs.items(): height = otRound(glyph.height) if height < 0: raise ValueError( "The height should not be negative: '%s'" % (glyphName)) verticalOrigin = _getVerticalOrigin(self.otf, glyph) bounds = self.glyphBoundingBoxes[glyphName] top = bounds.yMax if bounds else 0 vmtx[glyphName] = (height, verticalOrigin - top)
python
def setupTable_vmtx(self): if "vmtx" not in self.tables: return self.otf["vmtx"] = vmtx = newTable("vmtx") vmtx.metrics = {} for glyphName, glyph in self.allGlyphs.items(): height = otRound(glyph.height) if height < 0: raise ValueError( "The height should not be negative: '%s'" % (glyphName)) verticalOrigin = _getVerticalOrigin(self.otf, glyph) bounds = self.glyphBoundingBoxes[glyphName] top = bounds.yMax if bounds else 0 vmtx[glyphName] = (height, verticalOrigin - top)
[ "def", "setupTable_vmtx", "(", "self", ")", ":", "if", "\"vmtx\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"vmtx\"", "]", "=", "vmtx", "=", "newTable", "(", "\"vmtx\"", ")", "vmtx", ".", "metrics", "=", "{", "}",...
Make the vmtx table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "vmtx", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L739-L760
25,567
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_VORG
def setupTable_VORG(self): """ Make the VORG table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "VORG" not in self.tables: return self.otf["VORG"] = vorg = newTable("VORG") vorg.majorVersion = 1 vorg.minorVersion = 0 vorg.VOriginRecords = {} # Find the most frequent verticalOrigin vorg_count = Counter(_getVerticalOrigin(self.otf, glyph) for glyph in self.allGlyphs.values()) vorg.defaultVertOriginY = vorg_count.most_common(1)[0][0] if len(vorg_count) > 1: for glyphName, glyph in self.allGlyphs.items(): vorg.VOriginRecords[glyphName] = _getVerticalOrigin( self.otf, glyph) vorg.numVertOriginYMetrics = len(vorg.VOriginRecords)
python
def setupTable_VORG(self): if "VORG" not in self.tables: return self.otf["VORG"] = vorg = newTable("VORG") vorg.majorVersion = 1 vorg.minorVersion = 0 vorg.VOriginRecords = {} # Find the most frequent verticalOrigin vorg_count = Counter(_getVerticalOrigin(self.otf, glyph) for glyph in self.allGlyphs.values()) vorg.defaultVertOriginY = vorg_count.most_common(1)[0][0] if len(vorg_count) > 1: for glyphName, glyph in self.allGlyphs.items(): vorg.VOriginRecords[glyphName] = _getVerticalOrigin( self.otf, glyph) vorg.numVertOriginYMetrics = len(vorg.VOriginRecords)
[ "def", "setupTable_VORG", "(", "self", ")", ":", "if", "\"VORG\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"VORG\"", "]", "=", "vorg", "=", "newTable", "(", "\"VORG\"", ")", "vorg", ".", "majorVersion", "=", "1", ...
Make the VORG table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "VORG", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L762-L785
25,568
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.setupTable_post
def setupTable_post(self): """ Make the post table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired. """ if "post" not in self.tables: return self.otf["post"] = post = newTable("post") font = self.ufo post.formatType = 3.0 # italic angle italicAngle = getAttrWithFallback(font.info, "italicAngle") post.italicAngle = italicAngle # underline underlinePosition = getAttrWithFallback(font.info, "postscriptUnderlinePosition") post.underlinePosition = otRound(underlinePosition) underlineThickness = getAttrWithFallback(font.info, "postscriptUnderlineThickness") post.underlineThickness = otRound(underlineThickness) post.isFixedPitch = getAttrWithFallback(font.info, "postscriptIsFixedPitch") # misc post.minMemType42 = 0 post.maxMemType42 = 0 post.minMemType1 = 0 post.maxMemType1 = 0
python
def setupTable_post(self): if "post" not in self.tables: return self.otf["post"] = post = newTable("post") font = self.ufo post.formatType = 3.0 # italic angle italicAngle = getAttrWithFallback(font.info, "italicAngle") post.italicAngle = italicAngle # underline underlinePosition = getAttrWithFallback(font.info, "postscriptUnderlinePosition") post.underlinePosition = otRound(underlinePosition) underlineThickness = getAttrWithFallback(font.info, "postscriptUnderlineThickness") post.underlineThickness = otRound(underlineThickness) post.isFixedPitch = getAttrWithFallback(font.info, "postscriptIsFixedPitch") # misc post.minMemType42 = 0 post.maxMemType42 = 0 post.minMemType1 = 0 post.maxMemType1 = 0
[ "def", "setupTable_post", "(", "self", ")", ":", "if", "\"post\"", "not", "in", "self", ".", "tables", ":", "return", "self", ".", "otf", "[", "\"post\"", "]", "=", "post", "=", "newTable", "(", "\"post\"", ")", "font", "=", "self", ".", "ufo", "post...
Make the post table. **This should not be called externally.** Subclasses may override or supplement this method to handle the table creation in a different way if desired.
[ "Make", "the", "post", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L798-L825
25,569
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
BaseOutlineCompiler.importTTX
def importTTX(self): """ Merge TTX files from data directory "com.github.fonttools.ttx" **This should not be called externally.** Subclasses may override this method to handle the bounds creation in a different way if desired. """ import os import re prefix = "com.github.fonttools.ttx" sfntVersionRE = re.compile('(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)', flags=re.MULTILINE) if not hasattr(self.ufo, "data"): return if not self.ufo.data.fileNames: return for path in self.ufo.data.fileNames: foldername, filename = os.path.split(path) if (foldername == prefix and filename.endswith(".ttx")): ttx = self.ufo.data[path].decode('utf-8') # strip 'sfntVersion' attribute from ttFont element, # if present, to avoid overwriting the current value ttx = sfntVersionRE.sub(r'\1\3', ttx) fp = BytesIO(ttx.encode('utf-8')) self.otf.importXML(fp)
python
def importTTX(self): import os import re prefix = "com.github.fonttools.ttx" sfntVersionRE = re.compile('(^<ttFont\s+)(sfntVersion=".*"\s+)(.*>$)', flags=re.MULTILINE) if not hasattr(self.ufo, "data"): return if not self.ufo.data.fileNames: return for path in self.ufo.data.fileNames: foldername, filename = os.path.split(path) if (foldername == prefix and filename.endswith(".ttx")): ttx = self.ufo.data[path].decode('utf-8') # strip 'sfntVersion' attribute from ttFont element, # if present, to avoid overwriting the current value ttx = sfntVersionRE.sub(r'\1\3', ttx) fp = BytesIO(ttx.encode('utf-8')) self.otf.importXML(fp)
[ "def", "importTTX", "(", "self", ")", ":", "import", "os", "import", "re", "prefix", "=", "\"com.github.fonttools.ttx\"", "sfntVersionRE", "=", "re", ".", "compile", "(", "'(^<ttFont\\s+)(sfntVersion=\".*\"\\s+)(.*>$)'", ",", "flags", "=", "re", ".", "MULTILINE", ...
Merge TTX files from data directory "com.github.fonttools.ttx" **This should not be called externally.** Subclasses may override this method to handle the bounds creation in a different way if desired.
[ "Merge", "TTX", "files", "from", "data", "directory", "com", ".", "github", ".", "fonttools", ".", "ttx" ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L837-L863
25,570
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
OutlineTTFCompiler.setupTable_post
def setupTable_post(self): """Make a format 2 post table with the compiler's glyph order.""" super(OutlineTTFCompiler, self).setupTable_post() if "post" not in self.otf: return post = self.otf["post"] post.formatType = 2.0 post.extraNames = [] post.mapping = {} post.glyphOrder = self.glyphOrder
python
def setupTable_post(self): super(OutlineTTFCompiler, self).setupTable_post() if "post" not in self.otf: return post = self.otf["post"] post.formatType = 2.0 post.extraNames = [] post.mapping = {} post.glyphOrder = self.glyphOrder
[ "def", "setupTable_post", "(", "self", ")", ":", "super", "(", "OutlineTTFCompiler", ",", "self", ")", ".", "setupTable_post", "(", ")", "if", "\"post\"", "not", "in", "self", ".", "otf", ":", "return", "post", "=", "self", ".", "otf", "[", "\"post\"", ...
Make a format 2 post table with the compiler's glyph order.
[ "Make", "a", "format", "2", "post", "table", "with", "the", "compiler", "s", "glyph", "order", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L1143-L1153
25,571
googlefonts/ufo2ft
Lib/ufo2ft/outlineCompiler.py
OutlineTTFCompiler.setupTable_glyf
def setupTable_glyf(self): """Make the glyf table.""" if not {"glyf", "loca"}.issubset(self.tables): return self.otf["loca"] = newTable("loca") self.otf["glyf"] = glyf = newTable("glyf") glyf.glyphs = {} glyf.glyphOrder = self.glyphOrder hmtx = self.otf.get("hmtx") allGlyphs = self.allGlyphs for name in self.glyphOrder: glyph = allGlyphs[name] pen = TTGlyphPen(allGlyphs) try: glyph.draw(pen) except NotImplementedError: logger.error("%r has invalid curve format; skipped", name) ttGlyph = Glyph() else: ttGlyph = pen.glyph() if ( ttGlyph.isComposite() and hmtx is not None and self.autoUseMyMetrics ): self.autoUseMyMetrics(ttGlyph, name, hmtx) glyf[name] = ttGlyph
python
def setupTable_glyf(self): if not {"glyf", "loca"}.issubset(self.tables): return self.otf["loca"] = newTable("loca") self.otf["glyf"] = glyf = newTable("glyf") glyf.glyphs = {} glyf.glyphOrder = self.glyphOrder hmtx = self.otf.get("hmtx") allGlyphs = self.allGlyphs for name in self.glyphOrder: glyph = allGlyphs[name] pen = TTGlyphPen(allGlyphs) try: glyph.draw(pen) except NotImplementedError: logger.error("%r has invalid curve format; skipped", name) ttGlyph = Glyph() else: ttGlyph = pen.glyph() if ( ttGlyph.isComposite() and hmtx is not None and self.autoUseMyMetrics ): self.autoUseMyMetrics(ttGlyph, name, hmtx) glyf[name] = ttGlyph
[ "def", "setupTable_glyf", "(", "self", ")", ":", "if", "not", "{", "\"glyf\"", ",", "\"loca\"", "}", ".", "issubset", "(", "self", ".", "tables", ")", ":", "return", "self", ".", "otf", "[", "\"loca\"", "]", "=", "newTable", "(", "\"loca\"", ")", "se...
Make the glyf table.
[ "Make", "the", "glyf", "table", "." ]
915b986558e87bee288765d9218cc1cd4ebf7f4c
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/outlineCompiler.py#L1160-L1188
25,572
quadrismegistus/prosodic
prosodic/dicts/en/syllabify.py
loadLanguage
def loadLanguage(filename) : '''This function loads up a language configuration file and returns the configuration to be passed to the syllabify function.''' L = { "consonants" : [], "vowels" : [], "onsets" : [] } f = open(filename, "r") section = None for line in f : line = line.strip() if line in ("[consonants]", "[vowels]", "[onsets]") : section = line[1:-1] elif section == None : raise ValueError, "File must start with a section header such as [consonants]." elif not section in L : raise ValueError, "Invalid section: " + section else : L[section].append(line) for section in "consonants", "vowels", "onsets" : if len(L[section]) == 0 : raise ValueError, "File does not contain any consonants, vowels, or onsets." return L
python
def loadLanguage(filename) : '''This function loads up a language configuration file and returns the configuration to be passed to the syllabify function.''' L = { "consonants" : [], "vowels" : [], "onsets" : [] } f = open(filename, "r") section = None for line in f : line = line.strip() if line in ("[consonants]", "[vowels]", "[onsets]") : section = line[1:-1] elif section == None : raise ValueError, "File must start with a section header such as [consonants]." elif not section in L : raise ValueError, "Invalid section: " + section else : L[section].append(line) for section in "consonants", "vowels", "onsets" : if len(L[section]) == 0 : raise ValueError, "File does not contain any consonants, vowels, or onsets." return L
[ "def", "loadLanguage", "(", "filename", ")", ":", "L", "=", "{", "\"consonants\"", ":", "[", "]", ",", "\"vowels\"", ":", "[", "]", ",", "\"onsets\"", ":", "[", "]", "}", "f", "=", "open", "(", "filename", ",", "\"r\"", ")", "section", "=", "None",...
This function loads up a language configuration file and returns the configuration to be passed to the syllabify function.
[ "This", "function", "loads", "up", "a", "language", "configuration", "file", "and", "returns", "the", "configuration", "to", "be", "passed", "to", "the", "syllabify", "function", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/dicts/en/syllabify.py#L56-L79
25,573
quadrismegistus/prosodic
prosodic/dicts/en/syllabify.py
stringify
def stringify(syllables) : '''This function takes a syllabification returned by syllabify and turns it into a string, with phonemes spearated by spaces and syllables spearated by periods.''' ret = [] for syl in syllables : stress, onset, nucleus, coda = syl if stress != None and len(nucleus) != 0 : nucleus[0] += str(stress) ret.append(" ".join(onset + nucleus + coda)) return " . ".join(ret)
python
def stringify(syllables) : '''This function takes a syllabification returned by syllabify and turns it into a string, with phonemes spearated by spaces and syllables spearated by periods.''' ret = [] for syl in syllables : stress, onset, nucleus, coda = syl if stress != None and len(nucleus) != 0 : nucleus[0] += str(stress) ret.append(" ".join(onset + nucleus + coda)) return " . ".join(ret)
[ "def", "stringify", "(", "syllables", ")", ":", "ret", "=", "[", "]", "for", "syl", "in", "syllables", ":", "stress", ",", "onset", ",", "nucleus", ",", "coda", "=", "syl", "if", "stress", "!=", "None", "and", "len", "(", "nucleus", ")", "!=", "0",...
This function takes a syllabification returned by syllabify and turns it into a string, with phonemes spearated by spaces and syllables spearated by periods.
[ "This", "function", "takes", "a", "syllabification", "returned", "by", "syllabify", "and", "turns", "it", "into", "a", "string", "with", "phonemes", "spearated", "by", "spaces", "and", "syllables", "spearated", "by", "periods", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/dicts/en/syllabify.py#L158-L168
25,574
quadrismegistus/prosodic
prosodic/tools.py
slice
def slice(l,num_slices=None,slice_length=None,runts=True,random=False): """ Returns a new list of n evenly-sized segments of the original list """ if random: import random random.shuffle(l) if not num_slices and not slice_length: return l if not slice_length: slice_length=int(len(l)/num_slices) newlist=[l[i:i+slice_length] for i in range(0, len(l), slice_length)] if runts: return newlist return [lx for lx in newlist if len(lx)==slice_length]
python
def slice(l,num_slices=None,slice_length=None,runts=True,random=False): if random: import random random.shuffle(l) if not num_slices and not slice_length: return l if not slice_length: slice_length=int(len(l)/num_slices) newlist=[l[i:i+slice_length] for i in range(0, len(l), slice_length)] if runts: return newlist return [lx for lx in newlist if len(lx)==slice_length]
[ "def", "slice", "(", "l", ",", "num_slices", "=", "None", ",", "slice_length", "=", "None", ",", "runts", "=", "True", ",", "random", "=", "False", ")", ":", "if", "random", ":", "import", "random", "random", ".", "shuffle", "(", "l", ")", "if", "n...
Returns a new list of n evenly-sized segments of the original list
[ "Returns", "a", "new", "list", "of", "n", "evenly", "-", "sized", "segments", "of", "the", "original", "list" ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/tools.py#L3-L14
25,575
quadrismegistus/prosodic
prosodic/entity.py
entity.u2s
def u2s(self,u): """Returns an ASCII representation of the Unicode string 'u'.""" try: return u.encode('utf-8',errors='ignore') except (UnicodeDecodeError,AttributeError) as e: try: return str(u) except UnicodeEncodeError: return unicode(u).encode('utf-8',errors='ignore')
python
def u2s(self,u): try: return u.encode('utf-8',errors='ignore') except (UnicodeDecodeError,AttributeError) as e: try: return str(u) except UnicodeEncodeError: return unicode(u).encode('utf-8',errors='ignore')
[ "def", "u2s", "(", "self", ",", "u", ")", ":", "try", ":", "return", "u", ".", "encode", "(", "'utf-8'", ",", "errors", "=", "'ignore'", ")", "except", "(", "UnicodeDecodeError", ",", "AttributeError", ")", "as", "e", ":", "try", ":", "return", "str"...
Returns an ASCII representation of the Unicode string 'u'.
[ "Returns", "an", "ASCII", "representation", "of", "the", "Unicode", "string", "u", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L217-L226
25,576
quadrismegistus/prosodic
prosodic/entity.py
entity.wordtokens
def wordtokens(self,include_punct=True): """Returns a list of this object's Words in order of their appearance. Set flattenList to False to receive a list of lists of Words.""" ws=self.ents('WordToken') if not include_punct: return [w for w in ws if not w.is_punct] return ws
python
def wordtokens(self,include_punct=True): ws=self.ents('WordToken') if not include_punct: return [w for w in ws if not w.is_punct] return ws
[ "def", "wordtokens", "(", "self", ",", "include_punct", "=", "True", ")", ":", "ws", "=", "self", ".", "ents", "(", "'WordToken'", ")", "if", "not", "include_punct", ":", "return", "[", "w", "for", "w", "in", "ws", "if", "not", "w", ".", "is_punct", ...
Returns a list of this object's Words in order of their appearance. Set flattenList to False to receive a list of lists of Words.
[ "Returns", "a", "list", "of", "this", "object", "s", "Words", "in", "order", "of", "their", "appearance", ".", "Set", "flattenList", "to", "False", "to", "receive", "a", "list", "of", "lists", "of", "Words", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L387-L392
25,577
quadrismegistus/prosodic
prosodic/entity.py
entity.dir
def dir(self,methods=True,showall=True): """Show this object's attributes and methods.""" import inspect #print "[attributes]" for k,v in sorted(self.__dict__.items()): if k.startswith("_"): continue print makeminlength("."+k,being.linelen),"\t",v if not methods: return entmethods=dir(entity) print #print "[methods]" for x in [x for x in dir(self) if ("bound method "+self.classname() in str(getattr(self,x))) and not x.startswith("_")]: if (not showall) and (x in entmethods): continue attr=getattr(self,x) #print attr.__dict__ #print dir(attr) #doc=inspect.getdoc(attr) doc = attr.__doc__ if not doc: doc="" #else: # docsplit=[z for z in doc.replace("\r","\n").split("\n") if z] # if len(docsplit)>1: # doc = docsplit[0] + "\n" + makeminlength(" ",being.linelen) + "\n".join( makeminlength(" ",being.linelen)+"\t"+z for z in docsplit[1:]) # else: # doc = docsplit[0] y=describe_func(attr) if not y: y="" else: y=", ".join(a+"="+str(b) for (a,b) in y) print makeminlength("."+x+"("+y+")",being.linelen),"\t", doc if showall: print
python
def dir(self,methods=True,showall=True): import inspect #print "[attributes]" for k,v in sorted(self.__dict__.items()): if k.startswith("_"): continue print makeminlength("."+k,being.linelen),"\t",v if not methods: return entmethods=dir(entity) print #print "[methods]" for x in [x for x in dir(self) if ("bound method "+self.classname() in str(getattr(self,x))) and not x.startswith("_")]: if (not showall) and (x in entmethods): continue attr=getattr(self,x) #print attr.__dict__ #print dir(attr) #doc=inspect.getdoc(attr) doc = attr.__doc__ if not doc: doc="" #else: # docsplit=[z for z in doc.replace("\r","\n").split("\n") if z] # if len(docsplit)>1: # doc = docsplit[0] + "\n" + makeminlength(" ",being.linelen) + "\n".join( makeminlength(" ",being.linelen)+"\t"+z for z in docsplit[1:]) # else: # doc = docsplit[0] y=describe_func(attr) if not y: y="" else: y=", ".join(a+"="+str(b) for (a,b) in y) print makeminlength("."+x+"("+y+")",being.linelen),"\t", doc if showall: print
[ "def", "dir", "(", "self", ",", "methods", "=", "True", ",", "showall", "=", "True", ")", ":", "import", "inspect", "#print \"[attributes]\"", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "__dict__", ".", "items", "(", ")", ")", ":", "if",...
Show this object's attributes and methods.
[ "Show", "this", "object", "s", "attributes", "and", "methods", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L433-L472
25,578
quadrismegistus/prosodic
prosodic/entity.py
entity.makeBubbleChart
def makeBubbleChart(self,posdict,name,stattup=None): """Returns HTML for a bubble chart of the positin dictionary.""" xname=[x for x in name.split(".") if x.startswith("X_")][0] yname=[x for x in name.split(".") if x.startswith("Y_")][0] #elsename=name.replace(xname,'').replace(yname,'').replace('..','.').replace('..','.') o='<div id="'+name+'"><h2>'+name+'</h2>' if stattup: cc=stattup[0] p=stattup[1] o+='<h3>corr.coef='+str(cc)+' / p-value='+str(p)+'</h3>' o+='<br/><script type="text/javascript">\nvar myChart = new Chart.Bubble("'+name+'", {\nwidth: 400,\nheight: 400,\n bubbleSize: 10,\nxlabel:"'+xname+'",\nylabel:"'+yname+'"});\n' for posnum,xydict in posdict.items(): x_avg,x_std=mean_stdev(xydict['x']) y_avg,y_std=mean_stdev(xydict['y']) z=1/(x_std+y_std) o+='myChart.addBubble('+str(x_avg*100)+', '+str(y_avg*100)+', '+str(z)+', "#666", "'+str(posnum+1)+' [%'+str(x_avg*100)[0:5]+', %'+str(y_avg*100)[0:5]+']");\n' o+='myChart.redraw();\n</script>\n</div>' return o
python
def makeBubbleChart(self,posdict,name,stattup=None): xname=[x for x in name.split(".") if x.startswith("X_")][0] yname=[x for x in name.split(".") if x.startswith("Y_")][0] #elsename=name.replace(xname,'').replace(yname,'').replace('..','.').replace('..','.') o='<div id="'+name+'"><h2>'+name+'</h2>' if stattup: cc=stattup[0] p=stattup[1] o+='<h3>corr.coef='+str(cc)+' / p-value='+str(p)+'</h3>' o+='<br/><script type="text/javascript">\nvar myChart = new Chart.Bubble("'+name+'", {\nwidth: 400,\nheight: 400,\n bubbleSize: 10,\nxlabel:"'+xname+'",\nylabel:"'+yname+'"});\n' for posnum,xydict in posdict.items(): x_avg,x_std=mean_stdev(xydict['x']) y_avg,y_std=mean_stdev(xydict['y']) z=1/(x_std+y_std) o+='myChart.addBubble('+str(x_avg*100)+', '+str(y_avg*100)+', '+str(z)+', "#666", "'+str(posnum+1)+' [%'+str(x_avg*100)[0:5]+', %'+str(y_avg*100)[0:5]+']");\n' o+='myChart.redraw();\n</script>\n</div>' return o
[ "def", "makeBubbleChart", "(", "self", ",", "posdict", ",", "name", ",", "stattup", "=", "None", ")", ":", "xname", "=", "[", "x", "for", "x", "in", "name", ".", "split", "(", "\".\"", ")", "if", "x", ".", "startswith", "(", "\"X_\"", ")", "]", "...
Returns HTML for a bubble chart of the positin dictionary.
[ "Returns", "HTML", "for", "a", "bubble", "chart", "of", "the", "positin", "dictionary", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L790-L816
25,579
quadrismegistus/prosodic
prosodic/entity.py
entity.getName
def getName(self): """Return a Name string for this object.""" name=self.findattr('name') if not name: name="_directinput_" if self.classname().lower()=="line": name+="."+str(self).replace(" ","_").lower() else: name=name.replace('.txt','') while name.startswith("."): name=name[1:] return name
python
def getName(self): name=self.findattr('name') if not name: name="_directinput_" if self.classname().lower()=="line": name+="."+str(self).replace(" ","_").lower() else: name=name.replace('.txt','') while name.startswith("."): name=name[1:] return name
[ "def", "getName", "(", "self", ")", ":", "name", "=", "self", ".", "findattr", "(", "'name'", ")", "if", "not", "name", ":", "name", "=", "\"_directinput_\"", "if", "self", ".", "classname", "(", ")", ".", "lower", "(", ")", "==", "\"line\"", ":", ...
Return a Name string for this object.
[ "Return", "a", "Name", "string", "for", "this", "object", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L956-L970
25,580
quadrismegistus/prosodic
prosodic/entity.py
entity.scansion_prepare
def scansion_prepare(self,meter=None,conscious=False): """Print out header column for line-scansions for a given meter. """ import prosodic config=prosodic.config if not meter: if not hasattr(self,'_Text__bestparses'): return x=getattr(self,'_Text__bestparses') if not x.keys(): return meter=x.keys()[0] ckeys="\t".join(sorted([str(x) for x in meter.constraints])) self.om("\t".join([makeminlength(str("text"),config['linelen']), makeminlength(str("parse"),config['linelen']),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious)
python
def scansion_prepare(self,meter=None,conscious=False): import prosodic config=prosodic.config if not meter: if not hasattr(self,'_Text__bestparses'): return x=getattr(self,'_Text__bestparses') if not x.keys(): return meter=x.keys()[0] ckeys="\t".join(sorted([str(x) for x in meter.constraints])) self.om("\t".join([makeminlength(str("text"),config['linelen']), makeminlength(str("parse"),config['linelen']),"meter","num_parses","num_viols","score_viols",ckeys]),conscious=conscious)
[ "def", "scansion_prepare", "(", "self", ",", "meter", "=", "None", ",", "conscious", "=", "False", ")", ":", "import", "prosodic", "config", "=", "prosodic", ".", "config", "if", "not", "meter", ":", "if", "not", "hasattr", "(", "self", ",", "'_Text__bes...
Print out header column for line-scansions for a given meter.
[ "Print", "out", "header", "column", "for", "line", "-", "scansions", "for", "a", "given", "meter", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1138-L1150
25,581
quadrismegistus/prosodic
prosodic/entity.py
entity.report
def report(self,meter=None,include_bounded=False,reverse=True): """ Print all parses and their violations in a structured format. """ ReportStr = '' if not meter: from Meter import Meter meter=Meter.genDefault() if (hasattr(self,'allParses')): self.om(unicode(self)) allparses=self.allParses(meter=meter,include_bounded=include_bounded) numallparses=len(allparses) #allparses = reversed(allparses) if reverse else allparses for pi,parseList in enumerate(allparses): line=self.iparse2line(pi).txt #parseList.sort(key = lambda P: P.score()) hdr="\n\n"+'='*30+'\n[line #'+str(pi+1)+' of '+str(numallparses)+']: '+line+'\n\n\t' ftr='='*30+'\n' ReportStr+=self.om(hdr+meter.printParses(parseList,reverse=reverse).replace('\n','\n\t')[:-1]+ftr,conscious=False) else: for child in self.children: if type(child)==type([]): continue ReportStr+=child.report() return ReportStr
python
def report(self,meter=None,include_bounded=False,reverse=True): ReportStr = '' if not meter: from Meter import Meter meter=Meter.genDefault() if (hasattr(self,'allParses')): self.om(unicode(self)) allparses=self.allParses(meter=meter,include_bounded=include_bounded) numallparses=len(allparses) #allparses = reversed(allparses) if reverse else allparses for pi,parseList in enumerate(allparses): line=self.iparse2line(pi).txt #parseList.sort(key = lambda P: P.score()) hdr="\n\n"+'='*30+'\n[line #'+str(pi+1)+' of '+str(numallparses)+']: '+line+'\n\n\t' ftr='='*30+'\n' ReportStr+=self.om(hdr+meter.printParses(parseList,reverse=reverse).replace('\n','\n\t')[:-1]+ftr,conscious=False) else: for child in self.children: if type(child)==type([]): continue ReportStr+=child.report() return ReportStr
[ "def", "report", "(", "self", ",", "meter", "=", "None", ",", "include_bounded", "=", "False", ",", "reverse", "=", "True", ")", ":", "ReportStr", "=", "''", "if", "not", "meter", ":", "from", "Meter", "import", "Meter", "meter", "=", "Meter", ".", "...
Print all parses and their violations in a structured format.
[ "Print", "all", "parses", "and", "their", "violations", "in", "a", "structured", "format", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1168-L1191
25,582
quadrismegistus/prosodic
prosodic/entity.py
entity.tree
def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']): """Print a tree-structure of this object's phonological representation.""" tree = "" numchild=0 for child in self.children: if type(child)==type([]): child=child[0] numchild+=1 classname=child.classname() if classname=="Word": tree+="\n\n" elif classname=="Line": tree+="\n\n\n" elif classname=="Stanza": tree+="\n\n\n\n" if offset!=0: tree+="\n" for i in range(0,offset): tree+=" " #if not len(child.feats): # tree+=" " tree+="|" tree+="\n" newline="" for i in range(0,offset): newline+=" " newline+="|" cname="" for letter in classname: if letter==letter.upper(): cname+=letter prefix=prefix_inherited+cname+str(numchild) + "." newline+="-----| ("+prefix[:-1]+") <"+classname+">" if child.isBroken(): newline+="<<broken>>" else: string=self.u2s(child) if (not "<" in string): newline=makeminlength(newline,99) newline+="["+string+"]" elif string[0]!="<": newline+="\t"+string if len(child.feats): if (not child.classname() in nofeatsplease): for k,v in sorted(child.feats.items()): if v==None: continue newline+="\n" for i in range(0,offset+1): newline+=" " newline+="| " newline+=self.showFeat(k,v) tree+=newline tree+=child.tree(offset+1,prefix) return tree
python
def tree(self,offset=0,prefix_inherited="",nofeatsplease=['Phoneme']): tree = "" numchild=0 for child in self.children: if type(child)==type([]): child=child[0] numchild+=1 classname=child.classname() if classname=="Word": tree+="\n\n" elif classname=="Line": tree+="\n\n\n" elif classname=="Stanza": tree+="\n\n\n\n" if offset!=0: tree+="\n" for i in range(0,offset): tree+=" " #if not len(child.feats): # tree+=" " tree+="|" tree+="\n" newline="" for i in range(0,offset): newline+=" " newline+="|" cname="" for letter in classname: if letter==letter.upper(): cname+=letter prefix=prefix_inherited+cname+str(numchild) + "." newline+="-----| ("+prefix[:-1]+") <"+classname+">" if child.isBroken(): newline+="<<broken>>" else: string=self.u2s(child) if (not "<" in string): newline=makeminlength(newline,99) newline+="["+string+"]" elif string[0]!="<": newline+="\t"+string if len(child.feats): if (not child.classname() in nofeatsplease): for k,v in sorted(child.feats.items()): if v==None: continue newline+="\n" for i in range(0,offset+1): newline+=" " newline+="| " newline+=self.showFeat(k,v) tree+=newline tree+=child.tree(offset+1,prefix) return tree
[ "def", "tree", "(", "self", ",", "offset", "=", "0", ",", "prefix_inherited", "=", "\"\"", ",", "nofeatsplease", "=", "[", "'Phoneme'", "]", ")", ":", "tree", "=", "\"\"", "numchild", "=", "0", "for", "child", "in", "self", ".", "children", ":", "if"...
Print a tree-structure of this object's phonological representation.
[ "Print", "a", "tree", "-", "structure", "of", "this", "object", "s", "phonological", "representation", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1212-L1278
25,583
quadrismegistus/prosodic
prosodic/entity.py
entity.search
def search(self, searchTerm): """Returns objects matching the query.""" if type(searchTerm)==type(''): searchTerm=SearchTerm(searchTerm) if searchTerm not in self.featpaths: matches = None if searchTerm.type != None and searchTerm.type != self.classname(): matches = self._searchInChildren(searchTerm) elif searchTerm.isAtomic(): matches = self._searchSingleTerm(searchTerm) else: matches = self._searchMultipleTerms(searchTerm) if matches == True: matches = [self] if matches == False: matches = [] self.featpaths[searchTerm] = matches return self.featpaths[searchTerm]
python
def search(self, searchTerm): if type(searchTerm)==type(''): searchTerm=SearchTerm(searchTerm) if searchTerm not in self.featpaths: matches = None if searchTerm.type != None and searchTerm.type != self.classname(): matches = self._searchInChildren(searchTerm) elif searchTerm.isAtomic(): matches = self._searchSingleTerm(searchTerm) else: matches = self._searchMultipleTerms(searchTerm) if matches == True: matches = [self] if matches == False: matches = [] self.featpaths[searchTerm] = matches return self.featpaths[searchTerm]
[ "def", "search", "(", "self", ",", "searchTerm", ")", ":", "if", "type", "(", "searchTerm", ")", "==", "type", "(", "''", ")", ":", "searchTerm", "=", "SearchTerm", "(", "searchTerm", ")", "if", "searchTerm", "not", "in", "self", ".", "featpaths", ":",...
Returns objects matching the query.
[ "Returns", "objects", "matching", "the", "query", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L1501-L1520
25,584
quadrismegistus/prosodic
prosodic/Text.py
Text.stats_positions
def stats_positions(self,meter=None,all_parses=False): """Produce statistics from the parser""" """Positions All feats of slots All constraint violations """ parses = self.allParses(meter=meter) if all_parses else [[parse] for parse in self.bestParses(meter=meter)] dx={} for parselist in parses: for parse in parselist: if not parse: continue slot_i=0 for pos in parse.positions: for slot in pos.slots: slot_i+=1 feat_dicts = [slot.feats, pos.constraintScores, pos.feats] for feat_dict in feat_dicts: for k,v in feat_dict.items(): dk = (slot_i,str(k)) if not dk in dx: dx[dk]=[] dx[dk]+=[v] def _writegen(): for ((slot_i,k),l) in sorted(dx.items()): l2=[] for x in l: if type(x)==bool: x=1 if x else 0 elif type(x)==type(None): x=0 elif type(x) in [str,unicode]: continue else: x=float(x) if x>1: x=1 l2+=[x] #print k, l2 #try: if not l2: continue avg=sum(l2) / float(len(l2)) count=sum(l2) chances=len(l2) #except TypeError: # continue odx={'slot_num':slot_i, 'statistic':k, 'average':avg, 'count':count, 'chances':chances, 'text':self.name} odx['header']=['slot_num', 'statistic','count','chances','average'] #print odx yield odx name=self.name.replace('.txt','') ofn=os.path.join(self.dir_results, 'stats','texts',name, name+'.positions.csv') #print ofn if not os.path.exists(os.path.split(ofn)[0]): os.makedirs(os.path.split(ofn)[0]) for dx in writegengen(ofn, _writegen): yield dx print '>> saved:',ofn
python
def stats_positions(self,meter=None,all_parses=False): """Positions All feats of slots All constraint violations """ parses = self.allParses(meter=meter) if all_parses else [[parse] for parse in self.bestParses(meter=meter)] dx={} for parselist in parses: for parse in parselist: if not parse: continue slot_i=0 for pos in parse.positions: for slot in pos.slots: slot_i+=1 feat_dicts = [slot.feats, pos.constraintScores, pos.feats] for feat_dict in feat_dicts: for k,v in feat_dict.items(): dk = (slot_i,str(k)) if not dk in dx: dx[dk]=[] dx[dk]+=[v] def _writegen(): for ((slot_i,k),l) in sorted(dx.items()): l2=[] for x in l: if type(x)==bool: x=1 if x else 0 elif type(x)==type(None): x=0 elif type(x) in [str,unicode]: continue else: x=float(x) if x>1: x=1 l2+=[x] #print k, l2 #try: if not l2: continue avg=sum(l2) / float(len(l2)) count=sum(l2) chances=len(l2) #except TypeError: # continue odx={'slot_num':slot_i, 'statistic':k, 'average':avg, 'count':count, 'chances':chances, 'text':self.name} odx['header']=['slot_num', 'statistic','count','chances','average'] #print odx yield odx name=self.name.replace('.txt','') ofn=os.path.join(self.dir_results, 'stats','texts',name, name+'.positions.csv') #print ofn if not os.path.exists(os.path.split(ofn)[0]): os.makedirs(os.path.split(ofn)[0]) for dx in writegengen(ofn, _writegen): yield dx print '>> saved:',ofn
[ "def", "stats_positions", "(", "self", ",", "meter", "=", "None", ",", "all_parses", "=", "False", ")", ":", "\"\"\"Positions\n\t\tAll feats of slots\n\t\tAll constraint violations\n\n\n\t\t\"\"\"", "parses", "=", "self", ".", "allParses", "(", "meter", "=", "meter", ...
Produce statistics from the parser
[ "Produce", "statistics", "from", "the", "parser" ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L191-L256
25,585
quadrismegistus/prosodic
prosodic/Text.py
Text.iparse
def iparse(self,meter=None,num_processes=1,arbiter='Line',line_lim=None): """Parse this text metrically, yielding it line by line.""" from Meter import Meter,genDefault,parse_ent,parse_ent_mp import multiprocessing as mp meter=self.get_meter(meter) # set internal attributes self.__parses[meter.id]=[] self.__bestparses[meter.id]=[] self.__boundParses[meter.id]=[] self.__parsed_ents[meter.id]=[] lines = self.lines() lines=lines[:line_lim] numlines = len(lines) init=self ents=self.ents(arbiter) smax=self.config.get('line_maxsylls',100) smin=self.config.get('line_minsylls',0) #print '>> # of lines to parse:',len(ents) ents = [e for e in ents if e.num_syll >= smin and e.num_syll<=smax] #print '>> # of lines to parse after applying min/max line settings:',len(ents) self.scansion_prepare(meter=meter,conscious=True) numents=len(ents) #pool=mp.Pool(1) toprint=self.config['print_to_screen'] objects = [(ent,meter,init,False) for ent in ents] if num_processes>1: print '!! MULTIPROCESSING PARSING IS NOT WORKING YET !!' pool = mp.Pool(num_processes) jobs = [pool.apply_async(parse_ent_mp,(x,)) for x in objects] for j in jobs: print j.get() yield j.get() else: now=time.time() clock_snum=0 #for ei,ent in enumerate(pool.imap(parse_ent_mp,objects)): for ei,objectx in enumerate(objects): clock_snum+=ent.num_syll if ei and not ei%100: nownow=time.time() if self.config['print_to_screen']: print '>> parsing line #',ei,'of',numents,'lines','[',round(float(clock_snum/(nownow-now)),2),'syllables/second',']' now=nownow clock_snum=0 yield parse_ent_mp(objectx) if self.config['print_to_screen']: print '>> parsing complete in:',time.time()-now,'seconds'
python
def iparse(self,meter=None,num_processes=1,arbiter='Line',line_lim=None): from Meter import Meter,genDefault,parse_ent,parse_ent_mp import multiprocessing as mp meter=self.get_meter(meter) # set internal attributes self.__parses[meter.id]=[] self.__bestparses[meter.id]=[] self.__boundParses[meter.id]=[] self.__parsed_ents[meter.id]=[] lines = self.lines() lines=lines[:line_lim] numlines = len(lines) init=self ents=self.ents(arbiter) smax=self.config.get('line_maxsylls',100) smin=self.config.get('line_minsylls',0) #print '>> # of lines to parse:',len(ents) ents = [e for e in ents if e.num_syll >= smin and e.num_syll<=smax] #print '>> # of lines to parse after applying min/max line settings:',len(ents) self.scansion_prepare(meter=meter,conscious=True) numents=len(ents) #pool=mp.Pool(1) toprint=self.config['print_to_screen'] objects = [(ent,meter,init,False) for ent in ents] if num_processes>1: print '!! MULTIPROCESSING PARSING IS NOT WORKING YET !!' pool = mp.Pool(num_processes) jobs = [pool.apply_async(parse_ent_mp,(x,)) for x in objects] for j in jobs: print j.get() yield j.get() else: now=time.time() clock_snum=0 #for ei,ent in enumerate(pool.imap(parse_ent_mp,objects)): for ei,objectx in enumerate(objects): clock_snum+=ent.num_syll if ei and not ei%100: nownow=time.time() if self.config['print_to_screen']: print '>> parsing line #',ei,'of',numents,'lines','[',round(float(clock_snum/(nownow-now)),2),'syllables/second',']' now=nownow clock_snum=0 yield parse_ent_mp(objectx) if self.config['print_to_screen']: print '>> parsing complete in:',time.time()-now,'seconds'
[ "def", "iparse", "(", "self", ",", "meter", "=", "None", ",", "num_processes", "=", "1", ",", "arbiter", "=", "'Line'", ",", "line_lim", "=", "None", ")", ":", "from", "Meter", "import", "Meter", ",", "genDefault", ",", "parse_ent", ",", "parse_ent_mp", ...
Parse this text metrically, yielding it line by line.
[ "Parse", "this", "text", "metrically", "yielding", "it", "line", "by", "line", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L468-L523
25,586
quadrismegistus/prosodic
prosodic/Text.py
Text.scansion
def scansion(self,meter=None,conscious=False): """Print out the parses and their violations in scansion format.""" meter=self.get_meter(meter) self.scansion_prepare(meter=meter,conscious=conscious) for line in self.lines(): try: line.scansion(meter=meter,conscious=conscious) except AttributeError: print "!!! Line skipped [Unknown word]:" print line print line.words() print
python
def scansion(self,meter=None,conscious=False): meter=self.get_meter(meter) self.scansion_prepare(meter=meter,conscious=conscious) for line in self.lines(): try: line.scansion(meter=meter,conscious=conscious) except AttributeError: print "!!! Line skipped [Unknown word]:" print line print line.words() print
[ "def", "scansion", "(", "self", ",", "meter", "=", "None", ",", "conscious", "=", "False", ")", ":", "meter", "=", "self", ".", "get_meter", "(", "meter", ")", "self", ".", "scansion_prepare", "(", "meter", "=", "meter", ",", "conscious", "=", "conscio...
Print out the parses and their violations in scansion format.
[ "Print", "out", "the", "parses", "and", "their", "violations", "in", "scansion", "format", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L610-L621
25,587
quadrismegistus/prosodic
prosodic/Text.py
Text.allParses
def allParses(self,meter=None,include_bounded=False,one_per_meter=True): """Return a list of lists of parses.""" meter=self.get_meter(meter) try: parses=self.__parses[meter.id] if one_per_meter: toreturn=[] for _parses in parses: sofar=set() _parses2=[] for _p in _parses: _pm=_p.str_meter() if not _pm in sofar: sofar|={_pm} if _p.isBounded and _p.boundedBy.str_meter() == _pm: pass else: _parses2+=[_p] toreturn+=[_parses2] parses=toreturn if include_bounded: boundedParses=self.boundParses(meter) return [bp+boundp for bp,boundp in zip(toreturn,boundedParses)] else: return parses except (KeyError,IndexError) as e: return []
python
def allParses(self,meter=None,include_bounded=False,one_per_meter=True): meter=self.get_meter(meter) try: parses=self.__parses[meter.id] if one_per_meter: toreturn=[] for _parses in parses: sofar=set() _parses2=[] for _p in _parses: _pm=_p.str_meter() if not _pm in sofar: sofar|={_pm} if _p.isBounded and _p.boundedBy.str_meter() == _pm: pass else: _parses2+=[_p] toreturn+=[_parses2] parses=toreturn if include_bounded: boundedParses=self.boundParses(meter) return [bp+boundp for bp,boundp in zip(toreturn,boundedParses)] else: return parses except (KeyError,IndexError) as e: return []
[ "def", "allParses", "(", "self", ",", "meter", "=", "None", ",", "include_bounded", "=", "False", ",", "one_per_meter", "=", "True", ")", ":", "meter", "=", "self", ".", "get_meter", "(", "meter", ")", "try", ":", "parses", "=", "self", ".", "__parses"...
Return a list of lists of parses.
[ "Return", "a", "list", "of", "lists", "of", "parses", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L628-L658
25,588
quadrismegistus/prosodic
prosodic/Text.py
Text.validlines
def validlines(self): """Return all lines within which Prosodic understood all words.""" return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)]
python
def validlines(self): return [ln for ln in self.lines() if (not ln.isBroken() and not ln.ignoreMe)]
[ "def", "validlines", "(", "self", ")", ":", "return", "[", "ln", "for", "ln", "in", "self", ".", "lines", "(", ")", "if", "(", "not", "ln", ".", "isBroken", "(", ")", "and", "not", "ln", ".", "ignoreMe", ")", "]" ]
Return all lines within which Prosodic understood all words.
[ "Return", "all", "lines", "within", "which", "Prosodic", "understood", "all", "words", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/Text.py#L843-L846
25,589
bartTC/django-markup
django_markup/markup.py
MarkupFormatter.choices
def choices(self): """ Returns the filter list as a tuple. Useful for model choices. """ choice_list = getattr( settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES ) return [(f, self._get_filter_title(f)) for f in choice_list]
python
def choices(self): choice_list = getattr( settings, 'MARKUP_CHOICES', DEFAULT_MARKUP_CHOICES ) return [(f, self._get_filter_title(f)) for f in choice_list]
[ "def", "choices", "(", "self", ")", ":", "choice_list", "=", "getattr", "(", "settings", ",", "'MARKUP_CHOICES'", ",", "DEFAULT_MARKUP_CHOICES", ")", "return", "[", "(", "f", ",", "self", ".", "_get_filter_title", "(", "f", ")", ")", "for", "f", "in", "c...
Returns the filter list as a tuple. Useful for model choices.
[ "Returns", "the", "filter", "list", "as", "a", "tuple", ".", "Useful", "for", "model", "choices", "." ]
1c9c0b46373cc5350282407cec82114af80b8ea3
https://github.com/bartTC/django-markup/blob/1c9c0b46373cc5350282407cec82114af80b8ea3/django_markup/markup.py#L38-L45
25,590
bartTC/django-markup
django_markup/markup.py
MarkupFormatter.unregister
def unregister(self, filter_name): """ Unregister a filter from the filter list """ if filter_name in self.filter_list: self.filter_list.pop(filter_name)
python
def unregister(self, filter_name): if filter_name in self.filter_list: self.filter_list.pop(filter_name)
[ "def", "unregister", "(", "self", ",", "filter_name", ")", ":", "if", "filter_name", "in", "self", ".", "filter_list", ":", "self", ".", "filter_list", ".", "pop", "(", "filter_name", ")" ]
Unregister a filter from the filter list
[ "Unregister", "a", "filter", "from", "the", "filter", "list" ]
1c9c0b46373cc5350282407cec82114af80b8ea3
https://github.com/bartTC/django-markup/blob/1c9c0b46373cc5350282407cec82114af80b8ea3/django_markup/markup.py#L59-L64
25,591
quadrismegistus/prosodic
metricaltree/metricaltree.py
MetricalTree.convert
def convert(cls, tree): """ Convert a tree between different subtypes of Tree. ``cls`` determines which class will be used to encode the new tree. :type tree: Tree :param tree: The tree that should be converted. :return: The new Tree. """ if isinstance(tree, Tree): children = [cls.convert(child) for child in tree] if isinstance(tree, MetricalTree): return cls(tree._cat, children, tree._dep, tree._lstress) elif isinstance(tree, DependencyTree): return cls(tree._cat, children, tree._dep) else: return cls(tree._label, children) else: return tree
python
def convert(cls, tree): if isinstance(tree, Tree): children = [cls.convert(child) for child in tree] if isinstance(tree, MetricalTree): return cls(tree._cat, children, tree._dep, tree._lstress) elif isinstance(tree, DependencyTree): return cls(tree._cat, children, tree._dep) else: return cls(tree._label, children) else: return tree
[ "def", "convert", "(", "cls", ",", "tree", ")", ":", "if", "isinstance", "(", "tree", ",", "Tree", ")", ":", "children", "=", "[", "cls", ".", "convert", "(", "child", ")", "for", "child", "in", "tree", "]", "if", "isinstance", "(", "tree", ",", ...
Convert a tree between different subtypes of Tree. ``cls`` determines which class will be used to encode the new tree. :type tree: Tree :param tree: The tree that should be converted. :return: The new Tree.
[ "Convert", "a", "tree", "between", "different", "subtypes", "of", "Tree", ".", "cls", "determines", "which", "class", "will", "be", "used", "to", "encode", "the", "new", "tree", "." ]
8af66ed9be40c922d03a0b09bc11c87d2061b618
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/metricaltree/metricaltree.py#L377-L396
25,592
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/models/runtime_raw_extension.py
RuntimeRawExtension.raw
def raw(self, raw): """Sets the raw of this RuntimeRawExtension. Raw is the underlying serialization of this object. # noqa: E501 :param raw: The raw of this RuntimeRawExtension. # noqa: E501 :type: str """ if raw is None: raise ValueError("Invalid value for `raw`, must not be `None`") # noqa: E501 if raw is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', raw): # noqa: E501 raise ValueError(r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._raw = raw
python
def raw(self, raw): if raw is None: raise ValueError("Invalid value for `raw`, must not be `None`") # noqa: E501 if raw is not None and not re.search(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', raw): # noqa: E501 raise ValueError(r"Invalid value for `raw`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`") # noqa: E501 self._raw = raw
[ "def", "raw", "(", "self", ",", "raw", ")", ":", "if", "raw", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `raw`, must not be `None`\"", ")", "# noqa: E501", "if", "raw", "is", "not", "None", "and", "not", "re", ".", "search", "(", "...
Sets the raw of this RuntimeRawExtension. Raw is the underlying serialization of this object. # noqa: E501 :param raw: The raw of this RuntimeRawExtension. # noqa: E501 :type: str
[ "Sets", "the", "raw", "of", "this", "RuntimeRawExtension", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/models/runtime_raw_extension.py#L61-L74
25,593
tomplus/kubernetes_asyncio
kubernetes_asyncio/watch/watch.py
Watch.unmarshal_event
def unmarshal_event(self, data: str, response_type): """Return the K8s response `data` in JSON format. """ js = json.loads(data) # Make a copy of the original object and save it under the # `raw_object` key because we will replace the data under `object` with # a Python native type shortly. js['raw_object'] = js['object'] # Something went wrong. A typical example would be that the user # supplied a resource version that was too old. In that case K8s would # not send a conventional ADDED/DELETED/... event but an error. Turn # this error into a Python exception to save the user the hassle. if js['type'].lower() == 'error': return js # If possible, compile the JSON response into a Python native response # type, eg `V1Namespace` or `V1Pod`,`ExtensionsV1beta1Deployment`, ... if response_type is not None: js['object'] = self._api_client.deserialize( response=SimpleNamespace(data=json.dumps(js['raw_object'])), response_type=response_type ) # decode and save resource_version to continue watching if hasattr(js['object'], 'metadata'): self.resource_version = js['object'].metadata.resource_version # For custom objects that we don't have model defined, json # deserialization results in dictionary elif (isinstance(js['object'], dict) and 'metadata' in js['object'] and 'resourceVersion' in js['object']['metadata']): self.resource_version = js['object']['metadata']['resourceVersion'] return js
python
def unmarshal_event(self, data: str, response_type): js = json.loads(data) # Make a copy of the original object and save it under the # `raw_object` key because we will replace the data under `object` with # a Python native type shortly. js['raw_object'] = js['object'] # Something went wrong. A typical example would be that the user # supplied a resource version that was too old. In that case K8s would # not send a conventional ADDED/DELETED/... event but an error. Turn # this error into a Python exception to save the user the hassle. if js['type'].lower() == 'error': return js # If possible, compile the JSON response into a Python native response # type, eg `V1Namespace` or `V1Pod`,`ExtensionsV1beta1Deployment`, ... if response_type is not None: js['object'] = self._api_client.deserialize( response=SimpleNamespace(data=json.dumps(js['raw_object'])), response_type=response_type ) # decode and save resource_version to continue watching if hasattr(js['object'], 'metadata'): self.resource_version = js['object'].metadata.resource_version # For custom objects that we don't have model defined, json # deserialization results in dictionary elif (isinstance(js['object'], dict) and 'metadata' in js['object'] and 'resourceVersion' in js['object']['metadata']): self.resource_version = js['object']['metadata']['resourceVersion'] return js
[ "def", "unmarshal_event", "(", "self", ",", "data", ":", "str", ",", "response_type", ")", ":", "js", "=", "json", ".", "loads", "(", "data", ")", "# Make a copy of the original object and save it under the", "# `raw_object` key because we will replace the data under `objec...
Return the K8s response `data` in JSON format.
[ "Return", "the", "K8s", "response", "data", "in", "JSON", "format", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/watch/watch.py#L67-L105
25,594
tomplus/kubernetes_asyncio
kubernetes_asyncio/watch/watch.py
Watch.stream
def stream(self, func, *args, **kwargs): """Watch an API resource and stream the result back via a generator. :param func: The API function pointer. Any parameter to the function can be passed after this parameter. :return: Event object with these keys: 'type': The type of event such as "ADDED", "DELETED", etc. 'raw_object': a dict representing the watched object. 'object': A model representation of raw_object. The name of model will be determined based on the func's doc string. If it cannot be determined, 'object' value will be the same as 'raw_object'. Example: v1 = kubernetes_asyncio.client.CoreV1Api() watch = kubernetes_asyncio.watch.Watch() async for e in watch.stream(v1.list_namespace, timeout_seconds=10): type = e['type'] object = e['object'] # object is one of type return_type raw_object = e['raw_object'] # raw_object is a dict ... if should_stop: watch.stop() """ self.close() self._stop = False self.return_type = self.get_return_type(func) kwargs['watch'] = True kwargs['_preload_content'] = False self.func = partial(func, *args, **kwargs) return self
python
def stream(self, func, *args, **kwargs): self.close() self._stop = False self.return_type = self.get_return_type(func) kwargs['watch'] = True kwargs['_preload_content'] = False self.func = partial(func, *args, **kwargs) return self
[ "def", "stream", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "close", "(", ")", "self", ".", "_stop", "=", "False", "self", ".", "return_type", "=", "self", ".", "get_return_type", "(", "func", ")", ...
Watch an API resource and stream the result back via a generator. :param func: The API function pointer. Any parameter to the function can be passed after this parameter. :return: Event object with these keys: 'type': The type of event such as "ADDED", "DELETED", etc. 'raw_object': a dict representing the watched object. 'object': A model representation of raw_object. The name of model will be determined based on the func's doc string. If it cannot be determined, 'object' value will be the same as 'raw_object'. Example: v1 = kubernetes_asyncio.client.CoreV1Api() watch = kubernetes_asyncio.watch.Watch() async for e in watch.stream(v1.list_namespace, timeout_seconds=10): type = e['type'] object = e['object'] # object is one of type return_type raw_object = e['raw_object'] # raw_object is a dict ... if should_stop: watch.stop()
[ "Watch", "an", "API", "resource", "and", "stream", "the", "result", "back", "via", "a", "generator", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/watch/watch.py#L152-L185
25,595
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/rest.py
RESTResponse.getheader
def getheader(self, name, default=None): """Returns a given response header.""" return self.aiohttp_response.headers.get(name, default)
python
def getheader(self, name, default=None): return self.aiohttp_response.headers.get(name, default)
[ "def", "getheader", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "return", "self", ".", "aiohttp_response", ".", "headers", ".", "get", "(", "name", ",", "default", ")" ]
Returns a given response header.
[ "Returns", "a", "given", "response", "header", "." ]
f9ab15317ec921409714c7afef11aeb0f579985d
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/rest.py#L40-L42
25,596
swistakm/graceful
src/graceful/authorization.py
authentication_required
def authentication_required(req, resp, resource, uri_kwargs): """Ensure that user is authenticated otherwise return ``401 Unauthorized``. If request fails to authenticate this authorization hook will also include list of ``WWW-Athenticate`` challenges. Args: req (falcon.Request): the request object. resp (falcon.Response): the response object. resource (object): the resource object. uri_kwargs (dict): keyword arguments from the URI template. .. versionadded:: 0.4.0 """ if 'user' not in req.context: args = ["Unauthorized", "This resource requires authentication"] # compat: falcon >= 1.0.0 requires the list of challenges if FALCON_VERSION >= (1, 0, 0): args.append(req.context.get('challenges', [])) raise HTTPUnauthorized(*args)
python
def authentication_required(req, resp, resource, uri_kwargs): if 'user' not in req.context: args = ["Unauthorized", "This resource requires authentication"] # compat: falcon >= 1.0.0 requires the list of challenges if FALCON_VERSION >= (1, 0, 0): args.append(req.context.get('challenges', [])) raise HTTPUnauthorized(*args)
[ "def", "authentication_required", "(", "req", ",", "resp", ",", "resource", ",", "uri_kwargs", ")", ":", "if", "'user'", "not", "in", "req", ".", "context", ":", "args", "=", "[", "\"Unauthorized\"", ",", "\"This resource requires authentication\"", "]", "# comp...
Ensure that user is authenticated otherwise return ``401 Unauthorized``. If request fails to authenticate this authorization hook will also include list of ``WWW-Athenticate`` challenges. Args: req (falcon.Request): the request object. resp (falcon.Response): the response object. resource (object): the resource object. uri_kwargs (dict): keyword arguments from the URI template. .. versionadded:: 0.4.0
[ "Ensure", "that", "user", "is", "authenticated", "otherwise", "return", "401", "Unauthorized", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/authorization.py#L22-L43
25,597
swistakm/graceful
src/graceful/fields.py
BaseField.describe
def describe(self, **kwargs): """ Describe this field instance for purpose of self-documentation. Args: kwargs (dict): dictionary of additional description items for extending default description Returns: dict: dictionary of description items Suggested way for overriding description fields or extending it with additional items is calling super class method with new/overriden fields passed as keyword arguments like following: .. code-block:: python class DummyField(BaseField): def description(self, **kwargs): super().describe(is_dummy=True, **kwargs) """ description = { 'label': self.label, 'details': inspect.cleandoc(self.details), 'type': "list of {}".format(self.type) if self.many else self.type, 'spec': self.spec, 'read_only': self.read_only, 'write_only': self.write_only, 'allow_null': self.allow_null, } description.update(kwargs) return description
python
def describe(self, **kwargs): description = { 'label': self.label, 'details': inspect.cleandoc(self.details), 'type': "list of {}".format(self.type) if self.many else self.type, 'spec': self.spec, 'read_only': self.read_only, 'write_only': self.write_only, 'allow_null': self.allow_null, } description.update(kwargs) return description
[ "def", "describe", "(", "self", ",", "*", "*", "kwargs", ")", ":", "description", "=", "{", "'label'", ":", "self", ".", "label", ",", "'details'", ":", "inspect", ".", "cleandoc", "(", "self", ".", "details", ")", ",", "'type'", ":", "\"list of {}\"",...
Describe this field instance for purpose of self-documentation. Args: kwargs (dict): dictionary of additional description items for extending default description Returns: dict: dictionary of description items Suggested way for overriding description fields or extending it with additional items is calling super class method with new/overriden fields passed as keyword arguments like following: .. code-block:: python class DummyField(BaseField): def description(self, **kwargs): super().describe(is_dummy=True, **kwargs)
[ "Describe", "this", "field", "instance", "for", "purpose", "of", "self", "-", "documentation", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/fields.py#L134-L166
25,598
swistakm/graceful
src/graceful/fields.py
BoolField.from_representation
def from_representation(self, data): """Convert representation value to ``bool`` if it has expected form.""" if data in self._TRUE_VALUES: return True elif data in self._FALSE_VALUES: return False else: raise ValueError( "{type} type value must be one of {values}".format( type=self.type, values=self._TRUE_VALUES.union(self._FALSE_VALUES) ) )
python
def from_representation(self, data): if data in self._TRUE_VALUES: return True elif data in self._FALSE_VALUES: return False else: raise ValueError( "{type} type value must be one of {values}".format( type=self.type, values=self._TRUE_VALUES.union(self._FALSE_VALUES) ) )
[ "def", "from_representation", "(", "self", ",", "data", ")", ":", "if", "data", "in", "self", ".", "_TRUE_VALUES", ":", "return", "True", "elif", "data", "in", "self", ".", "_FALSE_VALUES", ":", "return", "False", "else", ":", "raise", "ValueError", "(", ...
Convert representation value to ``bool`` if it has expected form.
[ "Convert", "representation", "value", "to", "bool", "if", "it", "has", "expected", "form", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/fields.py#L280-L292
25,599
swistakm/graceful
src/graceful/serializers.py
MetaSerializer._get_fields
def _get_fields(mcs, bases, namespace): """Create fields dictionary to be used in resource class namespace. Pop all field objects from attributes dict (namespace) and store them under _field_storage_key atrribute. Also collect all fields from base classes in order that ensures fields can be overriden. Args: bases: all base classes of created serializer class namespace (dict): namespace as dictionary of attributes """ fields = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseField) ] for base in reversed(bases): if hasattr(base, mcs._fields_storage_key): fields = list( getattr(base, mcs._fields_storage_key).items() ) + fields return OrderedDict(fields)
python
def _get_fields(mcs, bases, namespace): fields = [ (name, namespace.pop(name)) for name, attribute in list(namespace.items()) if isinstance(attribute, BaseField) ] for base in reversed(bases): if hasattr(base, mcs._fields_storage_key): fields = list( getattr(base, mcs._fields_storage_key).items() ) + fields return OrderedDict(fields)
[ "def", "_get_fields", "(", "mcs", ",", "bases", ",", "namespace", ")", ":", "fields", "=", "[", "(", "name", ",", "namespace", ".", "pop", "(", "name", ")", ")", "for", "name", ",", "attribute", "in", "list", "(", "namespace", ".", "items", "(", ")...
Create fields dictionary to be used in resource class namespace. Pop all field objects from attributes dict (namespace) and store them under _field_storage_key atrribute. Also collect all fields from base classes in order that ensures fields can be overriden. Args: bases: all base classes of created serializer class namespace (dict): namespace as dictionary of attributes
[ "Create", "fields", "dictionary", "to", "be", "used", "in", "resource", "class", "namespace", "." ]
d4678cb6349a5c843a5e58002fc80140821609e4
https://github.com/swistakm/graceful/blob/d4678cb6349a5c843a5e58002fc80140821609e4/src/graceful/serializers.py#L41-L66