repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
twisted/mantissa
xmantissa/people.py
PersonPluginView.getPluginWidget
def getPluginWidget(self, pluginName): """ Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement} """ # this will always pick the first plugin with pluginName if there is # more than one. don't do that. for plugin in self.plugins: if _organizerPluginName(plugin) == pluginName: view = self._toLiveElement( plugin.personalize(self.person)) view.setFragmentParent(self) return view
python
def getPluginWidget(self, pluginName): """ Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement} """ # this will always pick the first plugin with pluginName if there is # more than one. don't do that. for plugin in self.plugins: if _organizerPluginName(plugin) == pluginName: view = self._toLiveElement( plugin.personalize(self.person)) view.setFragmentParent(self) return view
[ "def", "getPluginWidget", "(", "self", ",", "pluginName", ")", ":", "# this will always pick the first plugin with pluginName if there is", "# more than one. don't do that.", "for", "plugin", "in", "self", ".", "plugins", ":", "if", "_organizerPluginName", "(", "plugin", "...
Return the named plugin's view. @type pluginName: C{unicode} @param pluginName: The name of the plugin. @rtype: L{LiveElement}
[ "Return", "the", "named", "plugin", "s", "view", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1539-L1555
twisted/mantissa
xmantissa/people.py
OrganizerFragment.beforeRender
def beforeRender(self, ctx): """ Implement this hook to initialize the L{initialPerson} and L{initialState} slots with information from the request url's query args. """ # see the comment in Organizer.urlForViewState which suggests an # alternate implementation of this kind of functionality. request = inevow.IRequest(ctx) if not set(['initial-person', 'initial-state']).issubset( # <= set(request.args)): return initialPersonName = request.args['initial-person'][0].decode('utf-8') initialPerson = self.store.findFirst( Person, Person.name == initialPersonName) if initialPerson is None: return initialState = request.args['initial-state'][0].decode('utf-8') if initialState not in ORGANIZER_VIEW_STATES.ALL_STATES: return self.initialPerson = initialPerson self.initialState = initialState
python
def beforeRender(self, ctx): """ Implement this hook to initialize the L{initialPerson} and L{initialState} slots with information from the request url's query args. """ # see the comment in Organizer.urlForViewState which suggests an # alternate implementation of this kind of functionality. request = inevow.IRequest(ctx) if not set(['initial-person', 'initial-state']).issubset( # <= set(request.args)): return initialPersonName = request.args['initial-person'][0].decode('utf-8') initialPerson = self.store.findFirst( Person, Person.name == initialPersonName) if initialPerson is None: return initialState = request.args['initial-state'][0].decode('utf-8') if initialState not in ORGANIZER_VIEW_STATES.ALL_STATES: return self.initialPerson = initialPerson self.initialState = initialState
[ "def", "beforeRender", "(", "self", ",", "ctx", ")", ":", "# see the comment in Organizer.urlForViewState which suggests an", "# alternate implementation of this kind of functionality.", "request", "=", "inevow", ".", "IRequest", "(", "ctx", ")", "if", "not", "set", "(", ...
Implement this hook to initialize the L{initialPerson} and L{initialState} slots with information from the request url's query args.
[ "Implement", "this", "hook", "to", "initialize", "the", "L", "{", "initialPerson", "}", "and", "L", "{", "initialState", "}", "slots", "with", "information", "from", "the", "request", "url", "s", "query", "args", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1601-L1622
twisted/mantissa
xmantissa/people.py
OrganizerFragment.getInitialArguments
def getInitialArguments(self): """ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. """ initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.initialState) return initialArguments
python
def getInitialArguments(self): """ Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set. """ initialArguments = (self.organizer.storeOwnerPerson.name,) if self.initialPerson is not None: initialArguments += (self.initialPerson.name, self.initialState) return initialArguments
[ "def", "getInitialArguments", "(", "self", ")", ":", "initialArguments", "=", "(", "self", ".", "organizer", ".", "storeOwnerPerson", ".", "name", ",", ")", "if", "self", ".", "initialPerson", "is", "not", "None", ":", "initialArguments", "+=", "(", "self", ...
Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of L{initialPerson} and the value of L{initialState}, if they are set.
[ "Include", "L", "{", "organizer", "}", "s", "C", "{", "storeOwnerPerson", "}", "s", "name", "and", "the", "name", "of", "L", "{", "initialPerson", "}", "and", "the", "value", "of", "L", "{", "initialState", "}", "if", "they", "are", "set", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1625-L1633
twisted/mantissa
xmantissa/people.py
OrganizerFragment.getAddPerson
def getAddPerson(self): """ Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}. """ fragment = AddPersonFragment(self.organizer) fragment.setFragmentParent(self) return fragment
python
def getAddPerson(self): """ Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}. """ fragment = AddPersonFragment(self.organizer) fragment.setFragmentParent(self) return fragment
[ "def", "getAddPerson", "(", "self", ")", ":", "fragment", "=", "AddPersonFragment", "(", "self", ".", "organizer", ")", "fragment", ".", "setFragmentParent", "(", "self", ")", "return", "fragment" ]
Return an L{AddPersonFragment} which is a child of this fragment and which will add a person to C{self.organizer}.
[ "Return", "an", "L", "{", "AddPersonFragment", "}", "which", "is", "a", "child", "of", "this", "fragment", "and", "which", "will", "add", "a", "person", "to", "C", "{", "self", ".", "organizer", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1636-L1643
twisted/mantissa
xmantissa/people.py
OrganizerFragment.getImportPeople
def getImportPeople(self): """ Return an L{ImportPeopleWidget} which is a child of this fragment and which will add people to C{self.organizer}. """ fragment = ImportPeopleWidget(self.organizer) fragment.setFragmentParent(self) return fragment
python
def getImportPeople(self): """ Return an L{ImportPeopleWidget} which is a child of this fragment and which will add people to C{self.organizer}. """ fragment = ImportPeopleWidget(self.organizer) fragment.setFragmentParent(self) return fragment
[ "def", "getImportPeople", "(", "self", ")", ":", "fragment", "=", "ImportPeopleWidget", "(", "self", ".", "organizer", ")", "fragment", ".", "setFragmentParent", "(", "self", ")", "return", "fragment" ]
Return an L{ImportPeopleWidget} which is a child of this fragment and which will add people to C{self.organizer}.
[ "Return", "an", "L", "{", "ImportPeopleWidget", "}", "which", "is", "a", "child", "of", "this", "fragment", "and", "which", "will", "add", "people", "to", "C", "{", "self", ".", "organizer", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1647-L1654
twisted/mantissa
xmantissa/people.py
OrganizerFragment.getEditPerson
def getEditPerson(self, name): """ Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView} """ view = EditPersonView(self.organizer.personByName(name)) view.setFragmentParent(self) return view
python
def getEditPerson(self, name): """ Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView} """ view = EditPersonView(self.organizer.personByName(name)) view.setFragmentParent(self) return view
[ "def", "getEditPerson", "(", "self", ",", "name", ")", ":", "view", "=", "EditPersonView", "(", "self", ".", "organizer", ".", "personByName", "(", "name", ")", ")", "view", ".", "setFragmentParent", "(", "self", ")", "return", "view" ]
Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView}
[ "Get", "an", "L", "{", "EditPersonView", "}", "for", "editing", "the", "person", "named", "C", "{", "name", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1658-L1669
twisted/mantissa
xmantissa/people.py
OrganizerFragment.deletePerson
def deletePerson(self, name): """ Delete the person named C{name} @param name: A person name. @type name: C{unicode} """ self.organizer.deletePerson(self.organizer.personByName(name))
python
def deletePerson(self, name): """ Delete the person named C{name} @param name: A person name. @type name: C{unicode} """ self.organizer.deletePerson(self.organizer.personByName(name))
[ "def", "deletePerson", "(", "self", ",", "name", ")", ":", "self", ".", "organizer", ".", "deletePerson", "(", "self", ".", "organizer", ".", "personByName", "(", "name", ")", ")" ]
Delete the person named C{name} @param name: A person name. @type name: C{unicode}
[ "Delete", "the", "person", "named", "C", "{", "name", "}" ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1673-L1680
twisted/mantissa
xmantissa/people.py
OrganizerFragment.peopleTable
def peopleTable(self, request, tag): """ Return a L{PersonScrollingFragment} which will display the L{Person} items in the wrapped organizer. """ f = PersonScrollingFragment( self.organizer, None, Person.name, self.wt) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) return f
python
def peopleTable(self, request, tag): """ Return a L{PersonScrollingFragment} which will display the L{Person} items in the wrapped organizer. """ f = PersonScrollingFragment( self.organizer, None, Person.name, self.wt) f.setFragmentParent(self) f.docFactory = webtheme.getLoader(f.fragmentName) return f
[ "def", "peopleTable", "(", "self", ",", "request", ",", "tag", ")", ":", "f", "=", "PersonScrollingFragment", "(", "self", ".", "organizer", ",", "None", ",", "Person", ".", "name", ",", "self", ".", "wt", ")", "f", ".", "setFragmentParent", "(", "self...
Return a L{PersonScrollingFragment} which will display the L{Person} items in the wrapped organizer.
[ "Return", "a", "L", "{", "PersonScrollingFragment", "}", "which", "will", "display", "the", "L", "{", "Person", "}", "items", "in", "the", "wrapped", "organizer", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1684-L1693
twisted/mantissa
xmantissa/people.py
OrganizerFragment.peopleFilters
def peopleFilters(self, request, tag): """ Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern. """ filters = iter(self.organizer.getPeopleFilters()) # at some point we might actually want to look at what filter is # yielded first, and filter the person list accordingly. we're just # going to assume it's the "All" filter, and leave the person list # untouched for now. yield tag.onePattern('selected-filter').fillSlots( 'name', filters.next().filterName) pattern = tag.patternGenerator('filter') for filter in filters: yield pattern.fillSlots('name', filter.filterName)
python
def peopleFilters(self, request, tag): """ Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern. """ filters = iter(self.organizer.getPeopleFilters()) # at some point we might actually want to look at what filter is # yielded first, and filter the person list accordingly. we're just # going to assume it's the "All" filter, and leave the person list # untouched for now. yield tag.onePattern('selected-filter').fillSlots( 'name', filters.next().filterName) pattern = tag.patternGenerator('filter') for filter in filters: yield pattern.fillSlots('name', filter.filterName)
[ "def", "peopleFilters", "(", "self", ",", "request", ",", "tag", ")", ":", "filters", "=", "iter", "(", "self", ".", "organizer", ".", "getPeopleFilters", "(", ")", ")", "# at some point we might actually want to look at what filter is", "# yielded first, and filter the...
Return an instance of C{tag}'s I{filter} pattern for each filter we get from L{Organizer.getPeopleFilters}, filling the I{name} slot with the filter's name. The first filter will be rendered using the I{selected-filter} pattern.
[ "Return", "an", "instance", "of", "C", "{", "tag", "}", "s", "I", "{", "filter", "}", "pattern", "for", "each", "filter", "we", "get", "from", "L", "{", "Organizer", ".", "getPeopleFilters", "}", "filling", "the", "I", "{", "name", "}", "slot", "with...
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1697-L1713
twisted/mantissa
xmantissa/people.py
OrganizerFragment.getPersonPluginWidget
def getPersonPluginWidget(self, name): """ Return the L{PersonPluginView} for the named person. @type name: C{unicode} @param name: A value which corresponds to the I{name} attribute of an extant L{Person}. @rtype: L{PersonPluginView} """ fragment = PersonPluginView( self.organizer.getOrganizerPlugins(), self.organizer.personByName(name)) fragment.setFragmentParent(self) return fragment
python
def getPersonPluginWidget(self, name): """ Return the L{PersonPluginView} for the named person. @type name: C{unicode} @param name: A value which corresponds to the I{name} attribute of an extant L{Person}. @rtype: L{PersonPluginView} """ fragment = PersonPluginView( self.organizer.getOrganizerPlugins(), self.organizer.personByName(name)) fragment.setFragmentParent(self) return fragment
[ "def", "getPersonPluginWidget", "(", "self", ",", "name", ")", ":", "fragment", "=", "PersonPluginView", "(", "self", ".", "organizer", ".", "getOrganizerPlugins", "(", ")", ",", "self", ".", "organizer", ".", "personByName", "(", "name", ")", ")", "fragment...
Return the L{PersonPluginView} for the named person. @type name: C{unicode} @param name: A value which corresponds to the I{name} attribute of an extant L{Person}. @rtype: L{PersonPluginView}
[ "Return", "the", "L", "{", "PersonPluginView", "}", "for", "the", "named", "person", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1717-L1731
twisted/mantissa
xmantissa/people.py
EditPersonView.editContactItems
def editContactItems(self, nickname, **edits): """ Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: mapping from contact type identifiers to ListChanges instances. """ submissions = [] for paramName, submission in edits.iteritems(): contactType = self.contactTypes[paramName] submissions.append((contactType, submission)) self.person.store.transact( self.organizer.editPerson, self.person, nickname, submissions)
python
def editContactItems(self, nickname, **edits): """ Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: mapping from contact type identifiers to ListChanges instances. """ submissions = [] for paramName, submission in edits.iteritems(): contactType = self.contactTypes[paramName] submissions.append((contactType, submission)) self.person.store.transact( self.organizer.editPerson, self.person, nickname, submissions)
[ "def", "editContactItems", "(", "self", ",", "nickname", ",", "*", "*", "edits", ")", ":", "submissions", "=", "[", "]", "for", "paramName", ",", "submission", "in", "edits", ".", "iteritems", "(", ")", ":", "contactType", "=", "self", ".", "contactTypes...
Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: mapping from contact type identifiers to ListChanges instances.
[ "Update", "the", "information", "on", "the", "contact", "items", "associated", "with", "the", "wrapped", "L", "{", "Person", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1759-L1777
twisted/mantissa
xmantissa/people.py
EditPersonView.makeEditorialLiveForms
def makeEditorialLiveForms(self): """ Make some L{liveform.LiveForm} instances for editing the contact information of the wrapped L{Person}. """ parameters = [ liveform.Parameter( 'nickname', liveform.TEXT_INPUT, _normalizeWhitespace, 'Name', default=self.person.name)] separateForms = [] for contactType in self.organizer.getContactTypes(): if getattr(contactType, 'getEditFormForPerson', None): editForm = contactType.getEditFormForPerson(self.person) if editForm is not None: editForm.setFragmentParent(self) separateForms.append(editForm) continue param = self.organizer.toContactEditorialParameter( contactType, self.person) parameters.append(param) self.contactTypes[param.name] = contactType form = liveform.LiveForm( self.editContactItems, parameters, u'Save') form.compact() form.jsClass = u'Mantissa.People.EditPersonForm' form.setFragmentParent(self) return [form] + separateForms
python
def makeEditorialLiveForms(self): """ Make some L{liveform.LiveForm} instances for editing the contact information of the wrapped L{Person}. """ parameters = [ liveform.Parameter( 'nickname', liveform.TEXT_INPUT, _normalizeWhitespace, 'Name', default=self.person.name)] separateForms = [] for contactType in self.organizer.getContactTypes(): if getattr(contactType, 'getEditFormForPerson', None): editForm = contactType.getEditFormForPerson(self.person) if editForm is not None: editForm.setFragmentParent(self) separateForms.append(editForm) continue param = self.organizer.toContactEditorialParameter( contactType, self.person) parameters.append(param) self.contactTypes[param.name] = contactType form = liveform.LiveForm( self.editContactItems, parameters, u'Save') form.compact() form.jsClass = u'Mantissa.People.EditPersonForm' form.setFragmentParent(self) return [form] + separateForms
[ "def", "makeEditorialLiveForms", "(", "self", ")", ":", "parameters", "=", "[", "liveform", ".", "Parameter", "(", "'nickname'", ",", "liveform", ".", "TEXT_INPUT", ",", "_normalizeWhitespace", ",", "'Name'", ",", "default", "=", "self", ".", "person", ".", ...
Make some L{liveform.LiveForm} instances for editing the contact information of the wrapped L{Person}.
[ "Make", "some", "L", "{", "liveform", ".", "LiveForm", "}", "instances", "for", "editing", "the", "contact", "information", "of", "the", "wrapped", "L", "{", "Person", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1780-L1807
twisted/mantissa
xmantissa/people.py
PhoneNumberContactType.getParameters
def getParameters(self, phoneNumber): """ Return a C{list} of two liveform parameters, one for editing C{phoneNumber}'s I{number} attribute, and one for editing its I{label} attribute. @type phoneNumber: L{PhoneNumber} or C{NoneType} @param phoneNumber: If not C{None}, an existing contact item from which to get the parameter's default values. @rtype: C{list} """ defaultNumber = u'' defaultLabel = PhoneNumber.LABELS.HOME if phoneNumber is not None: defaultNumber = phoneNumber.number defaultLabel = phoneNumber.label labelChoiceParameter = liveform.ChoiceParameter( 'label', [liveform.Option(label, label, label == defaultLabel) for label in PhoneNumber.LABELS.ALL_LABELS], 'Number Type') return [ labelChoiceParameter, liveform.Parameter( 'number', liveform.TEXT_INPUT, unicode, 'Phone Number', default=defaultNumber)]
python
def getParameters(self, phoneNumber): """ Return a C{list} of two liveform parameters, one for editing C{phoneNumber}'s I{number} attribute, and one for editing its I{label} attribute. @type phoneNumber: L{PhoneNumber} or C{NoneType} @param phoneNumber: If not C{None}, an existing contact item from which to get the parameter's default values. @rtype: C{list} """ defaultNumber = u'' defaultLabel = PhoneNumber.LABELS.HOME if phoneNumber is not None: defaultNumber = phoneNumber.number defaultLabel = phoneNumber.label labelChoiceParameter = liveform.ChoiceParameter( 'label', [liveform.Option(label, label, label == defaultLabel) for label in PhoneNumber.LABELS.ALL_LABELS], 'Number Type') return [ labelChoiceParameter, liveform.Parameter( 'number', liveform.TEXT_INPUT, unicode, 'Phone Number', default=defaultNumber)]
[ "def", "getParameters", "(", "self", ",", "phoneNumber", ")", ":", "defaultNumber", "=", "u''", "defaultLabel", "=", "PhoneNumber", ".", "LABELS", ".", "HOME", "if", "phoneNumber", "is", "not", "None", ":", "defaultNumber", "=", "phoneNumber", ".", "number", ...
Return a C{list} of two liveform parameters, one for editing C{phoneNumber}'s I{number} attribute, and one for editing its I{label} attribute. @type phoneNumber: L{PhoneNumber} or C{NoneType} @param phoneNumber: If not C{None}, an existing contact item from which to get the parameter's default values. @rtype: C{list}
[ "Return", "a", "C", "{", "list", "}", "of", "two", "liveform", "parameters", "one", "for", "editing", "C", "{", "phoneNumber", "}", "s", "I", "{", "number", "}", "attribute", "and", "one", "for", "editing", "its", "I", "{", "label", "}", "attribute", ...
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L1977-L2006
twisted/mantissa
xmantissa/people.py
PhoneNumberContactType.createContactItem
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the new L{PhoneNumber} item. If C{''}, no item will be created. @type number: C{unicode} @rtype: L{PhoneNumber} or C{NoneType} """ if number: return PhoneNumber( store=person.store, person=person, label=label, number=number)
python
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the new L{PhoneNumber} item. If C{''}, no item will be created. @type number: C{unicode} @rtype: L{PhoneNumber} or C{NoneType} """ if number: return PhoneNumber( store=person.store, person=person, label=label, number=number)
[ "def", "createContactItem", "(", "self", ",", "person", ",", "label", ",", "number", ")", ":", "if", "number", ":", "return", "PhoneNumber", "(", "store", "=", "person", ".", "store", ",", "person", "=", "person", ",", "label", "=", "label", ",", "numb...
Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the new L{PhoneNumber} item. If C{''}, no item will be created. @type number: C{unicode} @rtype: L{PhoneNumber} or C{NoneType}
[ "Create", "a", "L", "{", "PhoneNumber", "}", "item", "for", "C", "{", "number", "}", "associated", "with", "C", "{", "person", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2016-L2034
twisted/mantissa
xmantissa/people.py
PhoneNumberContactType.editContactItem
def editContactItem(self, contact, label, number): """ Change the I{number} attribute of C{contact} to C{number}, and the I{label} attribute to C{label}. @type contact: L{PhoneNumber} @type label: C{unicode} @type number: C{unicode} @return: C{None} """ contact.label = label contact.number = number
python
def editContactItem(self, contact, label, number): """ Change the I{number} attribute of C{contact} to C{number}, and the I{label} attribute to C{label}. @type contact: L{PhoneNumber} @type label: C{unicode} @type number: C{unicode} @return: C{None} """ contact.label = label contact.number = number
[ "def", "editContactItem", "(", "self", ",", "contact", ",", "label", ",", "number", ")", ":", "contact", ".", "label", "=", "label", "contact", ".", "number", "=", "number" ]
Change the I{number} attribute of C{contact} to C{number}, and the I{label} attribute to C{label}. @type contact: L{PhoneNumber} @type label: C{unicode} @type number: C{unicode} @return: C{None}
[ "Change", "the", "I", "{", "number", "}", "attribute", "of", "C", "{", "contact", "}", "to", "C", "{", "number", "}", "and", "the", "I", "{", "label", "}", "attribute", "to", "C", "{", "label", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2037-L2051
twisted/mantissa
xmantissa/people.py
PhoneNumberContactType.getContactItems
def getContactItems(self, person): """ Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person} """ return person.store.query( PhoneNumber, PhoneNumber.person == person)
python
def getContactItems(self, person): """ Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person} """ return person.store.query( PhoneNumber, PhoneNumber.person == person)
[ "def", "getContactItems", "(", "self", ",", "person", ")", ":", "return", "person", ".", "store", ".", "query", "(", "PhoneNumber", ",", "PhoneNumber", ".", "person", "==", "person", ")" ]
Return an iterable of L{PhoneNumber} items that are associated with C{person}. @type person: L{Person}
[ "Return", "an", "iterable", "of", "L", "{", "PhoneNumber", "}", "items", "that", "are", "associated", "with", "C", "{", "person", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2054-L2062
twisted/mantissa
xmantissa/people.py
PostalContactType.getParameters
def getParameters(self, postalAddress): """ Return a C{list} of one L{LiveForm} parameter for editing a L{PostalAddress}. @type postalAddress: L{PostalAddress} or C{NoneType} @param postalAddress: If not C{None}, an existing contact item from which to get the postal address default value. @rtype: C{list} @return: The parameters necessary for specifying a postal address. """ address = u'' if postalAddress is not None: address = postalAddress.address return [ liveform.Parameter('address', liveform.TEXT_INPUT, unicode, 'Postal Address', default=address)]
python
def getParameters(self, postalAddress): """ Return a C{list} of one L{LiveForm} parameter for editing a L{PostalAddress}. @type postalAddress: L{PostalAddress} or C{NoneType} @param postalAddress: If not C{None}, an existing contact item from which to get the postal address default value. @rtype: C{list} @return: The parameters necessary for specifying a postal address. """ address = u'' if postalAddress is not None: address = postalAddress.address return [ liveform.Parameter('address', liveform.TEXT_INPUT, unicode, 'Postal Address', default=address)]
[ "def", "getParameters", "(", "self", ",", "postalAddress", ")", ":", "address", "=", "u''", "if", "postalAddress", "is", "not", "None", ":", "address", "=", "postalAddress", ".", "address", "return", "[", "liveform", ".", "Parameter", "(", "'address'", ",", ...
Return a C{list} of one L{LiveForm} parameter for editing a L{PostalAddress}. @type postalAddress: L{PostalAddress} or C{NoneType} @param postalAddress: If not C{None}, an existing contact item from which to get the postal address default value. @rtype: C{list} @return: The parameters necessary for specifying a postal address.
[ "Return", "a", "C", "{", "list", "}", "of", "one", "L", "{", "LiveForm", "}", "parameter", "for", "editing", "a", "L", "{", "PostalAddress", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2121-L2139
twisted/mantissa
xmantissa/people.py
PostalContactType.createContactItem
def createContactItem(self, person, address): """ Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type address: C{unicode} @param address: The value to use for the I{address} attribute of the newly created L{PostalAddress}. If C{''}, no L{PostalAddress} will be created. @rtype: L{PostalAddress} or C{NoneType} """ if address: return PostalAddress( store=person.store, person=person, address=address)
python
def createContactItem(self, person, address): """ Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type address: C{unicode} @param address: The value to use for the I{address} attribute of the newly created L{PostalAddress}. If C{''}, no L{PostalAddress} will be created. @rtype: L{PostalAddress} or C{NoneType} """ if address: return PostalAddress( store=person.store, person=person, address=address)
[ "def", "createContactItem", "(", "self", ",", "person", ",", "address", ")", ":", "if", "address", ":", "return", "PostalAddress", "(", "store", "=", "person", ".", "store", ",", "person", "=", "person", ",", "address", "=", "address", ")" ]
Create a new L{PostalAddress} associated with the given person based on the given postal address. @type person: L{Person} @param person: The person with whom to associate the new L{EmailAddress}. @type address: C{unicode} @param address: The value to use for the I{address} attribute of the newly created L{PostalAddress}. If C{''}, no L{PostalAddress} will be created. @rtype: L{PostalAddress} or C{NoneType}
[ "Create", "a", "new", "L", "{", "PostalAddress", "}", "associated", "with", "the", "given", "person", "based", "on", "the", "given", "postal", "address", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2149-L2167
twisted/mantissa
xmantissa/people.py
PostalContactType.getContactItems
def getContactItems(self, person): """ Return a C{list} of the L{PostalAddress} items associated with the given person. @type person: L{Person} """ return person.store.query(PostalAddress, PostalAddress.person == person)
python
def getContactItems(self, person): """ Return a C{list} of the L{PostalAddress} items associated with the given person. @type person: L{Person} """ return person.store.query(PostalAddress, PostalAddress.person == person)
[ "def", "getContactItems", "(", "self", ",", "person", ")", ":", "return", "person", ".", "store", ".", "query", "(", "PostalAddress", ",", "PostalAddress", ".", "person", "==", "person", ")" ]
Return a C{list} of the L{PostalAddress} items associated with the given person. @type person: L{Person}
[ "Return", "a", "C", "{", "list", "}", "of", "the", "L", "{", "PostalAddress", "}", "items", "associated", "with", "the", "given", "person", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2187-L2194
twisted/mantissa
xmantissa/people.py
NotesContactType.getParameters
def getParameters(self, notes): """ Return a C{list} of one L{LiveForm} parameter for editing a L{Notes}. @type notes: L{Notes} or C{NoneType} @param notes: If not C{None}, an existing contact item from which to get the parameter's default value. @rtype: C{list} """ defaultNotes = u'' if notes is not None: defaultNotes = notes.notes return [ liveform.Parameter('notes', liveform.TEXTAREA_INPUT, unicode, 'Notes', default=defaultNotes)]
python
def getParameters(self, notes): """ Return a C{list} of one L{LiveForm} parameter for editing a L{Notes}. @type notes: L{Notes} or C{NoneType} @param notes: If not C{None}, an existing contact item from which to get the parameter's default value. @rtype: C{list} """ defaultNotes = u'' if notes is not None: defaultNotes = notes.notes return [ liveform.Parameter('notes', liveform.TEXTAREA_INPUT, unicode, 'Notes', default=defaultNotes)]
[ "def", "getParameters", "(", "self", ",", "notes", ")", ":", "defaultNotes", "=", "u''", "if", "notes", "is", "not", "None", ":", "defaultNotes", "=", "notes", ".", "notes", "return", "[", "liveform", ".", "Parameter", "(", "'notes'", ",", "liveform", "....
Return a C{list} of one L{LiveForm} parameter for editing a L{Notes}. @type notes: L{Notes} or C{NoneType} @param notes: If not C{None}, an existing contact item from which to get the parameter's default value. @rtype: C{list}
[ "Return", "a", "C", "{", "list", "}", "of", "one", "L", "{", "LiveForm", "}", "parameter", "for", "editing", "a", "L", "{", "Notes", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2221-L2237
twisted/mantissa
xmantissa/people.py
NotesContactType.createContactItem
def createContactItem(self, person, notes): """ Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly created L{Notes}. If C{''}, no L{Notes} will be created. @rtype: L{Notes} or C{NoneType} """ if notes: return Notes( store=person.store, person=person, notes=notes)
python
def createContactItem(self, person, notes): """ Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly created L{Notes}. If C{''}, no L{Notes} will be created. @rtype: L{Notes} or C{NoneType} """ if notes: return Notes( store=person.store, person=person, notes=notes)
[ "def", "createContactItem", "(", "self", ",", "person", ",", "notes", ")", ":", "if", "notes", ":", "return", "Notes", "(", "store", "=", "person", ".", "store", ",", "person", "=", "person", ",", "notes", "=", "notes", ")" ]
Create a new L{Notes} associated with the given person based on the given string. @type person: L{Person} @param person: The person with whom to associate the new L{Notes}. @type notes: C{unicode} @param notes: The value to use for the I{notes} attribute of the newly created L{Notes}. If C{''}, no L{Notes} will be created. @rtype: L{Notes} or C{NoneType}
[ "Create", "a", "new", "L", "{", "Notes", "}", "associated", "with", "the", "given", "person", "based", "on", "the", "given", "string", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2247-L2263
twisted/mantissa
xmantissa/people.py
NotesContactType.getContactItems
def getContactItems(self, person): """ Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person} """ notes = list(person.store.query(Notes, Notes.person == person)) if not notes: return [Notes(store=person.store, person=person, notes=u'')] return notes
python
def getContactItems(self, person): """ Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person} """ notes = list(person.store.query(Notes, Notes.person == person)) if not notes: return [Notes(store=person.store, person=person, notes=u'')] return notes
[ "def", "getContactItems", "(", "self", ",", "person", ")", ":", "notes", "=", "list", "(", "person", ".", "store", ".", "query", "(", "Notes", ",", "Notes", ".", "person", "==", "person", ")", ")", "if", "not", "notes", ":", "return", "[", "Notes", ...
Return a C{list} of the L{Notes} items associated with the given person. If none exist, create one, wrap it in a list and return it. @type person: L{Person}
[ "Return", "a", "C", "{", "list", "}", "of", "the", "L", "{", "Notes", "}", "items", "associated", "with", "the", "given", "person", ".", "If", "none", "exist", "create", "one", "wrap", "it", "in", "a", "list", "and", "return", "it", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2283-L2295
twisted/mantissa
xmantissa/people.py
AddPersonFragment.render_addPersonForm
def render_addPersonForm(self, ctx, data): """ Create and return a L{liveform.LiveForm} for creating a new L{Person}. """ addPersonForm = liveform.LiveForm( self.addPerson, self._baseParameters, description='Add Person') addPersonForm.compact() addPersonForm.jsClass = u'Mantissa.People.AddPersonForm' addPersonForm.setFragmentParent(self) return addPersonForm
python
def render_addPersonForm(self, ctx, data): """ Create and return a L{liveform.LiveForm} for creating a new L{Person}. """ addPersonForm = liveform.LiveForm( self.addPerson, self._baseParameters, description='Add Person') addPersonForm.compact() addPersonForm.jsClass = u'Mantissa.People.AddPersonForm' addPersonForm.setFragmentParent(self) return addPersonForm
[ "def", "render_addPersonForm", "(", "self", ",", "ctx", ",", "data", ")", ":", "addPersonForm", "=", "liveform", ".", "LiveForm", "(", "self", ".", "addPerson", ",", "self", ".", "_baseParameters", ",", "description", "=", "'Add Person'", ")", "addPersonForm",...
Create and return a L{liveform.LiveForm} for creating a new L{Person}.
[ "Create", "and", "return", "a", "L", "{", "liveform", ".", "LiveForm", "}", "for", "creating", "a", "new", "L", "{", "Person", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2357-L2366
twisted/mantissa
xmantissa/people.py
AddPersonFragment.addPerson
def addPerson(self, nickname): """ Create a new L{Person} with the given C{nickname}. @type nickname: C{unicode} @param nickname: The value for the I{name} attribute of the created L{Person}. @raise L{liveform.InputError}: When some aspect of person creation raises a L{ValueError}. """ try: self.organizer.createPerson(nickname) except ValueError, e: raise liveform.InputError(unicode(e))
python
def addPerson(self, nickname): """ Create a new L{Person} with the given C{nickname}. @type nickname: C{unicode} @param nickname: The value for the I{name} attribute of the created L{Person}. @raise L{liveform.InputError}: When some aspect of person creation raises a L{ValueError}. """ try: self.organizer.createPerson(nickname) except ValueError, e: raise liveform.InputError(unicode(e))
[ "def", "addPerson", "(", "self", ",", "nickname", ")", ":", "try", ":", "self", ".", "organizer", ".", "createPerson", "(", "nickname", ")", "except", "ValueError", ",", "e", ":", "raise", "liveform", ".", "InputError", "(", "unicode", "(", "e", ")", "...
Create a new L{Person} with the given C{nickname}. @type nickname: C{unicode} @param nickname: The value for the I{name} attribute of the created L{Person}. @raise L{liveform.InputError}: When some aspect of person creation raises a L{ValueError}.
[ "Create", "a", "new", "L", "{", "Person", "}", "with", "the", "given", "C", "{", "nickname", "}", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2369-L2383
twisted/mantissa
xmantissa/people.py
ImportPeopleWidget._parseAddresses
def _parseAddresses(addresses): """ Extract name/address pairs from an RFC 2822 style address list. For addresses without a display name, the name defaults to the local-part for the purpose of importing. @type addresses: unicode @return: a list of C{(name, email)} tuples """ def coerce((name, email)): if len(email): if not len(name): name = email.split(u'@', 1)[0] # lame return (name, email) coerced = map(coerce, getaddresses([addresses])) return [r for r in coerced if r is not None]
python
def _parseAddresses(addresses): """ Extract name/address pairs from an RFC 2822 style address list. For addresses without a display name, the name defaults to the local-part for the purpose of importing. @type addresses: unicode @return: a list of C{(name, email)} tuples """ def coerce((name, email)): if len(email): if not len(name): name = email.split(u'@', 1)[0] # lame return (name, email) coerced = map(coerce, getaddresses([addresses])) return [r for r in coerced if r is not None]
[ "def", "_parseAddresses", "(", "addresses", ")", ":", "def", "coerce", "(", "(", "name", ",", "email", ")", ")", ":", "if", "len", "(", "email", ")", ":", "if", "not", "len", "(", "name", ")", ":", "name", "=", "email", ".", "split", "(", "u'@'",...
Extract name/address pairs from an RFC 2822 style address list. For addresses without a display name, the name defaults to the local-part for the purpose of importing. @type addresses: unicode @return: a list of C{(name, email)} tuples
[ "Extract", "name", "/", "address", "pairs", "from", "an", "RFC", "2822", "style", "address", "list", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2405-L2421
twisted/mantissa
xmantissa/people.py
ImportPeopleWidget.importPeopleForm
def importPeopleForm(self, request, tag): """ Create and return a L{liveform.LiveForm} for adding new L{Person}s. """ form = liveform.LiveForm( self.importAddresses, [liveform.Parameter('addresses', liveform.TEXTAREA_INPUT, self._parseAddresses, 'Email Addresses')], description='Import People') form.jsClass = u'Mantissa.People.ImportPeopleForm' form.compact() form.setFragmentParent(self) return form
python
def importPeopleForm(self, request, tag): """ Create and return a L{liveform.LiveForm} for adding new L{Person}s. """ form = liveform.LiveForm( self.importAddresses, [liveform.Parameter('addresses', liveform.TEXTAREA_INPUT, self._parseAddresses, 'Email Addresses')], description='Import People') form.jsClass = u'Mantissa.People.ImportPeopleForm' form.compact() form.setFragmentParent(self) return form
[ "def", "importPeopleForm", "(", "self", ",", "request", ",", "tag", ")", ":", "form", "=", "liveform", ".", "LiveForm", "(", "self", ".", "importAddresses", ",", "[", "liveform", ".", "Parameter", "(", "'addresses'", ",", "liveform", ".", "TEXTAREA_INPUT", ...
Create and return a L{liveform.LiveForm} for adding new L{Person}s.
[ "Create", "and", "return", "a", "L", "{", "liveform", ".", "LiveForm", "}", "for", "adding", "new", "L", "{", "Person", "}", "s", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2425-L2437
twisted/mantissa
xmantissa/people.py
ImportPeopleWidget.importAddresses
def importAddresses(self, addresses): """ Create new L{Person}s for the given names and email addresses. Names and emails that already exist are ignored. @param addresses: a sequence of C{(name, email)} tuples (as returned from L{_parseAddresses}) @return: the names of people actually imported """ results = [] for (name, address) in addresses: def txn(): # Skip names and addresses that already exist. if self.organizer.personByEmailAddress(address) is not None: return # XXX: Needs a better existence check. if self.store.query(Person, Person.name == name).count(): return try: person = self.organizer.createPerson(name) self.organizer.createContactItem( EmailContactType(self.store), person, dict(email=address)) except ValueError, e: # XXX: Granularity required; see #711 and #2435 raise liveform.ConfigurationError(u'%r' % (e,)) return person results.append(self.store.transact(txn)) return [p.name for p in results if p is not None]
python
def importAddresses(self, addresses): """ Create new L{Person}s for the given names and email addresses. Names and emails that already exist are ignored. @param addresses: a sequence of C{(name, email)} tuples (as returned from L{_parseAddresses}) @return: the names of people actually imported """ results = [] for (name, address) in addresses: def txn(): # Skip names and addresses that already exist. if self.organizer.personByEmailAddress(address) is not None: return # XXX: Needs a better existence check. if self.store.query(Person, Person.name == name).count(): return try: person = self.organizer.createPerson(name) self.organizer.createContactItem( EmailContactType(self.store), person, dict(email=address)) except ValueError, e: # XXX: Granularity required; see #711 and #2435 raise liveform.ConfigurationError(u'%r' % (e,)) return person results.append(self.store.transact(txn)) return [p.name for p in results if p is not None]
[ "def", "importAddresses", "(", "self", ",", "addresses", ")", ":", "results", "=", "[", "]", "for", "(", "name", ",", "address", ")", "in", "addresses", ":", "def", "txn", "(", ")", ":", "# Skip names and addresses that already exist.", "if", "self", ".", ...
Create new L{Person}s for the given names and email addresses. Names and emails that already exist are ignored. @param addresses: a sequence of C{(name, email)} tuples (as returned from L{_parseAddresses}) @return: the names of people actually imported
[ "Create", "new", "L", "{", "Person", "}", "s", "for", "the", "given", "names", "and", "email", "addresses", ".", "Names", "and", "emails", "that", "already", "exist", "are", "ignored", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2441-L2470
twisted/mantissa
xmantissa/people.py
MugshotUploadForm.renderHTTP
def renderHTTP(self, ctx): """ Extract the data from the I{uploaddata} field of the request and pass it to our callback. """ req = inevow.IRequest(ctx) if req.method == 'POST': udata = req.fields['uploaddata'] self.cbGotMugshot(udata.type.decode('ascii'), udata.file) return rend.Page.renderHTTP(self, ctx)
python
def renderHTTP(self, ctx): """ Extract the data from the I{uploaddata} field of the request and pass it to our callback. """ req = inevow.IRequest(ctx) if req.method == 'POST': udata = req.fields['uploaddata'] self.cbGotMugshot(udata.type.decode('ascii'), udata.file) return rend.Page.renderHTTP(self, ctx)
[ "def", "renderHTTP", "(", "self", ",", "ctx", ")", ":", "req", "=", "inevow", ".", "IRequest", "(", "ctx", ")", "if", "req", ".", "method", "==", "'POST'", ":", "udata", "=", "req", ".", "fields", "[", "'uploaddata'", "]", "self", ".", "cbGotMugshot"...
Extract the data from the I{uploaddata} field of the request and pass it to our callback.
[ "Extract", "the", "data", "from", "the", "I", "{", "uploaddata", "}", "field", "of", "the", "request", "and", "pass", "it", "to", "our", "callback", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2509-L2518
twisted/mantissa
xmantissa/people.py
Mugshot.fromFile
def fromFile(cls, person, inputFile, format): """ Create a L{Mugshot} item for C{person} out of the image data in C{inputFile}, or update C{person}'s existing L{Mugshot} item to reflect the new images. @param inputFile: An image of a person. @type inputFile: C{file} @param person: The person this mugshot is to be associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{unicode} (e.g. I{jpeg}) @rtype: L{Mugshot} """ body = cls.makeThumbnail(inputFile, person, format, smaller=False) inputFile.seek(0) smallerBody = cls.makeThumbnail( inputFile, person, format, smaller=True) ctype = u'image/' + format self = person.store.findUnique( cls, cls.person == person, default=None) if self is None: self = cls(store=person.store, person=person, type=ctype, body=body, smallerBody=smallerBody) else: self.body = body self.smallerBody = smallerBody self.type = ctype return self
python
def fromFile(cls, person, inputFile, format): """ Create a L{Mugshot} item for C{person} out of the image data in C{inputFile}, or update C{person}'s existing L{Mugshot} item to reflect the new images. @param inputFile: An image of a person. @type inputFile: C{file} @param person: The person this mugshot is to be associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{unicode} (e.g. I{jpeg}) @rtype: L{Mugshot} """ body = cls.makeThumbnail(inputFile, person, format, smaller=False) inputFile.seek(0) smallerBody = cls.makeThumbnail( inputFile, person, format, smaller=True) ctype = u'image/' + format self = person.store.findUnique( cls, cls.person == person, default=None) if self is None: self = cls(store=person.store, person=person, type=ctype, body=body, smallerBody=smallerBody) else: self.body = body self.smallerBody = smallerBody self.type = ctype return self
[ "def", "fromFile", "(", "cls", ",", "person", ",", "inputFile", ",", "format", ")", ":", "body", "=", "cls", ".", "makeThumbnail", "(", "inputFile", ",", "person", ",", "format", ",", "smaller", "=", "False", ")", "inputFile", ".", "seek", "(", "0", ...
Create a L{Mugshot} item for C{person} out of the image data in C{inputFile}, or update C{person}'s existing L{Mugshot} item to reflect the new images. @param inputFile: An image of a person. @type inputFile: C{file} @param person: The person this mugshot is to be associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{unicode} (e.g. I{jpeg}) @rtype: L{Mugshot}
[ "Create", "a", "L", "{", "Mugshot", "}", "item", "for", "C", "{", "person", "}", "out", "of", "the", "image", "data", "in", "C", "{", "inputFile", "}", "or", "update", "C", "{", "person", "}", "s", "existing", "L", "{", "Mugshot", "}", "item", "t...
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2557-L2593
twisted/mantissa
xmantissa/people.py
Mugshot.makeThumbnail
def makeThumbnail(cls, inputFile, person, format, smaller): """ Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{str} (e.g. I{jpeg}) @param smaller: Thumbnails are available in two sizes. if C{smaller} is C{True}, then the thumbnail will be in the smaller of the two sizes. @type smaller: C{bool} @return: path to the thumbnail. @rtype: L{twisted.python.filepath.FilePath} """ dirsegs = ['mugshots', str(person.storeID)] if smaller: dirsegs.insert(1, 'smaller') size = cls.smallerSize else: size = cls.size atomicOutputFile = person.store.newFile(*dirsegs) makeThumbnail(inputFile, atomicOutputFile, size, format) atomicOutputFile.close() return atomicOutputFile.finalpath
python
def makeThumbnail(cls, inputFile, person, format, smaller): """ Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{str} (e.g. I{jpeg}) @param smaller: Thumbnails are available in two sizes. if C{smaller} is C{True}, then the thumbnail will be in the smaller of the two sizes. @type smaller: C{bool} @return: path to the thumbnail. @rtype: L{twisted.python.filepath.FilePath} """ dirsegs = ['mugshots', str(person.storeID)] if smaller: dirsegs.insert(1, 'smaller') size = cls.smallerSize else: size = cls.size atomicOutputFile = person.store.newFile(*dirsegs) makeThumbnail(inputFile, atomicOutputFile, size, format) atomicOutputFile.close() return atomicOutputFile.finalpath
[ "def", "makeThumbnail", "(", "cls", ",", "inputFile", ",", "person", ",", "format", ",", "smaller", ")", ":", "dirsegs", "=", "[", "'mugshots'", ",", "str", "(", "person", ".", "storeID", ")", "]", "if", "smaller", ":", "dirsegs", ".", "insert", "(", ...
Make a thumbnail of a mugshot image and store it on disk. @param inputFile: The image to thumbnail. @type inputFile: C{file} @param person: The person this mugshot thumbnail is associated with. @type person: L{Person} @param format: The format of the data in C{inputFile}. @type format: C{str} (e.g. I{jpeg}) @param smaller: Thumbnails are available in two sizes. if C{smaller} is C{True}, then the thumbnail will be in the smaller of the two sizes. @type smaller: C{bool} @return: path to the thumbnail. @rtype: L{twisted.python.filepath.FilePath}
[ "Make", "a", "thumbnail", "of", "a", "mugshot", "image", "and", "store", "it", "on", "disk", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2597-L2627
twisted/mantissa
xmantissa/people.py
Mugshot.placeholderForPerson
def placeholderForPerson(cls, person): """ Make an unstored, placeholder L{Mugshot} instance for the given person. @param person: A person without a L{Mugshot}. @type person: L{Person} @rtype: L{Mugshot} """ imageDir = FilePath(__file__).parent().child( 'static').child('images') return cls( type=u'image/png', body=imageDir.child('mugshot-placeholder.png'), smallerBody=imageDir.child( 'mugshot-placeholder-smaller.png'), person=person)
python
def placeholderForPerson(cls, person): """ Make an unstored, placeholder L{Mugshot} instance for the given person. @param person: A person without a L{Mugshot}. @type person: L{Person} @rtype: L{Mugshot} """ imageDir = FilePath(__file__).parent().child( 'static').child('images') return cls( type=u'image/png', body=imageDir.child('mugshot-placeholder.png'), smallerBody=imageDir.child( 'mugshot-placeholder-smaller.png'), person=person)
[ "def", "placeholderForPerson", "(", "cls", ",", "person", ")", ":", "imageDir", "=", "FilePath", "(", "__file__", ")", ".", "parent", "(", ")", ".", "child", "(", "'static'", ")", ".", "child", "(", "'images'", ")", "return", "cls", "(", "type", "=", ...
Make an unstored, placeholder L{Mugshot} instance for the given person. @param person: A person without a L{Mugshot}. @type person: L{Person} @rtype: L{Mugshot}
[ "Make", "an", "unstored", "placeholder", "L", "{", "Mugshot", "}", "instance", "for", "the", "given", "person", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2631-L2648
rande/python-simple-ioc
ioc/extra/jinja2/di.py
Extension.post_build
def post_build(self, container_builder, container): """ Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals are functions. The tag must contain a name and a method options """ jinja = container.get('ioc.extra.jinja2') for id in container_builder.get_ids_by_tag('jinja2.filter'): definition = container_builder.get(id) for option in definition.get_tag('jinja2.filter'): if 'name' not in option: break if 'method' not in option: break jinja.filters[option['name']] = getattr(container.get(id), option['method']) for id in container_builder.get_ids_by_tag('jinja2.global'): definition = container_builder.get(id) for option in definition.get_tag('jinja2.global'): if 'name' not in option: break if 'method' not in option: break jinja.globals[option['name']] = getattr(container.get(id), option['method'])
python
def post_build(self, container_builder, container): """ Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals are functions. The tag must contain a name and a method options """ jinja = container.get('ioc.extra.jinja2') for id in container_builder.get_ids_by_tag('jinja2.filter'): definition = container_builder.get(id) for option in definition.get_tag('jinja2.filter'): if 'name' not in option: break if 'method' not in option: break jinja.filters[option['name']] = getattr(container.get(id), option['method']) for id in container_builder.get_ids_by_tag('jinja2.global'): definition = container_builder.get(id) for option in definition.get_tag('jinja2.global'): if 'name' not in option: break if 'method' not in option: break jinja.globals[option['name']] = getattr(container.get(id), option['method'])
[ "def", "post_build", "(", "self", ",", "container_builder", ",", "container", ")", ":", "jinja", "=", "container", ".", "get", "(", "'ioc.extra.jinja2'", ")", "for", "id", "in", "container_builder", ".", "get_ids_by_tag", "(", "'jinja2.filter'", ")", ":", "def...
Register filter and global in jinja environment instance IoC tags are: - jinja2.filter to register filter, the tag must contain a name and a method options - jinja2.global to add new global, here globals are functions. The tag must contain a name and a method options
[ "Register", "filter", "and", "global", "in", "jinja", "environment", "instance" ]
train
https://github.com/rande/python-simple-ioc/blob/36ddf667c1213a07a53cd4cdd708d02494e5190b/ioc/extra/jinja2/di.py#L40-L73
truemped/tornadotools
tornadotools/caching.py
cache_key
def cache_key(*args, **kwargs): """ Base method for computing the cache key with respect to the given arguments. """ key = "" for arg in args: if callable(arg): key += ":%s" % repr(arg) else: key += ":%s" % str(arg) return key
python
def cache_key(*args, **kwargs): """ Base method for computing the cache key with respect to the given arguments. """ key = "" for arg in args: if callable(arg): key += ":%s" % repr(arg) else: key += ":%s" % str(arg) return key
[ "def", "cache_key", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "key", "=", "\"\"", "for", "arg", "in", "args", ":", "if", "callable", "(", "arg", ")", ":", "key", "+=", "\":%s\"", "%", "repr", "(", "arg", ")", "else", ":", "key", "+="...
Base method for computing the cache key with respect to the given arguments.
[ "Base", "method", "for", "computing", "the", "cache", "key", "with", "respect", "to", "the", "given", "arguments", "." ]
train
https://github.com/truemped/tornadotools/blob/d22632b83810afc353fa886fbc9e265bee78653f/tornadotools/caching.py#L75-L87
mozilla-releng/signtool
signtool/signing/client.py
uploadfile
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post): """Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters. """ filehash = sha1sum(filename) files = {'filedata': open(filename, 'rb')} payload = { 'sha1': filehash, 'filename': os.path.basename(filename), 'token': token, 'nonce': nonce, } return method("%s/sign/%s" % (baseurl, format_), files=files, data=payload, verify=cert)
python
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post): """Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters. """ filehash = sha1sum(filename) files = {'filedata': open(filename, 'rb')} payload = { 'sha1': filehash, 'filename': os.path.basename(filename), 'token': token, 'nonce': nonce, } return method("%s/sign/%s" % (baseurl, format_), files=files, data=payload, verify=cert)
[ "def", "uploadfile", "(", "baseurl", ",", "filename", ",", "format_", ",", "token", ",", "nonce", ",", "cert", ",", "method", "=", "requests", ".", "post", ")", ":", "filehash", "=", "sha1sum", "(", "filename", ")", "files", "=", "{", "'filedata'", ":"...
Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters.
[ "Uploads", "file", "(", "given", "by", "filename", ")", "to", "server", "at", "baseurl", "." ]
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signing/client.py#L161-L177
xav-b/pyconsul
pyconsul/utils.py
decode_values
def decode_values(fct): ''' Decode base64 encoded responses from Consul storage ''' def inner(*args, **kwargs): ''' decorator ''' data = fct(*args, **kwargs) if 'error' not in data: for result in data: result['Value'] = base64.b64decode(result['Value']) return data return inner
python
def decode_values(fct): ''' Decode base64 encoded responses from Consul storage ''' def inner(*args, **kwargs): ''' decorator ''' data = fct(*args, **kwargs) if 'error' not in data: for result in data: result['Value'] = base64.b64decode(result['Value']) return data return inner
[ "def", "decode_values", "(", "fct", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "''' decorator '''", "data", "=", "fct", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "'error'", "not", "in", "data", ":", ...
Decode base64 encoded responses from Consul storage
[ "Decode", "base64", "encoded", "responses", "from", "Consul", "storage" ]
train
https://github.com/xav-b/pyconsul/blob/06ce3b921d01010c19643424486bea4b22196076/pyconsul/utils.py#L13-L22
xav-b/pyconsul
pyconsul/utils.py
safe_request
def safe_request(fct): ''' Return json messages instead of raising errors ''' def inner(*args, **kwargs): ''' decorator ''' try: _data = fct(*args, **kwargs) except requests.exceptions.ConnectionError as error: return {'error': str(error), 'status': 404} if _data.ok: if _data.content: safe_data = _data.json() else: safe_data = {'success': True} else: safe_data = {'error': _data.reason, 'status': _data.status_code} return safe_data return inner
python
def safe_request(fct): ''' Return json messages instead of raising errors ''' def inner(*args, **kwargs): ''' decorator ''' try: _data = fct(*args, **kwargs) except requests.exceptions.ConnectionError as error: return {'error': str(error), 'status': 404} if _data.ok: if _data.content: safe_data = _data.json() else: safe_data = {'success': True} else: safe_data = {'error': _data.reason, 'status': _data.status_code} return safe_data return inner
[ "def", "safe_request", "(", "fct", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "''' decorator '''", "try", ":", "_data", "=", "fct", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "requests", ".", "exce...
Return json messages instead of raising errors
[ "Return", "json", "messages", "instead", "of", "raising", "errors" ]
train
https://github.com/xav-b/pyconsul/blob/06ce3b921d01010c19643424486bea4b22196076/pyconsul/utils.py#L25-L43
twisted/mantissa
xmantissa/smtp.py
parseAddress
def parseAddress(address): """ Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address. """ parts = [] parser = _AddressParser() end = parser(parts, address) if end != len(address): raise InvalidTrailingBytes() return parts[0]
python
def parseAddress(address): """ Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address. """ parts = [] parser = _AddressParser() end = parser(parts, address) if end != len(address): raise InvalidTrailingBytes() return parts[0]
[ "def", "parseAddress", "(", "address", ")", ":", "parts", "=", "[", "]", "parser", "=", "_AddressParser", "(", ")", "end", "=", "parser", "(", "parts", ",", "address", ")", "if", "end", "!=", "len", "(", "address", ")", ":", "raise", "InvalidTrailingBy...
Parse the given RFC 2821 email address into a structured object. @type address: C{str} @param address: The address to parse. @rtype: L{Address} @raise xmantissa.error.ArgumentError: The given string was not a valid RFC 2821 address.
[ "Parse", "the", "given", "RFC", "2821", "email", "address", "into", "a", "structured", "object", "." ]
train
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/smtp.py#L190-L207
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.start
def start(self): """ The main method that starts the service. This is blocking. """ self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._start_periodic_tasks() # starts the event handlers self._initialize_event_handlers() self._start_event_handlers() try: self.io_loop.start() except RuntimeError: # TODO : find a way to check if the io_loop is running before trying to start it # this method to check if the loop is running is ugly pass
python
def start(self): """ The main method that starts the service. This is blocking. """ self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._start_periodic_tasks() # starts the event handlers self._initialize_event_handlers() self._start_event_handlers() try: self.io_loop.start() except RuntimeError: # TODO : find a way to check if the io_loop is running before trying to start it # this method to check if the loop is running is ugly pass
[ "def", "start", "(", "self", ")", ":", "self", ".", "_initial_setup", "(", ")", "self", ".", "on_service_start", "(", ")", "self", ".", "app", "=", "self", ".", "make_tornado_app", "(", ")", "enable_pretty_logging", "(", ")", "self", ".", "app", ".", "...
The main method that starts the service. This is blocking.
[ "The", "main", "method", "that", "starts", "the", "service", ".", "This", "is", "blocking", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L141-L163
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.get_plugin
def get_plugin(self, name): """ Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance. """ for plugin in self.plugins: if plugin.name == name: return plugin raise PluginDoesNotExistError("Plugin '{}' not found".format(name))
python
def get_plugin(self, name): """ Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance. """ for plugin in self.plugins: if plugin.name == name: return plugin raise PluginDoesNotExistError("Plugin '{}' not found".format(name))
[ "def", "get_plugin", "(", "self", ",", "name", ")", ":", "for", "plugin", "in", "self", ".", "plugins", ":", "if", "plugin", ".", "name", "==", "name", ":", "return", "plugin", "raise", "PluginDoesNotExistError", "(", "\"Plugin '{}' not found\"", ".", "forma...
Returns a plugin by name and raises ``gemstone.errors.PluginDoesNotExistError`` error if no plugin with such name exists. :param name: a string specifying a plugin name. :return: the corresponding plugin instance.
[ "Returns", "a", "plugin", "by", "name", "and", "raises", "gemstone", ".", "errors", ".", "PluginDoesNotExistError", "error", "if", "no", "plugin", "with", "such", "name", "exists", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L165-L177
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.get_service
def get_service(self, name): """ Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are multiple services with the same name running, or when the pattern matches multiple different services. .. todo:: Make this use self.io_loop to resolve the request. The current implementation is blocking and slow :param name: a pattern for the searched service. :return: a :py:class:`gemstone.RemoteService` instance :raises ValueError: when the service can not be located :raises ServiceConfigurationError: when there is no configured discovery strategy """ if not self.discovery_strategies: raise ServiceConfigurationError("No service registry available") cached = self.remote_service_cache.get_entry(name) if cached: return cached.remote_service for strategy in self.discovery_strategies: endpoints = strategy.locate(name) if not endpoints: continue random.shuffle(endpoints) for url in endpoints: try: service = get_remote_service_instance_for_url(url) self.remote_service_cache.add_entry(name, service) return service except ConnectionError: continue # could not establish connection, try next raise ValueError("Service could not be located")
python
def get_service(self, name): """ Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are multiple services with the same name running, or when the pattern matches multiple different services. .. todo:: Make this use self.io_loop to resolve the request. The current implementation is blocking and slow :param name: a pattern for the searched service. :return: a :py:class:`gemstone.RemoteService` instance :raises ValueError: when the service can not be located :raises ServiceConfigurationError: when there is no configured discovery strategy """ if not self.discovery_strategies: raise ServiceConfigurationError("No service registry available") cached = self.remote_service_cache.get_entry(name) if cached: return cached.remote_service for strategy in self.discovery_strategies: endpoints = strategy.locate(name) if not endpoints: continue random.shuffle(endpoints) for url in endpoints: try: service = get_remote_service_instance_for_url(url) self.remote_service_cache.add_entry(name, service) return service except ConnectionError: continue # could not establish connection, try next raise ValueError("Service could not be located")
[ "def", "get_service", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "discovery_strategies", ":", "raise", "ServiceConfigurationError", "(", "\"No service registry available\"", ")", "cached", "=", "self", ".", "remote_service_cache", ".", "get_entry"...
Locates a remote service by name. The name can be a glob-like pattern (``"project.worker.*"``). If multiple services match the given name, a random instance will be chosen. There might be multiple services that match a given name if there are multiple services with the same name running, or when the pattern matches multiple different services. .. todo:: Make this use self.io_loop to resolve the request. The current implementation is blocking and slow :param name: a pattern for the searched service. :return: a :py:class:`gemstone.RemoteService` instance :raises ValueError: when the service can not be located :raises ServiceConfigurationError: when there is no configured discovery strategy
[ "Locates", "a", "remote", "service", "by", "name", ".", "The", "name", "can", "be", "a", "glob", "-", "like", "pattern", "(", "project", ".", "worker", ".", "*", ")", ".", "If", "multiple", "services", "match", "the", "given", "name", "a", "random", ...
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L215-L253
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.start_thread
def start_thread(self, target, args, kwargs): """ Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0 """ thread_obj = threading.Thread(target=target, args=args, kwargs=kwargs, daemon=True) thread_obj.start()
python
def start_thread(self, target, args, kwargs): """ Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0 """ thread_obj = threading.Thread(target=target, args=args, kwargs=kwargs, daemon=True) thread_obj.start()
[ "def", "start_thread", "(", "self", ",", "target", ",", "args", ",", "kwargs", ")", ":", "thread_obj", "=", "threading", ".", "Thread", "(", "target", "=", "target", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ",", "daemon", "=", "True", ...
Shortcut method for starting a thread. :param target: The function to be executed. :param args: A tuple or list representing the positional arguments for the thread. :param kwargs: A dictionary representing the keyword arguments. .. versionadded:: 0.5.0
[ "Shortcut", "method", "for", "starting", "a", "thread", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L267-L278
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.emit_event
def emit_event(self, event_name, event_body): """ Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. :param event_name: a ``str`` representing the event type :param event_body: a Python object that can be represented as JSON. .. versionadded:: 0.5.0 .. versionchanged:: 0.10.0 Added parameter broadcast """ for transport in self.event_transports: transport.emit_event(event_name, event_body)
python
def emit_event(self, event_name, event_body): """ Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. :param event_name: a ``str`` representing the event type :param event_body: a Python object that can be represented as JSON. .. versionadded:: 0.5.0 .. versionchanged:: 0.10.0 Added parameter broadcast """ for transport in self.event_transports: transport.emit_event(event_name, event_body)
[ "def", "emit_event", "(", "self", ",", "event_name", ",", "event_body", ")", ":", "for", "transport", "in", "self", ".", "event_transports", ":", "transport", ".", "emit_event", "(", "event_name", ",", "event_body", ")" ]
Publishes an event of type ``event_name`` to all subscribers, having the body ``event_body``. The event is pushed through all available event transports. The event body must be a Python object that can be represented as a JSON. :param event_name: a ``str`` representing the event type :param event_body: a Python object that can be represented as JSON. .. versionadded:: 0.5.0 .. versionchanged:: 0.10.0 Added parameter broadcast
[ "Publishes", "an", "event", "of", "type", "event_name", "to", "all", "subscribers", "having", "the", "body", "event_body", ".", "The", "event", "is", "pushed", "through", "all", "available", "event", "transports", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L280-L297
vladcalin/gemstone
gemstone/core/microservice.py
MicroService.make_tornado_app
def make_tornado_app(self): """ Creates a :py:class`tornado.web.Application` instance that respect the JSON RPC 2.0 specs and exposes the designated methods. Can be used in tests to obtain the Tornado application. :return: a :py:class:`tornado.web.Application` instance """ handlers = [ (self.endpoint, TornadoJsonRpcHandler, {"microservice": self}) ] self._add_extra_handlers(handlers) self._add_static_handlers(handlers) return Application(handlers, template_path=self.template_dir)
python
def make_tornado_app(self): """ Creates a :py:class`tornado.web.Application` instance that respect the JSON RPC 2.0 specs and exposes the designated methods. Can be used in tests to obtain the Tornado application. :return: a :py:class:`tornado.web.Application` instance """ handlers = [ (self.endpoint, TornadoJsonRpcHandler, {"microservice": self}) ] self._add_extra_handlers(handlers) self._add_static_handlers(handlers) return Application(handlers, template_path=self.template_dir)
[ "def", "make_tornado_app", "(", "self", ")", ":", "handlers", "=", "[", "(", "self", ".", "endpoint", ",", "TornadoJsonRpcHandler", ",", "{", "\"microservice\"", ":", "self", "}", ")", "]", "self", ".", "_add_extra_handlers", "(", "handlers", ")", "self", ...
Creates a :py:class`tornado.web.Application` instance that respect the JSON RPC 2.0 specs and exposes the designated methods. Can be used in tests to obtain the Tornado application. :return: a :py:class:`tornado.web.Application` instance
[ "Creates", "a", ":", "py", ":", "class", "tornado", ".", "web", ".", "Application", "instance", "that", "respect", "the", "JSON", "RPC", "2", ".", "0", "specs", "and", "exposes", "the", "designated", "methods", ".", "Can", "be", "used", "in", "tests", ...
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L367-L383
vladcalin/gemstone
gemstone/core/microservice.py
MicroService._add_extra_handlers
def _add_extra_handlers(self, handlers): """ Adds the extra handler (defined by the user) :param handlers: a list of :py:class:`tornado.web.RequestHandler` instances. :return: """ extra_handlers = [(h[0], h[1], {"microservice": self}) for h in self.extra_handlers] handlers.extend(extra_handlers)
python
def _add_extra_handlers(self, handlers): """ Adds the extra handler (defined by the user) :param handlers: a list of :py:class:`tornado.web.RequestHandler` instances. :return: """ extra_handlers = [(h[0], h[1], {"microservice": self}) for h in self.extra_handlers] handlers.extend(extra_handlers)
[ "def", "_add_extra_handlers", "(", "self", ",", "handlers", ")", ":", "extra_handlers", "=", "[", "(", "h", "[", "0", "]", ",", "h", "[", "1", "]", ",", "{", "\"microservice\"", ":", "self", "}", ")", "for", "h", "in", "self", ".", "extra_handlers", ...
Adds the extra handler (defined by the user) :param handlers: a list of :py:class:`tornado.web.RequestHandler` instances. :return:
[ "Adds", "the", "extra", "handler", "(", "defined", "by", "the", "user", ")" ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L385-L393
vladcalin/gemstone
gemstone/core/microservice.py
MicroService._add_static_handlers
def _add_static_handlers(self, handlers): """ Creates and adds the handles needed for serving static files. :param handlers: """ for url, path in self.static_dirs: handlers.append((url.rstrip("/") + "/(.*)", StaticFileHandler, {"path": path}))
python
def _add_static_handlers(self, handlers): """ Creates and adds the handles needed for serving static files. :param handlers: """ for url, path in self.static_dirs: handlers.append((url.rstrip("/") + "/(.*)", StaticFileHandler, {"path": path}))
[ "def", "_add_static_handlers", "(", "self", ",", "handlers", ")", ":", "for", "url", ",", "path", "in", "self", ".", "static_dirs", ":", "handlers", ".", "append", "(", "(", "url", ".", "rstrip", "(", "\"/\"", ")", "+", "\"/(.*)\"", ",", "StaticFileHandl...
Creates and adds the handles needed for serving static files. :param handlers:
[ "Creates", "and", "adds", "the", "handles", "needed", "for", "serving", "static", "files", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L395-L402
vladcalin/gemstone
gemstone/core/microservice.py
MicroService._gather_exposed_methods
def _gather_exposed_methods(self): """ Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`. """ self._extract_methods_from_container(self) for module in self.modules: self._extract_methods_from_container(module)
python
def _gather_exposed_methods(self): """ Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`. """ self._extract_methods_from_container(self) for module in self.modules: self._extract_methods_from_container(module)
[ "def", "_gather_exposed_methods", "(", "self", ")", ":", "self", ".", "_extract_methods_from_container", "(", "self", ")", "for", "module", "in", "self", ".", "modules", ":", "self", ".", "_extract_methods_from_container", "(", "module", ")" ]
Searches for the exposed methods in the current microservice class. A method is considered exposed if it is decorated with the :py:func:`gemstone.public_method` or :py:func:`gemstone.private_api_method`.
[ "Searches", "for", "the", "exposed", "methods", "in", "the", "current", "microservice", "class", ".", "A", "method", "is", "considered", "exposed", "if", "it", "is", "decorated", "with", "the", ":", "py", ":", "func", ":", "gemstone", ".", "public_method", ...
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L404-L414
vladcalin/gemstone
gemstone/core/microservice.py
MicroService._gather_event_handlers
def _gather_event_handlers(self): """ Searches for the event handlers in the current microservice class. :return: """ self._extract_event_handlers_from_container(self) for module in self.modules: self._extract_event_handlers_from_container(module)
python
def _gather_event_handlers(self): """ Searches for the event handlers in the current microservice class. :return: """ self._extract_event_handlers_from_container(self) for module in self.modules: self._extract_event_handlers_from_container(module)
[ "def", "_gather_event_handlers", "(", "self", ")", ":", "self", ".", "_extract_event_handlers_from_container", "(", "self", ")", "for", "module", "in", "self", ".", "modules", ":", "self", ".", "_extract_event_handlers_from_container", "(", "module", ")" ]
Searches for the event handlers in the current microservice class. :return:
[ "Searches", "for", "the", "event", "handlers", "in", "the", "current", "microservice", "class", "." ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L424-L432
vladcalin/gemstone
gemstone/core/microservice.py
MicroService._periodic_task_iter
def _periodic_task_iter(self): """ Iterates through all the periodic tasks: - the service registry pinging - default dummy task if on Windows - user defined periodic tasks :return: """ for strategy in self.discovery_strategies: self.default_periodic_tasks.append( (functools.partial(strategy.ping, self.name, self.accessible_at), self.service_registry_ping_interval) ) self.default_periodic_tasks[-1][0]() all_periodic_tasks = self.default_periodic_tasks + self.periodic_tasks for func, timer_in_seconds in all_periodic_tasks: timer_milisec = timer_in_seconds * 1000 yield PeriodicCallback(func, timer_milisec, io_loop=self.io_loop)
python
def _periodic_task_iter(self): """ Iterates through all the periodic tasks: - the service registry pinging - default dummy task if on Windows - user defined periodic tasks :return: """ for strategy in self.discovery_strategies: self.default_periodic_tasks.append( (functools.partial(strategy.ping, self.name, self.accessible_at), self.service_registry_ping_interval) ) self.default_periodic_tasks[-1][0]() all_periodic_tasks = self.default_periodic_tasks + self.periodic_tasks for func, timer_in_seconds in all_periodic_tasks: timer_milisec = timer_in_seconds * 1000 yield PeriodicCallback(func, timer_milisec, io_loop=self.io_loop)
[ "def", "_periodic_task_iter", "(", "self", ")", ":", "for", "strategy", "in", "self", ".", "discovery_strategies", ":", "self", ".", "default_periodic_tasks", ".", "append", "(", "(", "functools", ".", "partial", "(", "strategy", ".", "ping", ",", "self", "....
Iterates through all the periodic tasks: - the service registry pinging - default dummy task if on Windows - user defined periodic tasks :return:
[ "Iterates", "through", "all", "the", "periodic", "tasks", ":" ]
train
https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/microservice.py#L438-L458
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.initialize
def initialize(self): '''Calling this function initializes the printer. Args: None Returns: None Raises: None ''' self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64))
python
def initialize(self): '''Calling this function initializes the printer. Args: None Returns: None Raises: None ''' self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64))
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "fonttype", "=", "self", ".", "font_types", "[", "'bitmap'", "]", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "chr", "(", "64", ")", ")" ]
Calling this function initializes the printer. Args: None Returns: None Raises: None
[ "Calling", "this", "function", "initializes", "the", "printer", ".", "Args", ":", "None", "Returns", ":", "None", "Raises", ":", "None" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L62-L73
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.select_charset
def select_charset(self, charset): '''Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset. ''' charsets = {'USA':0, 'France':1, 'Germany':2, 'UK':3, 'Denmark':4, 'Sweden':5, 'Italy':6, 'Spain':7, 'Japan':8, 'Norway':9, 'Denmark II':10, 'Spain II':11, 'Latin America':12, 'South Korea':13, 'Legal':64, } if charset in charsets: self.send(chr(27)+'R'+chr(charsets[charset])) else: raise RuntimeError('Invalid charset.')
python
def select_charset(self, charset): '''Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset. ''' charsets = {'USA':0, 'France':1, 'Germany':2, 'UK':3, 'Denmark':4, 'Sweden':5, 'Italy':6, 'Spain':7, 'Japan':8, 'Norway':9, 'Denmark II':10, 'Spain II':11, 'Latin America':12, 'South Korea':13, 'Legal':64, } if charset in charsets: self.send(chr(27)+'R'+chr(charsets[charset])) else: raise RuntimeError('Invalid charset.')
[ "def", "select_charset", "(", "self", ",", "charset", ")", ":", "charsets", "=", "{", "'USA'", ":", "0", ",", "'France'", ":", "1", ",", "'Germany'", ":", "2", ",", "'UK'", ":", "3", ",", "'Denmark'", ":", "4", ",", "'Sweden'", ":", "5", ",", "'I...
Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset.
[ "Select", "international", "character", "set", "and", "changes", "codes", "in", "code", "table", "accordingly", "Args", ":", "charset", ":", "String", ".", "The", "character", "set", "we", "want", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", "...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L75-L104
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.select_char_code_table
def select_char_code_table(self, table): '''Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable. ''' tables = {'standard': 0, 'eastern european': 1, 'western european': 2, 'spare': 3 } if table in tables: self.send(chr(27)+'t'+chr(tables[table])) else: raise RuntimeError('Invalid char table.')
python
def select_char_code_table(self, table): '''Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable. ''' tables = {'standard': 0, 'eastern european': 1, 'western european': 2, 'spare': 3 } if table in tables: self.send(chr(27)+'t'+chr(tables[table])) else: raise RuntimeError('Invalid char table.')
[ "def", "select_char_code_table", "(", "self", ",", "table", ")", ":", "tables", "=", "{", "'standard'", ":", "0", ",", "'eastern european'", ":", "1", ",", "'western european'", ":", "2", ",", "'spare'", ":", "3", "}", "if", "table", "in", "tables", ":",...
Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable.
[ "Select", "character", "code", "table", "from", "tree", "built", "in", "ones", ".", "Args", ":", "table", ":", "The", "desired", "character", "code", "table", ".", "Choose", "from", "standard", "eastern", "european", "western", "european", "and", "spare", "R...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L106-L124
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.cut_setting
def cut_setting(self, cut): '''Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type. ''' cut_settings = {'full' : 0b00000001, 'half' : 0b00000010, 'chain': 0b00000100, 'special': 0b00001000 } if cut in cut_settings: self.send(chr(27)+'iC'+chr(cut_settings[cut])) else: raise RuntimeError('Invalid cut type.')
python
def cut_setting(self, cut): '''Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type. ''' cut_settings = {'full' : 0b00000001, 'half' : 0b00000010, 'chain': 0b00000100, 'special': 0b00001000 } if cut in cut_settings: self.send(chr(27)+'iC'+chr(cut_settings[cut])) else: raise RuntimeError('Invalid cut type.')
[ "def", "cut_setting", "(", "self", ",", "cut", ")", ":", "cut_settings", "=", "{", "'full'", ":", "0b00000001", ",", "'half'", ":", "0b00000010", ",", "'chain'", ":", "0b00000100", ",", "'special'", ":", "0b00001000", "}", "if", "cut", "in", "cut_settings"...
Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type.
[ "Set", "cut", "setting", "for", "printer", ".", "Args", ":", "cut", ":", "The", "type", "of", "cut", "setting", "we", "want", ".", "Choices", "are", "full", "half", "chain", "and", "special", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L126-L145
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.rotated_printing
def rotated_printing(self, action): '''Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeError: Invalid action. ''' if action=='rotate': action='1' elif action=='cancel': action='0' else: raise RuntimeError('Invalid action.') self.send(chr(27)+chr(105)+chr(76)+action)
python
def rotated_printing(self, action): '''Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeError: Invalid action. ''' if action=='rotate': action='1' elif action=='cancel': action='0' else: raise RuntimeError('Invalid action.') self.send(chr(27)+chr(105)+chr(76)+action)
[ "def", "rotated_printing", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'rotate'", ":", "action", "=", "'1'", "elif", "action", "==", "'cancel'", ":", "action", "=", "'0'", "else", ":", "raise", "RuntimeError", "(", "'Invalid action.'", ")"...
Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeError: Invalid action.
[ "Calling", "this", "function", "applies", "the", "desired", "action", "to", "the", "printing", "orientation", "of", "the", "printer", ".", "Args", ":", "action", ":", "The", "desired", "printing", "orientation", ".", "rotate", "enables", "rotated", "printing", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L151-L168
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.feed_amount
def feed_amount(self, amount): '''Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: None Raises: None ''' n = None if amount=='1/8': amount = '0' elif amount=='1/6': amount = '2' elif re.search('/180', amount): n = re.search(r"(\d+)/180", amount) n = n.group(1) amount = '3' elif re.search('/60', amount): n = re.search(r"(\d+)/60", amount) n = n.group(1) amount = 'A' if n: self.send(chr(27)+amount+n) else: self.send(chr(27)+amount)
python
def feed_amount(self, amount): '''Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: None Raises: None ''' n = None if amount=='1/8': amount = '0' elif amount=='1/6': amount = '2' elif re.search('/180', amount): n = re.search(r"(\d+)/180", amount) n = n.group(1) amount = '3' elif re.search('/60', amount): n = re.search(r"(\d+)/60", amount) n = n.group(1) amount = 'A' if n: self.send(chr(27)+amount+n) else: self.send(chr(27)+amount)
[ "def", "feed_amount", "(", "self", ",", "amount", ")", ":", "n", "=", "None", "if", "amount", "==", "'1/8'", ":", "amount", "=", "'0'", "elif", "amount", "==", "'1/6'", ":", "amount", "=", "'2'", "elif", "re", ".", "search", "(", "'/180'", ",", "am...
Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: None Raises: None
[ "Calling", "this", "function", "sets", "the", "form", "feed", "amount", "to", "the", "specified", "setting", ".", "Args", ":", "amount", ":", "the", "form", "feed", "setting", "you", "desire", ".", "Options", "are", "1", "/", "8", "1", "/", "6", "x", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L170-L197
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.page_length
def page_length(self, length): '''Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000. ''' mH = length/256 mL = length%256 if length < 12000: self.send(chr(27)+'('+'C'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Length must be less than 12000.')
python
def page_length(self, length): '''Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000. ''' mH = length/256 mL = length%256 if length < 12000: self.send(chr(27)+'('+'C'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Length must be less than 12000.')
[ "def", "page_length", "(", "self", ",", "length", ")", ":", "mH", "=", "length", "/", "256", "mL", "=", "length", "%", "256", "if", "length", "<", "12000", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'('", "+", "'C'", "+", "chr"...
Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000.
[ "Specifies", "page", "length", ".", "This", "command", "is", "only", "valid", "with", "continuous", "length", "labels", ".", "Args", ":", "length", ":", "The", "length", "of", "the", "page", "in", "dots", ".", "Can", "t", "exceed", "12000", ".", "Returns...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L199-L214
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.page_format
def page_format(self, topmargin, bottommargin): '''Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. Returns: None Raises: RuntimeError: Top margin must be less than the bottom margin. ''' tL = topmargin%256 tH = topmargin/256 BL = bottommargin%256 BH = topmargin/256 if (tL+tH*256) < (BL + BH*256): self.send(chr(27)+'('+'c'+chr(4)+chr(0)+chr(tL)+chr(tH)+chr(BL)+chr(BH)) else: raise RuntimeError('The top margin must be less than the bottom margin')
python
def page_format(self, topmargin, bottommargin): '''Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. Returns: None Raises: RuntimeError: Top margin must be less than the bottom margin. ''' tL = topmargin%256 tH = topmargin/256 BL = bottommargin%256 BH = topmargin/256 if (tL+tH*256) < (BL + BH*256): self.send(chr(27)+'('+'c'+chr(4)+chr(0)+chr(tL)+chr(tH)+chr(BL)+chr(BH)) else: raise RuntimeError('The top margin must be less than the bottom margin')
[ "def", "page_format", "(", "self", ",", "topmargin", ",", "bottommargin", ")", ":", "tL", "=", "topmargin", "%", "256", "tH", "=", "topmargin", "/", "256", "BL", "=", "bottommargin", "%", "256", "BH", "=", "topmargin", "/", "256", "if", "(", "tL", "+...
Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. Returns: None Raises: RuntimeError: Top margin must be less than the bottom margin.
[ "Specify", "settings", "for", "top", "and", "bottom", "margins", ".", "Physically", "printable", "area", "depends", "on", "media", ".", "Args", ":", "topmargin", ":", "the", "top", "margin", "in", "dots", ".", "The", "top", "margin", "must", "be", "less", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L216-L234
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.left_margin
def left_margin(self, margin): '''Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter. ''' if margin <= 255 and margin >= 0: self.send(chr(27)+'I'+chr(margin)) else: raise RuntimeError('Invalid margin parameter.')
python
def left_margin(self, margin): '''Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter. ''' if margin <= 255 and margin >= 0: self.send(chr(27)+'I'+chr(margin)) else: raise RuntimeError('Invalid margin parameter.')
[ "def", "left_margin", "(", "self", ",", "margin", ")", ":", "if", "margin", "<=", "255", "and", "margin", ">=", "0", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'I'", "+", "chr", "(", "margin", ")", ")", "else", ":", "raise", "R...
Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter.
[ "Specify", "the", "left", "margin", ".", "Args", ":", "margin", ":", "The", "left", "margin", "in", "character", "width", ".", "Must", "be", "less", "than", "the", "media", "s", "width", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L236-L249
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.right_margin
def right_margin(self, margin): '''Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter ''' if margin >=1 and margin <=255: self.send(chr(27)+'Q'+chr(margin)) else: raise RuntimeError('Invalid margin parameter in function rightMargin')
python
def right_margin(self, margin): '''Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter ''' if margin >=1 and margin <=255: self.send(chr(27)+'Q'+chr(margin)) else: raise RuntimeError('Invalid margin parameter in function rightMargin')
[ "def", "right_margin", "(", "self", ",", "margin", ")", ":", "if", "margin", ">=", "1", "and", "margin", "<=", "255", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'Q'", "+", "chr", "(", "margin", ")", ")", "else", ":", "raise", "...
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
[ "Specify", "the", "right", "margin", ".", "Args", ":", "margin", ":", "The", "right", "margin", "in", "character", "width", "must", "be", "less", "than", "the", "media", "s", "width", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Inva...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L251-L264
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.vert_tab_pos
def vert_tab_pos(self, positions): '''Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeError: Too many positions. ''' if positions == 'clear': self.send(chr(27)+'B'+chr(0)) return if positions.min < 1 or positions.max >255: raise RuntimeError('Invalid position parameter in function horzTabPos') sendstr = chr(27) + 'D' if len(positions)<=16: for position in positions: sendstr += chr(position) self.send(sendstr + chr(0)) else: raise RuntimeError('Too many positions in function vertTabPos')
python
def vert_tab_pos(self, positions): '''Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeError: Too many positions. ''' if positions == 'clear': self.send(chr(27)+'B'+chr(0)) return if positions.min < 1 or positions.max >255: raise RuntimeError('Invalid position parameter in function horzTabPos') sendstr = chr(27) + 'D' if len(positions)<=16: for position in positions: sendstr += chr(position) self.send(sendstr + chr(0)) else: raise RuntimeError('Too many positions in function vertTabPos')
[ "def", "vert_tab_pos", "(", "self", ",", "positions", ")", ":", "if", "positions", "==", "'clear'", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'B'", "+", "chr", "(", "0", ")", ")", "return", "if", "positions", ".", "min", "<", "1...
Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeError: Too many positions.
[ "Sets", "tab", "positions", "up", "to", "a", "maximum", "of", "32", "positions", ".", "Also", "can", "clear", "tab", "positions", ".", "Args", ":", "positions", "--", "Either", "a", "list", "of", "tab", "positions", "(", "between", "1", "and", "255", "...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L290-L312
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.forward_feed
def forward_feed(self, amount): '''Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None Raises: RuntimeError: Invalid foward feed. ''' if amount <= 255 and amount >=0: self.send(chr(27)+'J'+chr(amount)) else: raise RuntimeError('Invalid foward feed, must be less than 255 and >= 0')
python
def forward_feed(self, amount): '''Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None Raises: RuntimeError: Invalid foward feed. ''' if amount <= 255 and amount >=0: self.send(chr(27)+'J'+chr(amount)) else: raise RuntimeError('Invalid foward feed, must be less than 255 and >= 0')
[ "def", "forward_feed", "(", "self", ",", "amount", ")", ":", "if", "amount", "<=", "255", "and", "amount", ">=", "0", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'J'", "+", "chr", "(", "amount", ")", ")", "else", ":", "raise", "...
Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None Raises: RuntimeError: Invalid foward feed.
[ "Calling", "this", "function", "finishes", "input", "of", "the", "current", "line", "then", "moves", "the", "vertical", "print", "position", "forward", "by", "x", "/", "300", "inch", ".", "Args", ":", "amount", ":", "how", "far", "foward", "you", "want", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L329-L344
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.abs_vert_pos
def abs_vert_pos(self, amount): '''Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position. ''' mL = amount%256 mH = amount/256 if amount < 32767 and amount > 0: self.send(chr(27)+'('+'V'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Invalid vertical position in function absVertPos')
python
def abs_vert_pos(self, amount): '''Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position. ''' mL = amount%256 mH = amount/256 if amount < 32767 and amount > 0: self.send(chr(27)+'('+'V'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Invalid vertical position in function absVertPos')
[ "def", "abs_vert_pos", "(", "self", ",", "amount", ")", ":", "mL", "=", "amount", "%", "256", "mH", "=", "amount", "/", "256", "if", "amount", "<", "32767", "and", "amount", ">", "0", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "...
Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position.
[ "Specify", "vertical", "print", "position", "from", "the", "top", "margin", "position", ".", "Args", ":", "amount", ":", "The", "distance", "from", "the", "top", "margin", "you", "d", "like", "from", "0", "to", "32767", "Returns", ":", "None", "Raises", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L346-L361
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.abs_horz_pos
def abs_horz_pos(self, amount): '''Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. Returns: None Raises: None ''' n1 = amount%256 n2 = amount/256 self.send(chr(27)+'${n1}{n2}'.format(n1=chr(n1), n2=chr(n2)))
python
def abs_horz_pos(self, amount): '''Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. Returns: None Raises: None ''' n1 = amount%256 n2 = amount/256 self.send(chr(27)+'${n1}{n2}'.format(n1=chr(n1), n2=chr(n2)))
[ "def", "abs_horz_pos", "(", "self", ",", "amount", ")", ":", "n1", "=", "amount", "%", "256", "n2", "=", "amount", "/", "256", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'${n1}{n2}'", ".", "format", "(", "n1", "=", "chr", "(", "n1", ...
Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. Returns: None Raises: None
[ "Calling", "this", "function", "sets", "the", "absoulte", "print", "position", "for", "the", "next", "data", "this", "is", "the", "position", "from", "the", "left", "margin", ".", "Args", ":", "amount", ":", "desired", "positioning", ".", "Can", "be", "a",...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L363-L377
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.rel_horz_pos
def rel_horz_pos(self, amount): '''Calling this function sets the relative horizontal position for the next data, this is the position from the current position. The next character will be printed (x/180)inches away from the current position. The relative position CANNOT be specified to the left. This command is only valid with left alignment. Args: amount: desired positioning. Can be a number from 0 to 7086. The actual positioning is calculated as (amount/180)inches from the current position. Returns: None Raises: None ''' n1 = amount%256 n2 = amount/256 self.send(chr(27)+'\{n1}{n2}'.format(n1=chr(n1),n2=chr(n2)))
python
def rel_horz_pos(self, amount): '''Calling this function sets the relative horizontal position for the next data, this is the position from the current position. The next character will be printed (x/180)inches away from the current position. The relative position CANNOT be specified to the left. This command is only valid with left alignment. Args: amount: desired positioning. Can be a number from 0 to 7086. The actual positioning is calculated as (amount/180)inches from the current position. Returns: None Raises: None ''' n1 = amount%256 n2 = amount/256 self.send(chr(27)+'\{n1}{n2}'.format(n1=chr(n1),n2=chr(n2)))
[ "def", "rel_horz_pos", "(", "self", ",", "amount", ")", ":", "n1", "=", "amount", "%", "256", "n2", "=", "amount", "/", "256", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'\\{n1}{n2}'", ".", "format", "(", "n1", "=", "chr", "(", "n1", ...
Calling this function sets the relative horizontal position for the next data, this is the position from the current position. The next character will be printed (x/180)inches away from the current position. The relative position CANNOT be specified to the left. This command is only valid with left alignment. Args: amount: desired positioning. Can be a number from 0 to 7086. The actual positioning is calculated as (amount/180)inches from the current position. Returns: None Raises: None
[ "Calling", "this", "function", "sets", "the", "relative", "horizontal", "position", "for", "the", "next", "data", "this", "is", "the", "position", "from", "the", "current", "position", ".", "The", "next", "character", "will", "be", "printed", "(", "x", "/", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L379-L395
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.alignment
def alignment(self, align): '''Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment. ''' if align=='left': align = '0' elif align=='center': align = '1' elif align=='right': align = '2' elif align=='justified': align = '3' else: raise RuntimeError('Invalid alignment in function alignment') self.send(chr(27)+'a'+align)
python
def alignment(self, align): '''Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment. ''' if align=='left': align = '0' elif align=='center': align = '1' elif align=='right': align = '2' elif align=='justified': align = '3' else: raise RuntimeError('Invalid alignment in function alignment') self.send(chr(27)+'a'+align)
[ "def", "alignment", "(", "self", ",", "align", ")", ":", "if", "align", "==", "'left'", ":", "align", "=", "'0'", "elif", "align", "==", "'center'", ":", "align", "=", "'1'", "elif", "align", "==", "'right'", ":", "align", "=", "'2'", "elif", "align"...
Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment.
[ "Sets", "the", "alignment", "of", "the", "printer", ".", "Args", ":", "align", ":", "desired", "alignment", ".", "Options", "are", "left", "center", "right", "and", "justified", ".", "Anything", "else", "will", "throw", "an", "error", ".", "Returns", ":", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L397-L418
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.frame
def frame(self, action): '''Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' choices = {'on': '1', 'off': '0'} if action in choices: self.send(chr(27)+'if'+choices[action]) else: raise RuntimeError('Invalid action for function frame, choices are on and off')
python
def frame(self, action): '''Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' choices = {'on': '1', 'off': '0'} if action in choices: self.send(chr(27)+'if'+choices[action]) else: raise RuntimeError('Invalid action for function frame, choices are on and off')
[ "def", "frame", "(", "self", ",", "action", ")", ":", "choices", "=", "{", "'on'", ":", "'1'", ",", "'off'", ":", "'0'", "}", "if", "action", "in", "choices", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'if'", "+", "choices", "[...
Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Places", "/", "removes", "frame", "around", "text", "Args", ":", "action", "--", "Enable", "or", "disable", "frame", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "action", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L471-L486
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.bold
def bold(self, action): '''Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = 'E' elif action == 'off': action = 'F' else: raise RuntimeError('Invalid action for function bold. Options are on and off') self.send(chr(27)+action)
python
def bold(self, action): '''Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = 'E' elif action == 'off': action = 'F' else: raise RuntimeError('Invalid action for function bold. Options are on and off') self.send(chr(27)+action)
[ "def", "bold", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'on'", ":", "action", "=", "'E'", "elif", "action", "==", "'off'", ":", "action", "=", "'F'", "else", ":", "raise", "RuntimeError", "(", "'Invalid action for function bold. Options a...
Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Enable", "/", "cancel", "bold", "printing", "Args", ":", "action", ":", "Enable", "or", "disable", "bold", "printing", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "action", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L514-L530
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.italic
def italic(self, action): '''Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = '4' elif action=='off': action = '5' else: raise RuntimeError('Invalid action for function italic. Options are on and off') self.send(chr(27)+action)
python
def italic(self, action): '''Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action =='on': action = '4' elif action=='off': action = '5' else: raise RuntimeError('Invalid action for function italic. Options are on and off') self.send(chr(27)+action)
[ "def", "italic", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'on'", ":", "action", "=", "'4'", "elif", "action", "==", "'off'", ":", "action", "=", "'5'", "else", ":", "raise", "RuntimeError", "(", "'Invalid action for function italic. Optio...
Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Enable", "/", "cancel", "italic", "printing", "Args", ":", "action", ":", "Enable", "or", "disable", "italic", "printing", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "action", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L532-L548
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.double_strike
def double_strike(self, action): '''Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 'G' elif action == 'off': action = 'H' else: raise RuntimeError('Invalid action for function doubleStrike. Options are on and off') self.send(chr(27)+action)
python
def double_strike(self, action): '''Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 'G' elif action == 'off': action = 'H' else: raise RuntimeError('Invalid action for function doubleStrike. Options are on and off') self.send(chr(27)+action)
[ "def", "double_strike", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'on'", ":", "action", "=", "'G'", "elif", "action", "==", "'off'", ":", "action", "=", "'H'", "else", ":", "raise", "RuntimeError", "(", "'Invalid action for function double...
Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Enable", "/", "cancel", "doublestrike", "printing", "Args", ":", "action", ":", "Enable", "or", "disable", "doublestrike", "printing", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "action", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L550-L566
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.double_width
def double_width(self, action): '''Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = '1' elif action == 'off': action = '0' else: raise RuntimeError('Invalid action for function doubleWidth. Options are on and off') self.send(chr(27)+'W'+action)
python
def double_width(self, action): '''Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = '1' elif action == 'off': action = '0' else: raise RuntimeError('Invalid action for function doubleWidth. Options are on and off') self.send(chr(27)+'W'+action)
[ "def", "double_width", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'on'", ":", "action", "=", "'1'", "elif", "action", "==", "'off'", ":", "action", "=", "'0'", "else", ":", "raise", "RuntimeError", "(", "'Invalid action for function doubleW...
Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Enable", "/", "cancel", "doublewidth", "printing", "Args", ":", "action", ":", "Enable", "or", "disable", "doublewidth", "printing", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "action", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L568-L584
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.compressed_char
def compressed_char(self, action): '''Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 15 elif action == 'off': action = 18 else: raise RuntimeError('Invalid action for function compressedChar. Options are on and off') self.send(chr(action))
python
def compressed_char(self, action): '''Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action. ''' if action == 'on': action = 15 elif action == 'off': action = 18 else: raise RuntimeError('Invalid action for function compressedChar. Options are on and off') self.send(chr(action))
[ "def", "compressed_char", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'on'", ":", "action", "=", "15", "elif", "action", "==", "'off'", ":", "action", "=", "18", "else", ":", "raise", "RuntimeError", "(", "'Invalid action for function compre...
Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
[ "Enable", "/", "cancel", "compressed", "character", "printing", "Args", ":", "action", ":", "Enable", "or", "disable", "compressed", "character", "printing", ".", "Options", "are", "on", "and", "off", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":",...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L586-L602
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.underline
def underline(self, action): '''Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None ''' if action == 'off': action = '0' self.send(chr(27)+chr(45)+action) else: self.send(chr(27)+chr(45)+action)
python
def underline(self, action): '''Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None ''' if action == 'off': action = '0' self.send(chr(27)+chr(45)+action) else: self.send(chr(27)+chr(45)+action)
[ "def", "underline", "(", "self", ",", "action", ")", ":", "if", "action", "==", "'off'", ":", "action", "=", "'0'", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "chr", "(", "45", ")", "+", "action", ")", "else", ":", "self", ".", "send...
Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None
[ "Enable", "/", "cancel", "underline", "printing", "Args", ":", "action", "--", "Enable", "or", "disable", "underline", "printing", ".", "Options", "are", "1", "-", "4", "and", "cancel", "Returns", ":", "None", "Raises", ":", "None" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L604-L618
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.char_size
def char_size(self, size): '''Changes font size Args: size: change font size. Options are 24' '32' '48' for bitmap fonts 33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233, 11, 44, 77, 111, 144 for outline fonts. Returns: None Raises: RuntimeError: Invalid font size. Warning: Your font is currently set to outline and you have selected a bitmap only font size Warning: Your font is currently set to bitmap and you have selected an outline only font size ''' sizes = {'24':0, '32':0, '48':0, '33':0, '38':0, '42':0, '46':0, '50':0, '58':0, '67':0, '75':0, '83':0, '92':0, '100':0, '117':0, '133':0, '150':0, '167':0, '200':0, '233':0, '11':1, '44':1, '77':1, '111':1, '144':1 } if size in sizes: if size in ['24','32','48'] and self.fonttype != self.font_types['bitmap']: raise Warning('Your font is currently set to outline and you have selected a bitmap only font size') if size not in ['24', '32', '48'] and self.fonttype != self.font_types['outline']: raise Warning('Your font is currently set to bitmap and you have selected an outline only font size') self.send(chr(27)+'X'+chr(0)+chr(int(size))+chr(sizes[size])) else: raise RuntimeError('Invalid size for function charSize, choices are auto 4pt 6pt 9pt 12pt 18pt and 24pt')
python
def char_size(self, size): '''Changes font size Args: size: change font size. Options are 24' '32' '48' for bitmap fonts 33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233, 11, 44, 77, 111, 144 for outline fonts. Returns: None Raises: RuntimeError: Invalid font size. Warning: Your font is currently set to outline and you have selected a bitmap only font size Warning: Your font is currently set to bitmap and you have selected an outline only font size ''' sizes = {'24':0, '32':0, '48':0, '33':0, '38':0, '42':0, '46':0, '50':0, '58':0, '67':0, '75':0, '83':0, '92':0, '100':0, '117':0, '133':0, '150':0, '167':0, '200':0, '233':0, '11':1, '44':1, '77':1, '111':1, '144':1 } if size in sizes: if size in ['24','32','48'] and self.fonttype != self.font_types['bitmap']: raise Warning('Your font is currently set to outline and you have selected a bitmap only font size') if size not in ['24', '32', '48'] and self.fonttype != self.font_types['outline']: raise Warning('Your font is currently set to bitmap and you have selected an outline only font size') self.send(chr(27)+'X'+chr(0)+chr(int(size))+chr(sizes[size])) else: raise RuntimeError('Invalid size for function charSize, choices are auto 4pt 6pt 9pt 12pt 18pt and 24pt')
[ "def", "char_size", "(", "self", ",", "size", ")", ":", "sizes", "=", "{", "'24'", ":", "0", ",", "'32'", ":", "0", ",", "'48'", ":", "0", ",", "'33'", ":", "0", ",", "'38'", ":", "0", ",", "'42'", ":", "0", ",", "'46'", ":", "0", ",", "'...
Changes font size Args: size: change font size. Options are 24' '32' '48' for bitmap fonts 33, 38, 42, 46, 50, 58, 67, 75, 83, 92, 100, 117, 133, 150, 167, 200 233, 11, 44, 77, 111, 144 for outline fonts. Returns: None Raises: RuntimeError: Invalid font size. Warning: Your font is currently set to outline and you have selected a bitmap only font size Warning: Your font is currently set to bitmap and you have selected an outline only font size
[ "Changes", "font", "size", "Args", ":", "size", ":", "change", "font", "size", ".", "Options", "are", "24", "32", "48", "for", "bitmap", "fonts", "33", "38", "42", "46", "50", "58", "67", "75", "83", "92", "100", "117", "133", "150", "167", "200", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L620-L667
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.select_font
def select_font(self, font): '''Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font: font type Returns: None Raises: RuntimeError: Invalid font. ''' fonts = {'brougham': 0, 'lettergothicbold': 1, 'brusselsbit' : 2, 'helsinkibit': 3, 'sandiego': 4, 'lettergothic': 9, 'brusselsoutline': 10, 'helsinkioutline': 11} if font in fonts: if font in ['broughham', 'lettergothicbold', 'brusselsbit', 'helsinkibit', 'sandiego']: self.fonttype = self.font_types['bitmap'] else: self.fonttype = self.font_types['outline'] self.send(chr(27)+'k'+chr(fonts[font])) else: raise RuntimeError('Invalid font in function selectFont')
python
def select_font(self, font): '''Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font: font type Returns: None Raises: RuntimeError: Invalid font. ''' fonts = {'brougham': 0, 'lettergothicbold': 1, 'brusselsbit' : 2, 'helsinkibit': 3, 'sandiego': 4, 'lettergothic': 9, 'brusselsoutline': 10, 'helsinkioutline': 11} if font in fonts: if font in ['broughham', 'lettergothicbold', 'brusselsbit', 'helsinkibit', 'sandiego']: self.fonttype = self.font_types['bitmap'] else: self.fonttype = self.font_types['outline'] self.send(chr(27)+'k'+chr(fonts[font])) else: raise RuntimeError('Invalid font in function selectFont')
[ "def", "select_font", "(", "self", ",", "font", ")", ":", "fonts", "=", "{", "'brougham'", ":", "0", ",", "'lettergothicbold'", ":", "1", ",", "'brusselsbit'", ":", "2", ",", "'helsinkibit'", ":", "3", ",", "'sandiego'", ":", "4", ",", "'lettergothic'", ...
Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font: font type Returns: None Raises: RuntimeError: Invalid font.
[ "Select", "font", "type", "Choices", "are", ":", "<Bit", "map", "fonts", ">", "brougham", "lettergothicbold", "brusselsbit", "helsinkibit", "sandiego", "<Outline", "fonts", ">", "lettergothic", "brusselsoutline", "helsinkioutline", "Args", ":", "font", ":", "font", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L669-L708
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.char_style
def char_style(self, style): '''Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style ''' styleset = {'normal': 0, 'outline': 1, 'shadow': 2, 'outlineshadow': 3 } if style in styleset: self.send(chr(27) + 'q' + chr(styleset[style])) else: raise RuntimeError('Invalid character style in function charStyle')
python
def char_style(self, style): '''Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style ''' styleset = {'normal': 0, 'outline': 1, 'shadow': 2, 'outlineshadow': 3 } if style in styleset: self.send(chr(27) + 'q' + chr(styleset[style])) else: raise RuntimeError('Invalid character style in function charStyle')
[ "def", "char_style", "(", "self", ",", "style", ")", ":", "styleset", "=", "{", "'normal'", ":", "0", ",", "'outline'", ":", "1", ",", "'shadow'", ":", "2", ",", "'outlineshadow'", ":", "3", "}", "if", "style", "in", "styleset", ":", "self", ".", "...
Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style
[ "Sets", "the", "character", "style", ".", "Args", ":", "style", ":", "The", "desired", "character", "style", ".", "Choose", "from", "normal", "outline", "shadow", "and", "outlineshadow", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", ...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L710-L728
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.proportional_char
def proportional_char(self, action): '''Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action. ''' actions = {'off': 0, 'on': 1 } if action in actions: self.send(chr(27)+'p'+action) else: raise RuntimeError('Invalid action in function proportionalChar')
python
def proportional_char(self, action): '''Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action. ''' actions = {'off': 0, 'on': 1 } if action in actions: self.send(chr(27)+'p'+action) else: raise RuntimeError('Invalid action in function proportionalChar')
[ "def", "proportional_char", "(", "self", ",", "action", ")", ":", "actions", "=", "{", "'off'", ":", "0", ",", "'on'", ":", "1", "}", "if", "action", "in", "actions", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "'p'", "+", "action"...
Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action.
[ "Specifies", "proportional", "characters", ".", "When", "turned", "on", "the", "character", "spacing", "set", "with", "charSpacing", ".", "Args", ":", "action", ":", "Turn", "proportional", "characters", "on", "or", "off", ".", "Returns", ":", "None", "Raises"...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L766-L783
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.char_spacing
def char_spacing(self, dots): '''Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount. ''' if dots in range(0,127): self.send(chr(27)+chr(32)+chr(dots)) else: raise RuntimeError('Invalid dot amount in function charSpacing')
python
def char_spacing(self, dots): '''Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount. ''' if dots in range(0,127): self.send(chr(27)+chr(32)+chr(dots)) else: raise RuntimeError('Invalid dot amount in function charSpacing')
[ "def", "char_spacing", "(", "self", ",", "dots", ")", ":", "if", "dots", "in", "range", "(", "0", ",", "127", ")", ":", "self", ".", "send", "(", "chr", "(", "27", ")", "+", "chr", "(", "32", ")", "+", "chr", "(", "dots", ")", ")", "else", ...
Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount.
[ "Specifes", "character", "spacing", "in", "dots", ".", "Args", ":", "dots", ":", "the", "character", "spacing", "you", "desire", "in", "dots", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "dot", "amount", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L785-L798
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.barcode
def barcode(self, data, format, characters='off', height=48, width='small', parentheses='on', ratio='3:1', equalize='off', rss_symbol='rss14std', horiz_char_rss=2): '''Print a standard barcode in the specified format Args: data: the barcode data format: the barcode type you want. Choose between code39, itf, ean8/upca, upce, codabar, code128, gs1-128, rss characters: Whether you want characters below the bar code. 'off' or 'on' height: Height, in dots. width: width of barcode. Choose 'xsmall' 'small' 'medium' 'large' parentheses: Parentheses deletion on or off. 'on' or 'off' Only matters with GS1-128 ratio: ratio between thick and thin bars. Choose '3:1', '2.5:1', and '2:1' equalize: equalize bar lengths, choose 'off' or 'on' rss_symbol: rss symbols model, choose from 'rss14std', 'rss14trun', 'rss14stacked', 'rss14stackedomni', 'rsslimited', 'rssexpandedstd', 'rssexpandedstacked' horiz_char_rss: for rss expanded stacked, specify the number of horizontal characters, must be an even number b/w 2 and 20. ''' barcodes = {'code39': '0', 'itf': '1', 'ean8/upca': '5', 'upce': '6', 'codabar': '9', 'code128': 'a', 'gs1-128': 'b', 'rss': 'c'} widths = {'xsmall': '0', 'small': '1', 'medium': '2', 'large': '3'} ratios = {'3:1': '0', '2.5:1': '1', '2:1': '2'} rss_symbols = {'rss14std': '0', 'rss14trun': '1', 'rss14stacked': '2', 'rss14stackedomni' : '3', 'rsslimited': '4', 'rssexpandedstd': '5', 'rssexpandedstacked': '6' } character_choices = {'off': '0', 'on' : '1'} parentheses_choices = {'off':'1', 'on': '0'} equalize_choices = {'off': '0', 'on': '1'} sendstr = '' n2 = height/256 n1 = height%256 if format in barcodes and width in widths and ratio in ratios and characters in character_choices and rss_symbol in rss_symbols: sendstr += (chr(27)+'i'+'t'+barcodes[format]+'s'+'p'+'r'+character_choices[characters]+'u'+'x'+'y'+'h' + chr(n1) + chr(n2) + 'w'+widths[width]+'e'+parentheses_choices[parentheses]+'o'+rss_symbols[rss_symbol]+'c'+chr(horiz_char_rss)+'z'+ratios[ratio]+'f'+equalize_choices[equalize] + 'b' + data + chr(92)) if format in ['code128', 'gs1-128']: sendstr += chr(92)+ chr(92) self.send(sendstr) else: raise RuntimeError('Invalid parameters')
python
def barcode(self, data, format, characters='off', height=48, width='small', parentheses='on', ratio='3:1', equalize='off', rss_symbol='rss14std', horiz_char_rss=2): '''Print a standard barcode in the specified format Args: data: the barcode data format: the barcode type you want. Choose between code39, itf, ean8/upca, upce, codabar, code128, gs1-128, rss characters: Whether you want characters below the bar code. 'off' or 'on' height: Height, in dots. width: width of barcode. Choose 'xsmall' 'small' 'medium' 'large' parentheses: Parentheses deletion on or off. 'on' or 'off' Only matters with GS1-128 ratio: ratio between thick and thin bars. Choose '3:1', '2.5:1', and '2:1' equalize: equalize bar lengths, choose 'off' or 'on' rss_symbol: rss symbols model, choose from 'rss14std', 'rss14trun', 'rss14stacked', 'rss14stackedomni', 'rsslimited', 'rssexpandedstd', 'rssexpandedstacked' horiz_char_rss: for rss expanded stacked, specify the number of horizontal characters, must be an even number b/w 2 and 20. ''' barcodes = {'code39': '0', 'itf': '1', 'ean8/upca': '5', 'upce': '6', 'codabar': '9', 'code128': 'a', 'gs1-128': 'b', 'rss': 'c'} widths = {'xsmall': '0', 'small': '1', 'medium': '2', 'large': '3'} ratios = {'3:1': '0', '2.5:1': '1', '2:1': '2'} rss_symbols = {'rss14std': '0', 'rss14trun': '1', 'rss14stacked': '2', 'rss14stackedomni' : '3', 'rsslimited': '4', 'rssexpandedstd': '5', 'rssexpandedstacked': '6' } character_choices = {'off': '0', 'on' : '1'} parentheses_choices = {'off':'1', 'on': '0'} equalize_choices = {'off': '0', 'on': '1'} sendstr = '' n2 = height/256 n1 = height%256 if format in barcodes and width in widths and ratio in ratios and characters in character_choices and rss_symbol in rss_symbols: sendstr += (chr(27)+'i'+'t'+barcodes[format]+'s'+'p'+'r'+character_choices[characters]+'u'+'x'+'y'+'h' + chr(n1) + chr(n2) + 'w'+widths[width]+'e'+parentheses_choices[parentheses]+'o'+rss_symbols[rss_symbol]+'c'+chr(horiz_char_rss)+'z'+ratios[ratio]+'f'+equalize_choices[equalize] + 'b' + data + chr(92)) if format in ['code128', 'gs1-128']: sendstr += chr(92)+ chr(92) self.send(sendstr) else: raise RuntimeError('Invalid parameters')
[ "def", "barcode", "(", "self", ",", "data", ",", "format", ",", "characters", "=", "'off'", ",", "height", "=", "48", ",", "width", "=", "'small'", ",", "parentheses", "=", "'on'", ",", "ratio", "=", "'3:1'", ",", "equalize", "=", "'off'", ",", "rss_...
Print a standard barcode in the specified format Args: data: the barcode data format: the barcode type you want. Choose between code39, itf, ean8/upca, upce, codabar, code128, gs1-128, rss characters: Whether you want characters below the bar code. 'off' or 'on' height: Height, in dots. width: width of barcode. Choose 'xsmall' 'small' 'medium' 'large' parentheses: Parentheses deletion on or off. 'on' or 'off' Only matters with GS1-128 ratio: ratio between thick and thin bars. Choose '3:1', '2.5:1', and '2:1' equalize: equalize bar lengths, choose 'off' or 'on' rss_symbol: rss symbols model, choose from 'rss14std', 'rss14trun', 'rss14stacked', 'rss14stackedomni', 'rsslimited', 'rssexpandedstd', 'rssexpandedstacked' horiz_char_rss: for rss expanded stacked, specify the number of horizontal characters, must be an even number b/w 2 and 20.
[ "Print", "a", "standard", "barcode", "in", "the", "specified", "format", "Args", ":", "data", ":", "the", "barcode", "data", "format", ":", "the", "barcode", "type", "you", "want", ".", "Choose", "between", "code39", "itf", "ean8", "/", "upca", "upce", "...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L813-L874
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.choose_template
def choose_template(self, template): '''Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None ''' n1 = int(template)/10 n2 = int(template)%10 self.send('^TS'+'0'+str(n1)+str(n2))
python
def choose_template(self, template): '''Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None ''' n1 = int(template)/10 n2 = int(template)%10 self.send('^TS'+'0'+str(n1)+str(n2))
[ "def", "choose_template", "(", "self", ",", "template", ")", ":", "n1", "=", "int", "(", "template", ")", "/", "10", "n2", "=", "int", "(", "template", ")", "%", "10", "self", ".", "send", "(", "'^TS'", "+", "'0'", "+", "str", "(", "n1", ")", "...
Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None
[ "Choose", "a", "template", "Args", ":", "template", ":", "String", "choose", "which", "template", "you", "would", "like", ".", "Returns", ":", "None", "Raises", ":", "None" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L892-L904
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.machine_op
def machine_op(self, operation): '''Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation ''' operations = {'feed2start': 1, 'feedone': 2, 'cut': 3 } if operation in operations: self.send('^'+'O'+'P'+chr(operations[operation])) else: raise RuntimeError('Invalid operation.')
python
def machine_op(self, operation): '''Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation ''' operations = {'feed2start': 1, 'feedone': 2, 'cut': 3 } if operation in operations: self.send('^'+'O'+'P'+chr(operations[operation])) else: raise RuntimeError('Invalid operation.')
[ "def", "machine_op", "(", "self", ",", "operation", ")", ":", "operations", "=", "{", "'feed2start'", ":", "1", ",", "'feedone'", ":", "2", ",", "'cut'", ":", "3", "}", "if", "operation", "in", "operations", ":", "self", ".", "send", "(", "'^'", "+",...
Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation
[ "Perform", "machine", "operations", "Args", ":", "operations", ":", "which", "operation", "you", "would", "like", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "operation" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L906-L924
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.print_start_trigger
def print_start_trigger(self, type): '''Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type. ''' types = {'recieved': 1, 'filled': 2, 'num_recieved': 3} if type in types: self.send('^PT'+chr(types[type])) else: raise RuntimeError('Invalid type.')
python
def print_start_trigger(self, type): '''Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type. ''' types = {'recieved': 1, 'filled': 2, 'num_recieved': 3} if type in types: self.send('^PT'+chr(types[type])) else: raise RuntimeError('Invalid type.')
[ "def", "print_start_trigger", "(", "self", ",", "type", ")", ":", "types", "=", "{", "'recieved'", ":", "1", ",", "'filled'", ":", "2", ",", "'num_recieved'", ":", "3", "}", "if", "type", "in", "types", ":", "self", ".", "send", "(", "'^PT'", "+", ...
Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type.
[ "Set", "print", "start", "trigger", ".", "Args", ":", "type", ":", "The", "type", "of", "trigger", "you", "desire", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Invalid", "type", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L938-L955
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.print_start_command
def print_start_command(self, command): '''Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long. ''' size = len(command) if size > 20: raise RuntimeError('Command too long') n1 = size/10 n2 = size%10 self.send('^PS'+chr(n1)+chr(n2)+command)
python
def print_start_command(self, command): '''Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long. ''' size = len(command) if size > 20: raise RuntimeError('Command too long') n1 = size/10 n2 = size%10 self.send('^PS'+chr(n1)+chr(n2)+command)
[ "def", "print_start_command", "(", "self", ",", "command", ")", ":", "size", "=", "len", "(", "command", ")", "if", "size", ">", "20", ":", "raise", "RuntimeError", "(", "'Command too long'", ")", "n1", "=", "size", "/", "10", "n2", "=", "size", "%", ...
Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long.
[ "Set", "print", "command", "Args", ":", "command", ":", "the", "type", "of", "command", "you", "desire", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Command", "too", "long", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L957-L972
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.received_char_count
def received_char_count(self, count): '''Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None ''' n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send('^PC'+chr(n1)+chr(n2)+chr(n3))
python
def received_char_count(self, count): '''Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None ''' n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send('^PC'+chr(n1)+chr(n2)+chr(n3))
[ "def", "received_char_count", "(", "self", ",", "count", ")", ":", "n1", "=", "count", "/", "100", "n2", "=", "(", "count", "-", "(", "n1", "*", "100", ")", ")", "/", "10", "n3", "=", "(", "count", "-", "(", "(", "n1", "*", "100", ")", "+", ...
Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None
[ "Set", "recieved", "char", "count", "limit", "Args", ":", "count", ":", "the", "amount", "of", "received", "characters", "you", "want", "to", "stop", "at", ".", "Returns", ":", "None", "Raises", ":", "None" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L974-L987
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.select_delim
def select_delim(self, delim): '''Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long. ''' size = len(delim) if size > 20: raise RuntimeError('Delimeter too long') n1 = size/10 n2 = size%10 self.send('^SS'+chr(n1)+chr(n2))
python
def select_delim(self, delim): '''Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long. ''' size = len(delim) if size > 20: raise RuntimeError('Delimeter too long') n1 = size/10 n2 = size%10 self.send('^SS'+chr(n1)+chr(n2))
[ "def", "select_delim", "(", "self", ",", "delim", ")", ":", "size", "=", "len", "(", "delim", ")", "if", "size", ">", "20", ":", "raise", "RuntimeError", "(", "'Delimeter too long'", ")", "n1", "=", "size", "/", "10", "n2", "=", "size", "%", "10", ...
Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long.
[ "Select", "desired", "delimeter", "Args", ":", "delim", ":", "The", "delimeter", "character", "you", "want", ".", "Returns", ":", "None", "Raises", ":", "RuntimeError", ":", "Delimeter", "too", "long", "." ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L989-L1004
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.insert_into_obj
def insert_into_obj(self, data): '''Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None ''' if not data: data = '' size = len(data) n1 = size%256 n2 = size/256 self.send('^DI'+chr(n1)+chr(n2)+data)
python
def insert_into_obj(self, data): '''Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None ''' if not data: data = '' size = len(data) n1 = size%256 n2 = size/256 self.send('^DI'+chr(n1)+chr(n2)+data)
[ "def", "insert_into_obj", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "data", "=", "''", "size", "=", "len", "(", "data", ")", "n1", "=", "size", "%", "256", "n2", "=", "size", "/", "256", "self", ".", "send", "(", "'^DI'", "+...
Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None
[ "Insert", "text", "into", "selected", "object", ".", "Args", ":", "data", ":", "The", "data", "you", "want", "to", "insert", ".", "Returns", ":", "None", "Raises", ":", "None" ]
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L1018-L1034
fozzle/python-brotherprint
brotherprint/brotherprint.py
BrotherPrint.select_and_insert
def select_and_insert(self, name, data): '''Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None ''' self.select_obj(name) self.insert_into_obj(data)
python
def select_and_insert(self, name, data): '''Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None ''' self.select_obj(name) self.insert_into_obj(data)
[ "def", "select_and_insert", "(", "self", ",", "name", ",", "data", ")", ":", "self", ".", "select_obj", "(", "name", ")", "self", ".", "insert_into_obj", "(", "data", ")" ]
Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None
[ "Combines", "selection", "and", "data", "insertion", "into", "one", "function", "Args", ":", "name", ":", "the", "name", "of", "the", "object", "you", "want", "to", "insert", "into", "data", ":", "the", "data", "you", "want", "to", "insert", "Returns", "...
train
https://github.com/fozzle/python-brotherprint/blob/5fb92df11b599c30a7da3d6ac7ed60acff230044/brotherprint/brotherprint.py#L1036-L1048
openvax/datacache
datacache/database_helpers.py
connect_if_correct_version
def connect_if_correct_version(db_path, version): """Return a sqlite3 database connection if the version in the database's metadata matches the version argument. Also implicitly checks for whether the data in this database has been completely filled, since we set the version last. TODO: Make an explicit 'complete' flag to the metadata. """ db = Database(db_path) if db.has_version() and db.version() == version: return db.connection return None
python
def connect_if_correct_version(db_path, version): """Return a sqlite3 database connection if the version in the database's metadata matches the version argument. Also implicitly checks for whether the data in this database has been completely filled, since we set the version last. TODO: Make an explicit 'complete' flag to the metadata. """ db = Database(db_path) if db.has_version() and db.version() == version: return db.connection return None
[ "def", "connect_if_correct_version", "(", "db_path", ",", "version", ")", ":", "db", "=", "Database", "(", "db_path", ")", "if", "db", ".", "has_version", "(", ")", "and", "db", ".", "version", "(", ")", "==", "version", ":", "return", "db", ".", "conn...
Return a sqlite3 database connection if the version in the database's metadata matches the version argument. Also implicitly checks for whether the data in this database has been completely filled, since we set the version last. TODO: Make an explicit 'complete' flag to the metadata.
[ "Return", "a", "sqlite3", "database", "connection", "if", "the", "version", "in", "the", "database", "s", "metadata", "matches", "the", "version", "argument", "." ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L37-L49
openvax/datacache
datacache/database_helpers.py
_create_cached_db
def _create_cached_db( db_path, tables, version=1): """ Either create or retrieve sqlite database. Parameters -------- db_path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache.DatabaseTable objects version : int, optional Version acceptable as cached data. Returns sqlite3 connection """ require_string(db_path, "db_path") require_iterable_of(tables, DatabaseTable) require_integer(version, "version") # if the database file doesn't already exist and we encounter an error # later, delete the file before raising an exception delete_on_error = not exists(db_path) # if the database already exists, contains all the table # names and has the right version, then just return it db = Database(db_path) # make sure to delete the database file in case anything goes wrong # to avoid leaving behind an empty DB table_names = [table.name for table in tables] try: if db.has_tables(table_names) and \ db.has_version() and \ db.version() == version: logger.info("Found existing table in database %s", db_path) else: if len(db.table_names()) > 0: logger.info( "Dropping tables from database %s: %s", db_path, ", ".join(db.table_names())) db.drop_all_tables() logger.info( "Creating database %s containing: %s", db_path, ", ".join(table_names)) db.create(tables, version) except: logger.warning( "Failed to create tables %s in database %s", table_names, db_path) db.close() if delete_on_error: remove(db_path) raise return db.connection
python
def _create_cached_db( db_path, tables, version=1): """ Either create or retrieve sqlite database. Parameters -------- db_path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache.DatabaseTable objects version : int, optional Version acceptable as cached data. Returns sqlite3 connection """ require_string(db_path, "db_path") require_iterable_of(tables, DatabaseTable) require_integer(version, "version") # if the database file doesn't already exist and we encounter an error # later, delete the file before raising an exception delete_on_error = not exists(db_path) # if the database already exists, contains all the table # names and has the right version, then just return it db = Database(db_path) # make sure to delete the database file in case anything goes wrong # to avoid leaving behind an empty DB table_names = [table.name for table in tables] try: if db.has_tables(table_names) and \ db.has_version() and \ db.version() == version: logger.info("Found existing table in database %s", db_path) else: if len(db.table_names()) > 0: logger.info( "Dropping tables from database %s: %s", db_path, ", ".join(db.table_names())) db.drop_all_tables() logger.info( "Creating database %s containing: %s", db_path, ", ".join(table_names)) db.create(tables, version) except: logger.warning( "Failed to create tables %s in database %s", table_names, db_path) db.close() if delete_on_error: remove(db_path) raise return db.connection
[ "def", "_create_cached_db", "(", "db_path", ",", "tables", ",", "version", "=", "1", ")", ":", "require_string", "(", "db_path", ",", "\"db_path\"", ")", "require_iterable_of", "(", "tables", ",", "DatabaseTable", ")", "require_integer", "(", "version", ",", "...
Either create or retrieve sqlite database. Parameters -------- db_path : str Path to sqlite3 database file tables : dict Dictionary mapping table names to datacache.DatabaseTable objects version : int, optional Version acceptable as cached data. Returns sqlite3 connection
[ "Either", "create", "or", "retrieve", "sqlite", "database", "." ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L51-L112
openvax/datacache
datacache/database_helpers.py
build_tables
def build_tables( table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}): """ Parameters ---------- table_names_to_dataframes : dict Dictionary mapping each table name to a DataFrame table_names_to_primary_keys : dict Dictionary mapping each table to its primary key table_names_to_indices : dict Dictionary mapping each table to a set of indices Returns list of DatabaseTable objects """ tables = [] for table_name, df in table_names_to_dataframes.items(): table_indices = table_names_to_indices.get(table_name, []) primary_key = table_names_to_primary_keys.get(table_name) table = DatabaseTable.from_dataframe( name=table_name, df=df, indices=table_indices, primary_key=primary_key) tables.append(table) return tables
python
def build_tables( table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}): """ Parameters ---------- table_names_to_dataframes : dict Dictionary mapping each table name to a DataFrame table_names_to_primary_keys : dict Dictionary mapping each table to its primary key table_names_to_indices : dict Dictionary mapping each table to a set of indices Returns list of DatabaseTable objects """ tables = [] for table_name, df in table_names_to_dataframes.items(): table_indices = table_names_to_indices.get(table_name, []) primary_key = table_names_to_primary_keys.get(table_name) table = DatabaseTable.from_dataframe( name=table_name, df=df, indices=table_indices, primary_key=primary_key) tables.append(table) return tables
[ "def", "build_tables", "(", "table_names_to_dataframes", ",", "table_names_to_primary_keys", "=", "{", "}", ",", "table_names_to_indices", "=", "{", "}", ")", ":", "tables", "=", "[", "]", "for", "table_name", ",", "df", "in", "table_names_to_dataframes", ".", "...
Parameters ---------- table_names_to_dataframes : dict Dictionary mapping each table name to a DataFrame table_names_to_primary_keys : dict Dictionary mapping each table to its primary key table_names_to_indices : dict Dictionary mapping each table to a set of indices Returns list of DatabaseTable objects
[ "Parameters", "----------", "table_names_to_dataframes", ":", "dict", "Dictionary", "mapping", "each", "table", "name", "to", "a", "DataFrame" ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L114-L142
openvax/datacache
datacache/database_helpers.py
db_from_dataframes_with_absolute_path
def db_from_dataframes_with_absolute_path( db_path, table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_path : str Path to database file to create table_names_to_dataframes : dict Dictionary from table names to DataFrame objects table_names_to_primary_keys : dict, optional Name of primary key column for each table table_names_to_indices : dict, optional Dictionary from table names to list of column name tuples overwrite : bool, optional If the database already exists, overwrite it? version : int, optional """ if overwrite and exists(db_path): remove(db_path) tables = build_tables( table_names_to_dataframes, table_names_to_primary_keys, table_names_to_indices) return _create_cached_db( db_path, tables=tables, version=version)
python
def db_from_dataframes_with_absolute_path( db_path, table_names_to_dataframes, table_names_to_primary_keys={}, table_names_to_indices={}, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_path : str Path to database file to create table_names_to_dataframes : dict Dictionary from table names to DataFrame objects table_names_to_primary_keys : dict, optional Name of primary key column for each table table_names_to_indices : dict, optional Dictionary from table names to list of column name tuples overwrite : bool, optional If the database already exists, overwrite it? version : int, optional """ if overwrite and exists(db_path): remove(db_path) tables = build_tables( table_names_to_dataframes, table_names_to_primary_keys, table_names_to_indices) return _create_cached_db( db_path, tables=tables, version=version)
[ "def", "db_from_dataframes_with_absolute_path", "(", "db_path", ",", "table_names_to_dataframes", ",", "table_names_to_primary_keys", "=", "{", "}", ",", "table_names_to_indices", "=", "{", "}", ",", "overwrite", "=", "False", ",", "version", "=", "1", ")", ":", "...
Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_path : str Path to database file to create table_names_to_dataframes : dict Dictionary from table names to DataFrame objects table_names_to_primary_keys : dict, optional Name of primary key column for each table table_names_to_indices : dict, optional Dictionary from table names to list of column name tuples overwrite : bool, optional If the database already exists, overwrite it? version : int, optional
[ "Create", "a", "sqlite3", "database", "from", "a", "collection", "of", "DataFrame", "objects" ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L144-L183
openvax/datacache
datacache/database_helpers.py
db_from_dataframes
def db_from_dataframes( db_filename, dataframes, primary_keys={}, indices={}, subdir=None, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_filename : str Name of database file to create dataframes : dict Dictionary from table names to DataFrame objects primary_keys : dict, optional Name of primary key column for each table indices : dict, optional Dictionary from table names to list of column name tuples subdir : str, optional overwrite : bool, optional If the database already exists, overwrite it? version : int, optional """ if not (subdir is None or isinstance(subdir, str)): raise TypeError("Expected subdir to be None or str, got %s : %s" % ( subdir, type(subdir))) db_path = build_path(db_filename, subdir) return db_from_dataframes_with_absolute_path( db_path, table_names_to_dataframes=dataframes, table_names_to_primary_keys=primary_keys, table_names_to_indices=indices, overwrite=overwrite, version=version)
python
def db_from_dataframes( db_filename, dataframes, primary_keys={}, indices={}, subdir=None, overwrite=False, version=1): """ Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_filename : str Name of database file to create dataframes : dict Dictionary from table names to DataFrame objects primary_keys : dict, optional Name of primary key column for each table indices : dict, optional Dictionary from table names to list of column name tuples subdir : str, optional overwrite : bool, optional If the database already exists, overwrite it? version : int, optional """ if not (subdir is None or isinstance(subdir, str)): raise TypeError("Expected subdir to be None or str, got %s : %s" % ( subdir, type(subdir))) db_path = build_path(db_filename, subdir) return db_from_dataframes_with_absolute_path( db_path, table_names_to_dataframes=dataframes, table_names_to_primary_keys=primary_keys, table_names_to_indices=indices, overwrite=overwrite, version=version)
[ "def", "db_from_dataframes", "(", "db_filename", ",", "dataframes", ",", "primary_keys", "=", "{", "}", ",", "indices", "=", "{", "}", ",", "subdir", "=", "None", ",", "overwrite", "=", "False", ",", "version", "=", "1", ")", ":", "if", "not", "(", "...
Create a sqlite3 database from a collection of DataFrame objects Parameters ---------- db_filename : str Name of database file to create dataframes : dict Dictionary from table names to DataFrame objects primary_keys : dict, optional Name of primary key column for each table indices : dict, optional Dictionary from table names to list of column name tuples subdir : str, optional overwrite : bool, optional If the database already exists, overwrite it? version : int, optional
[ "Create", "a", "sqlite3", "database", "from", "a", "collection", "of", "DataFrame", "objects" ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L185-L227
openvax/datacache
datacache/database_helpers.py
db_from_dataframe
def db_from_dataframe( db_filename, table_name, df, primary_key=None, subdir=None, overwrite=False, indices=(), version=1): """ Given a dataframe `df`, turn it into a sqlite3 database. Store values in a table called `table_name`. Returns full path to the sqlite database file. """ return db_from_dataframes( db_filename=db_filename, dataframes={table_name: df}, primary_keys={table_name: primary_key}, indices={table_name: indices}, subdir=subdir, overwrite=overwrite, version=version)
python
def db_from_dataframe( db_filename, table_name, df, primary_key=None, subdir=None, overwrite=False, indices=(), version=1): """ Given a dataframe `df`, turn it into a sqlite3 database. Store values in a table called `table_name`. Returns full path to the sqlite database file. """ return db_from_dataframes( db_filename=db_filename, dataframes={table_name: df}, primary_keys={table_name: primary_key}, indices={table_name: indices}, subdir=subdir, overwrite=overwrite, version=version)
[ "def", "db_from_dataframe", "(", "db_filename", ",", "table_name", ",", "df", ",", "primary_key", "=", "None", ",", "subdir", "=", "None", ",", "overwrite", "=", "False", ",", "indices", "=", "(", ")", ",", "version", "=", "1", ")", ":", "return", "db_...
Given a dataframe `df`, turn it into a sqlite3 database. Store values in a table called `table_name`. Returns full path to the sqlite database file.
[ "Given", "a", "dataframe", "df", "turn", "it", "into", "a", "sqlite3", "database", ".", "Store", "values", "in", "a", "table", "called", "table_name", "." ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L229-L251
openvax/datacache
datacache/database_helpers.py
_db_filename_from_dataframe
def _db_filename_from_dataframe(base_filename, df): """ Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types. """ db_filename = base_filename + ("_nrows%d" % len(df)) for column_name in df.columns: column_db_type = db_type(df[column_name].dtype) column_name = column_name.replace(" ", "_") db_filename += ".%s_%s" % (column_name, column_db_type) return db_filename + ".db"
python
def _db_filename_from_dataframe(base_filename, df): """ Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types. """ db_filename = base_filename + ("_nrows%d" % len(df)) for column_name in df.columns: column_db_type = db_type(df[column_name].dtype) column_name = column_name.replace(" ", "_") db_filename += ".%s_%s" % (column_name, column_db_type) return db_filename + ".db"
[ "def", "_db_filename_from_dataframe", "(", "base_filename", ",", "df", ")", ":", "db_filename", "=", "base_filename", "+", "(", "\"_nrows%d\"", "%", "len", "(", "df", ")", ")", "for", "column_name", "in", "df", ".", "columns", ":", "column_db_type", "=", "db...
Generate database filename for a sqlite3 database we're going to fill with the contents of a DataFrame, using the DataFrame's column names and types.
[ "Generate", "database", "filename", "for", "a", "sqlite3", "database", "we", "re", "going", "to", "fill", "with", "the", "contents", "of", "a", "DataFrame", "using", "the", "DataFrame", "s", "column", "names", "and", "types", "." ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L254-L265
openvax/datacache
datacache/database_helpers.py
fetch_csv_db
def fetch_csv_db( table_name, download_url, csv_filename=None, db_filename=None, subdir=None, version=1, **pandas_kwargs): """ Download a remote CSV file and create a local sqlite3 database from its contents """ df = fetch_csv_dataframe( download_url=download_url, filename=csv_filename, subdir=subdir, **pandas_kwargs) base_filename = splitext(csv_filename)[0] if db_filename is None: db_filename = _db_filename_from_dataframe(base_filename, df) return db_from_dataframe( db_filename, table_name, df, subdir=subdir, version=version)
python
def fetch_csv_db( table_name, download_url, csv_filename=None, db_filename=None, subdir=None, version=1, **pandas_kwargs): """ Download a remote CSV file and create a local sqlite3 database from its contents """ df = fetch_csv_dataframe( download_url=download_url, filename=csv_filename, subdir=subdir, **pandas_kwargs) base_filename = splitext(csv_filename)[0] if db_filename is None: db_filename = _db_filename_from_dataframe(base_filename, df) return db_from_dataframe( db_filename, table_name, df, subdir=subdir, version=version)
[ "def", "fetch_csv_db", "(", "table_name", ",", "download_url", ",", "csv_filename", "=", "None", ",", "db_filename", "=", "None", ",", "subdir", "=", "None", ",", "version", "=", "1", ",", "*", "*", "pandas_kwargs", ")", ":", "df", "=", "fetch_csv_datafram...
Download a remote CSV file and create a local sqlite3 database from its contents
[ "Download", "a", "remote", "CSV", "file", "and", "create", "a", "local", "sqlite3", "database", "from", "its", "contents" ]
train
https://github.com/openvax/datacache/blob/73bcac02d37cf153710a07fbdc636aa55cb214ca/datacache/database_helpers.py#L267-L292
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance.get_all
def get_all(self, security): """ Get all available quote data for the given ticker security. Returns a dictionary. """ url = 'http://www.google.com/finance?q=%s' % security page = self._request(url) soup = BeautifulSoup(page) snapData = soup.find("table", {"class": "snap-data"}) if snapData is None: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) data = {} for row in snapData.findAll('tr'): keyTd, valTd = row.findAll('td') data[keyTd.getText()] = valTd.getText() return data
python
def get_all(self, security): """ Get all available quote data for the given ticker security. Returns a dictionary. """ url = 'http://www.google.com/finance?q=%s' % security page = self._request(url) soup = BeautifulSoup(page) snapData = soup.find("table", {"class": "snap-data"}) if snapData is None: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) data = {} for row in snapData.findAll('tr'): keyTd, valTd = row.findAll('td') data[keyTd.getText()] = valTd.getText() return data
[ "def", "get_all", "(", "self", ",", "security", ")", ":", "url", "=", "'http://www.google.com/finance?q=%s'", "%", "security", "page", "=", "self", ".", "_request", "(", "url", ")", "soup", "=", "BeautifulSoup", "(", "page", ")", "snapData", "=", "soup", "...
Get all available quote data for the given ticker security. Returns a dictionary.
[ "Get", "all", "available", "quote", "data", "for", "the", "given", "ticker", "security", ".", "Returns", "a", "dictionary", "." ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L41-L58
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance.quotes
def quotes(self, security, start, end): """ Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list. """ try: url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (security.symbol, start, end) try: page = self._request(url) except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep days = page.readlines() values = [day.split(',') for day in days] # sample values:[['Date', 'Open', 'High', 'Low', 'Close', 'Volume'], \ # ['2009-12-31', '112.77', '112.80', '111.39', '111.44', '90637900']...] for value in values[1:]: date = convertGoogCSVDate(value[0]) try: yield Quote(date, value[1].strip(), value[2].strip(), value[3].strip(), value[4].strip(), value[5].strip(), None) except Exception: LOG.warning("Exception when processing %s at date %s for value %s" % (security, date, value)) except BaseException: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc())
python
def quotes(self, security, start, end): """ Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list. """ try: url = 'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv' % (security.symbol, start, end) try: page = self._request(url) except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep days = page.readlines() values = [day.split(',') for day in days] # sample values:[['Date', 'Open', 'High', 'Low', 'Close', 'Volume'], \ # ['2009-12-31', '112.77', '112.80', '111.39', '111.44', '90637900']...] for value in values[1:]: date = convertGoogCSVDate(value[0]) try: yield Quote(date, value[1].strip(), value[2].strip(), value[3].strip(), value[4].strip(), value[5].strip(), None) except Exception: LOG.warning("Exception when processing %s at date %s for value %s" % (security, date, value)) except BaseException: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc())
[ "def", "quotes", "(", "self", ",", "security", ",", "start", ",", "end", ")", ":", "try", ":", "url", "=", "'http://www.google.com/finance/historical?q=%s&startdate=%s&enddate=%s&output=csv'", "%", "(", "security", ".", "symbol", ",", "start", ",", "end", ")", "...
Get historical prices for the given ticker security. Date format is 'YYYYMMDD' Returns a nested list.
[ "Get", "historical", "prices", "for", "the", "given", "ticker", "security", ".", "Date", "format", "is", "YYYYMMDD", "Returns", "a", "nested", "list", "." ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L60-L95
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance.financials
def financials(self, security): """ get financials: google finance provide annual and quanter financials, if annual is true, we will use annual data Up to four lastest year/quanter data will be provided by google Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii """ try: url = 'http://www.google.com/finance?q=%s&fstype=ii' % security try: page = self._request(url).read() except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep bPage = BeautifulSoup(page) target = bPage.find(id='incinterimdiv') keyTimeValue = {} # ugly do...while i = 0 while True: self._parseTarget(target, keyTimeValue) if i < 5: i += 1 target = target.nextSibling # ugly beautiful soap... if '\n' == target: target = target.nextSibling else: break return keyTimeValue except BaseException: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc())
python
def financials(self, security): """ get financials: google finance provide annual and quanter financials, if annual is true, we will use annual data Up to four lastest year/quanter data will be provided by google Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii """ try: url = 'http://www.google.com/finance?q=%s&fstype=ii' % security try: page = self._request(url).read() except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep bPage = BeautifulSoup(page) target = bPage.find(id='incinterimdiv') keyTimeValue = {} # ugly do...while i = 0 while True: self._parseTarget(target, keyTimeValue) if i < 5: i += 1 target = target.nextSibling # ugly beautiful soap... if '\n' == target: target = target.nextSibling else: break return keyTimeValue except BaseException: raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in GoogleFinance.getHistoricalPrices %s" % traceback.format_exc())
[ "def", "financials", "(", "self", ",", "security", ")", ":", "try", ":", "url", "=", "'http://www.google.com/finance?q=%s&fstype=ii'", "%", "security", "try", ":", "page", "=", "self", ".", "_request", "(", "url", ")", ".", "read", "(", ")", "except", "UfE...
get financials: google finance provide annual and quanter financials, if annual is true, we will use annual data Up to four lastest year/quanter data will be provided by google Refer to page as an example: http://www.google.com/finance?q=TSE:CVG&fstype=ii
[ "get", "financials", ":", "google", "finance", "provide", "annual", "and", "quanter", "financials", "if", "annual", "is", "true", "we", "will", "use", "annual", "data", "Up", "to", "four", "lastest", "year", "/", "quanter", "data", "will", "be", "provided", ...
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L99-L137
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance._parseTarget
def _parseTarget(self, target, keyTimeValue): ''' parse table for get financial ''' table = target.table timestamps = self._getTimeStamps(table) for tr in table.tbody.findChildren('tr'): for i, td in enumerate(tr.findChildren('td')): if 0 == i: key = td.getText() if key not in keyTimeValue: keyTimeValue[key] = {} else: keyTimeValue[key][timestamps[i - 1]] = self._getValue(td)
python
def _parseTarget(self, target, keyTimeValue): ''' parse table for get financial ''' table = target.table timestamps = self._getTimeStamps(table) for tr in table.tbody.findChildren('tr'): for i, td in enumerate(tr.findChildren('td')): if 0 == i: key = td.getText() if key not in keyTimeValue: keyTimeValue[key] = {} else: keyTimeValue[key][timestamps[i - 1]] = self._getValue(td)
[ "def", "_parseTarget", "(", "self", ",", "target", ",", "keyTimeValue", ")", ":", "table", "=", "target", ".", "table", "timestamps", "=", "self", ".", "_getTimeStamps", "(", "table", ")", "for", "tr", "in", "table", ".", "tbody", ".", "findChildren", "(...
parse table for get financial
[ "parse", "table", "for", "get", "financial" ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L139-L151
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance._getTimeStamps
def _getTimeStamps(self, table): ''' get time stamps ''' timeStamps = [] for th in table.thead.tr.contents: if '\n' != th: timeStamps.append(th.getText()) return timeStamps[1:]
python
def _getTimeStamps(self, table): ''' get time stamps ''' timeStamps = [] for th in table.thead.tr.contents: if '\n' != th: timeStamps.append(th.getText()) return timeStamps[1:]
[ "def", "_getTimeStamps", "(", "self", ",", "table", ")", ":", "timeStamps", "=", "[", "]", "for", "th", "in", "table", ".", "thead", ".", "tr", ".", "contents", ":", "if", "'\\n'", "!=", "th", ":", "timeStamps", ".", "append", "(", "th", ".", "getT...
get time stamps
[ "get", "time", "stamps" ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L153-L160
llazzaro/analyzerdam
analyzerdam/google_finance.py
GoogleFinance.ticks
def ticks(self, security, start, end): """ Get tick prices for the given ticker security. @security: stock security @interval: interval in mins(google finance only support query till 1 min) @start: start date(YYYYMMDD) @end: end date(YYYYMMDD) start and end is disabled since only 15 days data will show @Returns a nested list. """ period = 1 # url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (security, interval, period, start) url = 'http://www.google.com/finance/getprices?q=%s&i=61&p=%sd&f=d,o,h,l,c,v' % (security.symbol, period) LOG.debug('fetching {0}'.format(url)) try: response = self._request(url) except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep # use csv reader here days = response.text.split('\n')[7:] # first 7 line is document # sample values:'a1316784600,31.41,31.5,31.4,31.43,150911' values = [day.split(',') for day in days if len(day.split(',')) >= 6] for value in values: yield json.dumps({'date': value[0][1:].strip(), 'close': value[1].strip(), 'high': value[2].strip(), 'low': value[3].strip(), 'open': value[4].strip(), 'volume': value[5].strip()})
python
def ticks(self, security, start, end): """ Get tick prices for the given ticker security. @security: stock security @interval: interval in mins(google finance only support query till 1 min) @start: start date(YYYYMMDD) @end: end date(YYYYMMDD) start and end is disabled since only 15 days data will show @Returns a nested list. """ period = 1 # url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (security, interval, period, start) url = 'http://www.google.com/finance/getprices?q=%s&i=61&p=%sd&f=d,o,h,l,c,v' % (security.symbol, period) LOG.debug('fetching {0}'.format(url)) try: response = self._request(url) except UfException as ufExcep: # if symol is not right, will get 400 if Errors.NETWORK_400_ERROR == ufExcep.getCode: raise UfException(Errors.STOCK_SYMBOL_ERROR, "Can find data for stock %s, security error?" % security) raise ufExcep # use csv reader here days = response.text.split('\n')[7:] # first 7 line is document # sample values:'a1316784600,31.41,31.5,31.4,31.43,150911' values = [day.split(',') for day in days if len(day.split(',')) >= 6] for value in values: yield json.dumps({'date': value[0][1:].strip(), 'close': value[1].strip(), 'high': value[2].strip(), 'low': value[3].strip(), 'open': value[4].strip(), 'volume': value[5].strip()})
[ "def", "ticks", "(", "self", ",", "security", ",", "start", ",", "end", ")", ":", "period", "=", "1", "# url = 'http://www.google.com/finance/getprices?q=%s&i=%s&p=%sd&f=d,o,h,l,c,v&ts=%s' % (security, interval, period, start)\r", "url", "=", "'http://www.google.com/finance/getpr...
Get tick prices for the given ticker security. @security: stock security @interval: interval in mins(google finance only support query till 1 min) @start: start date(YYYYMMDD) @end: end date(YYYYMMDD) start and end is disabled since only 15 days data will show @Returns a nested list.
[ "Get", "tick", "prices", "for", "the", "given", "ticker", "security", "." ]
train
https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/google_finance.py#L168-L202
pudo/jsongraph
jsongraph/common.py
GraphOperations.get_binding
def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF terms matching that schema. """ schema = self.parent.get_schema(schema) return Binding(schema, self.parent.resolver, data=data)
python
def get_binding(self, schema, data): """ For a given schema, get a binding mediator providing links to the RDF terms matching that schema. """ schema = self.parent.get_schema(schema) return Binding(schema, self.parent.resolver, data=data)
[ "def", "get_binding", "(", "self", ",", "schema", ",", "data", ")", ":", "schema", "=", "self", ".", "parent", ".", "get_schema", "(", "schema", ")", "return", "Binding", "(", "schema", ",", "self", ".", "parent", ".", "resolver", ",", "data", "=", "...
For a given schema, get a binding mediator providing links to the RDF terms matching that schema.
[ "For", "a", "given", "schema", "get", "a", "binding", "mediator", "providing", "links", "to", "the", "RDF", "terms", "matching", "that", "schema", "." ]
train
https://github.com/pudo/jsongraph/blob/35e4f397dbe69cd5553cf9cb9ab98859c3620f03/jsongraph/common.py#L11-L15