INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Set the brightness level for the entire display
def set_brightness(self, brightness): """ Set the brightness level for the entire display @param brightness: brightness level (0 -15) """ if brightness > 15: brightness = 15 brightness |= 0xE0 self.brightness = brightness self.firmata.i2c_write...
Populate the bit map with the supplied shape and color and then write the entire bitmap to the display
def set_bit_map(self, shape, color): """ Populate the bit map with the supplied "shape" and color and then write the entire bitmap to the display @param shape: pattern to display @param color: color for the pattern """ for row in range(0, 8): data = sh...
Write the entire buffer to the display
def output_entire_buffer(self): """ Write the entire buffer to the display """ green = 0 red = 0 for row in range(0, 8): for col in range(0, 8): if self.display_buffer[row][col] == self.LED_GREEN: green |= 1 << col ...
Set all led s to off.
def clear_display_buffer(self): """ Set all led's to off. """ for row in range(0, 8): self.firmata.i2c_write(0x70, row * 2, 0, 0) self.firmata.i2c_write(0x70, (row * 2) + 1, 0, 0) for column in range(0, 8): self.display_buffer[row][col...
This method will allow up to 30 seconds for discovery ( communicating with ) an Arduino board and then will determine a pin configuration table for the board.: return: True if board is successfully discovered or False upon timeout
def auto_discover_board(self, verbose): """ This method will allow up to 30 seconds for discovery (communicating with) an Arduino board and then will determine a pin configuration table for the board. :return: True if board is successfully discovered or False upon timeout """ ...
This method processes the report version message sent asynchronously by Firmata when it starts up or after refresh_report_version () is called
def report_version(self, data): """ This method processes the report version message, sent asynchronously by Firmata when it starts up or after refresh_report_version() is called Use the api method api_get_version to retrieve this information :param data: Message data ...
This method arms a pin to allow data latching for the pin.
def set_analog_latch(self, pin, threshold_type, threshold_value, cb): """ This method "arms" a pin to allow data latching for the pin. :param pin: Analog pin number (value following an 'A' designator, i.e. A5 = 5 :param threshold_type: ANALOG_LATCH_GT | ANALOG_LATCH_LT | ANALOG_LATCH_...
This method arms a pin to allow data latching for the pin.
def set_digital_latch(self, pin, threshold_type, cb): """ This method "arms" a pin to allow data latching for the pin. :param pin: digital pin number :param threshold_type: DIGITAL_LATCH_HIGH | DIGITAL_LATCH_LOW :param cb: User provided callback function """ wi...
This method reads the analog latch table for the specified pin and returns a list that contains: [ latch_state latched_data and time_stamp ]. If the latch state is latched the entry in the table is cleared
def get_analog_latch_data(self, pin): """ This method reads the analog latch table for the specified pin and returns a list that contains: [latch_state, latched_data, and time_stamp]. If the latch state is latched, the entry in the table is cleared :param pin: pin number ...
This method reads the digital latch table for the specified pin and returns a list that contains: [ latch_state latched_data and time_stamp ]. If the latch state is latched the entry in the table is cleared
def get_digital_latch_data(self, pin): """ This method reads the digital latch table for the specified pin and returns a list that contains: [latch_state, latched_data, and time_stamp]. If the latch state is latched, the entry in the table is cleared :param pin: pin number ...
This method processes the report firmware message sent asynchronously by Firmata when it starts up or after refresh_report_firmware () is called Use the api method api_get_firmware_version to retrieve this information
def report_firmware(self, data): """ This method processes the report firmware message, sent asynchronously by Firmata when it starts up or after refresh_report_firmware() is called Use the api method api_get_firmware_version to retrieve this information :param data: M...
This method handles the incoming analog data message. It stores the data value for the pin in the analog response table. If a callback function was associated with this pin the callback function is invoked. This method also checks to see if latching was requested for the pin. If the latch criteria was met the latching ...
def analog_message(self, data): """ This method handles the incoming analog data message. It stores the data value for the pin in the analog response table. If a callback function was associated with this pin, the callback function is invoked. This method also checks to see if la...
This method handles the incoming digital message. It stores the data values in the digital response table. Data is stored for all 8 bits of a digital port
def digital_message(self, data): """ This method handles the incoming digital message. It stores the data values in the digital response table. Data is stored for all 8 bits of a digital port :param data: Message data from Firmata :return: No return value. """ ...
This method handles the incoming encoder data message and stores the data in the digital response table.
def encoder_data(self, data): """ This method handles the incoming encoder data message and stores the data in the digital response table. :param data: Message data from Firmata :return: No return value. """ prev_val = self.digital_response_table[data[self.RESPO...
This method handles the incoming sonar data message and stores the data in the response table.
def sonar_data(self, data): """ This method handles the incoming sonar data message and stores the data in the response table. :param data: Message data from Firmata :return: No return value. """ val = int((data[self.MSB] << 7) + data[self.LSB]) pin_numb...
This method will send a Sysex command to Firmata with any accompanying data
def send_sysex(self, sysex_command, sysex_data=None): """ This method will send a Sysex command to Firmata with any accompanying data :param sysex_command: sysex command :param sysex_data: data for command :return : No return value. """ if not sysex_data: ...
This method is used to transmit a non - sysex command.
def send_command(self, command): """ This method is used to transmit a non-sysex command. :param command: Command to send to firmata includes command + data formatted by caller :return : No return value. """ send_message = "" for i in command: send_m...
Send the reset command to the Arduino. It resets the response tables to their initial values
def system_reset(self): """ Send the reset command to the Arduino. It resets the response tables to their initial values :return: No return value """ data = chr(self.SYSTEM_RESET) self.pymata.transport.write(data) # response table re-initialization ...
This method handles the incoming string data message from Firmata. The string is printed to the console
def _string_data(self, data): """ This method handles the incoming string data message from Firmata. The string is printed to the console :param data: Message data from Firmata :return: No return value.s """ print("_string_data:") string_to_print = [] ...
This method receives replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data is retrieved via a call to i2c_get_read_data () in pymata. py It a callback was specified in pymata. i2c_read the raw data is sent through the callback
def i2c_reply(self, data): """ This method receives replies to i2c_read requests. It stores the data for each i2c device address in a dictionary called i2c_map. The data is retrieved via a call to i2c_get_read_data() in pymata.py It a callback was specified in pymata.i2c_read, th...
This method starts the thread that continuously runs to receive and interpret messages coming from Firmata. This must be the last method in this file It also checks the deque for messages to be sent to Firmata.
def run(self): """ This method starts the thread that continuously runs to receive and interpret messages coming from Firmata. This must be the last method in this file It also checks the deque for messages to be sent to Firmata. """ # To add a command to the command disp...
Use requests to fetch remote content
def retrieve_url(self, url): """ Use requests to fetch remote content """ try: r = requests.get(url) except requests.ConnectionError: raise exceptions.RetrieveError('Connection fail') if r.status_code >= 400: raise exceptions.Retrieve...
Use BeautifulSoup to parse HTML/ XML http:// www. crummy. com/ software/ BeautifulSoup/ bs4/ doc/ #specifying - the - parser - to - use
def parse_html(self, html): """ Use BeautifulSoup to parse HTML / XML http://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use """ soup = BeautifulSoup(html, self.parser) title_tag = soup.find('title') self.result.title = title_tag.stri...
Combine finder_image_urls and extender_image_urls remove duplicate but keep order
def image_urls(self): """ Combine finder_image_urls and extender_image_urls, remove duplicate but keep order """ all_image_urls = self.finder_image_urls[:] for image_url in self.extender_image_urls: if image_url not in all_image_urls: all_imag...
Example: http:// lh4. ggpht. com/ - fFi - qJRuxeY/ UjwHSOTHGOI/ AAAAAAAArgE/ SWTMT - hXzB4/ s640/ Celeber - ru - Emma - Watson - Net - A - Porter - The - Edit - Magazine - Photoshoot - 2013 - 01. jpg to http:// lh4. ggpht. com/ - fFi - qJRuxeY/ UjwHSOTHGOI/ AAAAAAAArgE/ SWTMT - hXzB4/ s1600/ Celeber - ru - Emma - Watso...
def ggpht_s1600_extender(pipeline_index, finder_image_urls, extender_image_urls=[], *args, **kwargs): """ Example: http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s640/Celeber-ru-Emma-Watson-Net-A-Porter-The-Edi...
Find image URL in background - image
def background_image_finder(pipeline_index, soup, finder_image_urls=[], *args, **kwargs): """ Find image URL in background-image Example: <div style="width: 100%; height: 100%; background-image: url(http://distilleryima...
Find image URL in <img > s src attribute
def img_src_finder(pipeline_index, soup, finder_image_urls=[], *args, **kwargs): """ Find image URL in <img>'s src attribute """ now_finder_image_urls = [] for img in soup.find_all('img'): src = img.get('src', None) if src: ...
Find image URL in <a > s href attribute
def a_href_finder(pipeline_index, soup, finder_image_urls=[], *args, **kwargs): """ Find image URL in <a>'s href attribute """ now_finder_image_urls = [] for a in soup.find_all('a'): href = a.get('href', None) if href: ...
Return the node name where the name would land to
def _getnodenamefor(self, name): "Return the node name where the ``name`` would land to" return 'node_' + str( (abs(binascii.crc32(b(name)) & 0xffffffff) % self.no_servers) + 1)
Return the node where the name would land to
def getnodefor(self, name): "Return the node where the ``name`` would land to" node = self._getnodenamefor(name) return {node: self.cluster['nodes'][node]}
Return the encoding idletime or refcount about the key
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" redisent = self.redises[self._getnodenamefor(key) + '_slave'] return getattr(redisent, 'object')(infotype, key)
Pop a value off the tail of src push it on the head of dst and then return it.
def _rc_brpoplpush(self, src, dst, timeout=0): """ Pop a value off the tail of ``src``, push it on the head of ``dst`` and then return it. This command blocks until a value is in ``src`` or until ``timeout`` seconds elapse, whichever is first. A ``timeout`` value of 0 blocks ...
RPOP a value off of the src list and LPUSH it on to the dst list. Returns the value.
def _rc_rpoplpush(self, src, dst): """ RPOP a value off of the ``src`` list and LPUSH it on to the ``dst`` list. Returns the value. """ rpop = self.rpop(src) if rpop is not None: self.lpush(dst, rpop) return rpop return None
Returns the members of the set resulting from the difference between the first set and all the successive sets.
def _rc_sdiff(self, src, *args): """ Returns the members of the set resulting from the difference between the first set and all the successive sets. """ args = list_or_args(src, args) src_set = self.smembers(args.pop(0)) if src_set is not set([]): for ...
Store the difference of sets src args into a new set named dest. Returns the number of keys in the new set.
def _rc_sdiffstore(self, dst, src, *args): """ Store the difference of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set. """ args = list_or_args(src, args) result = self.sdiff(*args) if result is not set([]): ...
Returns the members of the set resulting from the difference between the first set and all the successive sets.
def _rc_sinter(self, src, *args): """ Returns the members of the set resulting from the difference between the first set and all the successive sets. """ args = list_or_args(src, args) src_set = self.smembers(args.pop(0)) if src_set is not set([]): for...
Store the difference of sets src args into a new set named dest. Returns the number of keys in the new set.
def _rc_sinterstore(self, dst, src, *args): """ Store the difference of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set. """ args = list_or_args(src, args) result = self.sinter(*args) if result is not set([]): ...
Move value from set src to set dst not atomic
def _rc_smove(self, src, dst, value): """ Move ``value`` from set ``src`` to set ``dst`` not atomic """ if self.type(src) != b("set"): return self.smove(src + "{" + src + "}", dst, value) if self.type(dst) != b("set"): return self.smove(dst + "{" +...
Returns the members of the set resulting from the union between the first set and all the successive sets.
def _rc_sunion(self, src, *args): """ Returns the members of the set resulting from the union between the first set and all the successive sets. """ args = list_or_args(src, args) src_set = self.smembers(args.pop(0)) if src_set is not set([]): for key ...
Store the union of sets src args into a new set named dest. Returns the number of keys in the new set.
def _rc_sunionstore(self, dst, src, *args): """ Store the union of sets ``src``, ``args`` into a new set named ``dest``. Returns the number of keys in the new set. """ args = list_or_args(src, args) result = self.sunion(*args) if result is not set([]): ...
Sets each key in the mapping dict to its corresponding value
def _rc_mset(self, mapping): "Sets each key in the ``mapping`` dict to its corresponding value" result = True for k, v in iteritems(mapping): result = result and self.set(k, v) return result
Sets each key in the mapping dict to its corresponding value if none of the keys are already set
def _rc_msetnx(self, mapping): """ Sets each key in the ``mapping`` dict to its corresponding value if none of the keys are already set """ for k in iterkeys(mapping): if self.exists(k): return False return self._rc_mset(mapping)
Returns a list of values ordered identically to * args
def _rc_mget(self, keys, *args): """ Returns a list of values ordered identically to ``*args`` """ args = list_or_args(keys, args) result = [] for key in args: result.append(self.get(key)) return result
Rename key src to dst
def _rc_rename(self, src, dst): """ Rename key ``src`` to ``dst`` """ if src == dst: return self.rename(src + "{" + src + "}", src) if not self.exists(src): return self.rename(src + "{" + src + "}", src) self.delete(dst) ktype = self.type(...
Rename key src to dst if dst doesn t already exist
def _rc_renamenx(self, src, dst): "Rename key ``src`` to ``dst`` if ``dst`` doesn't already exist" if self.exists(dst): return False return self._rc_rename(src, dst)
Returns a list of keys matching pattern
def _rc_keys(self, pattern='*'): "Returns a list of keys matching ``pattern``" result = [] for alias, redisent in iteritems(self.redises): if alias.find('_slave') == -1: continue result.extend(redisent.keys(pattern)) return result
Returns the number of keys in the current database
def _rc_dbsize(self): "Returns the number of keys in the current database" result = 0 for alias, redisent in iteritems(self.redises): if alias.find('_slave') == -1: continue result += redisent.dbsize() return result
Prepare the date in the instance state for serialization.
def prepare(self): """Prepare the date in the instance state for serialization. """ # Create a collection for the attributes and elements of # this instance. attributes, elements = OrderedDict(), [] # Initialize the namespace map. nsmap = dict([self.meta.namespa...
Sign an XML document with the given private key file. This will add a <Signature > element to the document.
def sign(xml, stream, password=None): """ Sign an XML document with the given private key file. This will add a <Signature> element to the document. :param lxml.etree._Element xml: The document to sign :param file stream: The private key to sign the document with :param str password: The passwo...
Verify the signaure of an XML document with the given certificate. Returns True if the document is signed with a valid signature. Returns False if the document is not signed or if the signature is invalid.
def verify(xml, stream): """ Verify the signaure of an XML document with the given certificate. Returns `True` if the document is signed with a valid signature. Returns `False` if the document is not signed or if the signature is invalid. :param lxml.etree._Element xml: The document to sign ...
Add number of photos to each gallery.
def get_queryset(self, request): """ Add number of photos to each gallery. """ qs = super(GalleryAdmin, self).get_queryset(request) return qs.annotate(photo_count=Count('photos'))
Set currently authenticated user as the author of the gallery.
def save_model(self, request, obj, form, change): """ Set currently authenticated user as the author of the gallery. """ obj.author = request.user obj.save()
For each photo set it s author to currently authenticated user.
def save_formset(self, request, form, formset, change): """ For each photo set it's author to currently authenticated user. """ instances = formset.save(commit=False) for instance in instances: if isinstance(instance, Photo): instance.author = request....
Outputs a list of tuples with ranges or the empty list According to the rfc start or end values can be omitted
def parse_byteranges(cls, environ): """ Outputs a list of tuples with ranges or the empty list According to the rfc, start or end values can be omitted """ r = [] s = environ.get(cls.header_range, '').replace(' ','').lower() if s: l = s.split('=') ...
Removes errored ranges
def check_ranges(cls, ranges, length): """Removes errored ranges""" result = [] for start, end in ranges: if isinstance(start, int) or isinstance(end, int): if isinstance(start, int) and not (0 <= start < length): continue elif isin...
Converts to valid byte ranges
def convert_ranges(cls, ranges, length): """Converts to valid byte ranges""" result = [] for start, end in ranges: if end is None: result.append( (start, length-1) ) elif start is None: s = length - end result.append( (0 if ...
Sorts and removes overlaps
def condense_ranges(cls, ranges): """Sorts and removes overlaps""" result = [] if ranges: ranges.sort(key=lambda tup: tup[0]) result.append(ranges[0]) for i in range(1, len(ranges)): if result[-1][1] + 1 >= ranges[i][0]: res...
Renders the selected social widget. You can specify optional settings that will be passed to widget template.
def social_widget_render(parser, token): """ Renders the selected social widget. You can specify optional settings that will be passed to widget template. Sample usage: {% social_widget_render widget_template ke1=val1 key2=val2 %} For example to render Twitter follow button you can use code like ...
In - place addition
def add(self, addend_mat, axis=1): """ In-place addition :param addend_mat: A matrix to be added on the Sparse3DMatrix object :param axis: The dimension along the addend_mat is added :return: Nothing (as it performs in-place operations) """ if self.finalized: ...
In - place multiplication
def multiply(self, multiplier, axis=None): """ In-place multiplication :param multiplier: A matrix or vector to be multiplied :param axis: The dim along which 'multiplier' is multiplied :return: Nothing (as it performs in-place operations) """ if self.finalized: ...
Initializes the probability of read origin according to the alignment profile
def prepare(self, pseudocount=0.0, lenfile=None, read_length=100): """ Initializes the probability of read origin according to the alignment profile :param pseudocount: Uniform prior for allele specificity estimation :return: Nothing (as it performs an in-place operations) """ ...
Initializes the probability of read origin according to the alignment profile
def reset(self, pseudocount=0.0): """ Initializes the probability of read origin according to the alignment profile :param pseudocount: Uniform prior for allele specificity estimation :return: Nothing (as it performs an in-place operations) """ self.probability.reset() ...
Updates the probability of read origin at read level
def update_probability_at_read_level(self, model=3): """ Updates the probability of read origin at read level :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele) :return: Nothing (as it performs in-place...
A single EM step: Update probability at read level and then re - estimate allelic specific expression
def update_allelic_expression(self, model=3): """ A single EM step: Update probability at read level and then re-estimate allelic specific expression :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele) :...
Runs EM iterations
def run(self, model, tol=0.001, max_iters=999, verbose=True): """ Runs EM iterations :param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele) :param tol: Tolerance for termination :param max_iters: Ma...
Exports expected read counts
def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None): """ Exports expected read counts :param filename: File name for output :param grp_wise: whether the report is at isoform level or gene level :param reorder: whether the report should be either '...
Exports expected depths
def report_depths(self, filename, tpm=True, grp_wise=False, reorder='as-is', notes=None): """ Exports expected depths :param filename: File name for output :param grp_wise: whether the report is at isoform level or gene level :param reorder: whether the report should be either '...
Writes the posterior probability of read origin
def export_posterior_probability(self, filename, title="Posterior Probability"): """ Writes the posterior probability of read origin :param filename: File name for output :param title: The title of the posterior probability matrix :return: Nothing but the method writes a file in...
Returns AlignmentPropertyMatrix object in which loci are bundled using grouping information.: param reset: whether to reset the values at the loci: param shallow: whether to copy all the meta data
def bundle(self, reset=False, shallow=False): # Copies the original matrix (Use lots of memory) """ Returns ``AlignmentPropertyMatrix`` object in which loci are bundled using grouping information. :param reset: whether to reset the values at the loci :param shallow: whether to copy...
Read - wise normalization: param axis: The dimension along which we want to normalize values: param grouping_mat: An incidence matrix that specifies which isoforms are from a same gene: return: Nothing ( as the method performs in - place operations ): rtype: None
def normalize_reads(self, axis, grouping_mat=None): """ Read-wise normalization :param axis: The dimension along which we want to normalize values :param grouping_mat: An incidence matrix that specifies which isoforms are from a same gene :return: Nothing (as the method pe...
Pull out alignments of certain reads: param reads_to_use: numpy array of dtype = bool specifying which reads to use: param shallow: whether to copy sparse 3D matrix only or not: return: a new AlignmentPropertyMatrix object that particular reads are
def pull_alignments_from(self, reads_to_use, shallow=False): """ Pull out alignments of certain reads :param reads_to_use: numpy array of dtype=bool specifying which reads to use :param shallow: whether to copy sparse 3D matrix only or not :return: a new AlignmentPropertyM...
Pull out alignments of uniquely - aligning reads: param ignore_haplotype: whether to regard allelic multiread as uniquely - aligning read: param shallow: whether to copy sparse 3D matrix only or not: return: a new AlignmentPropertyMatrix object that particular reads are
def get_unique_reads(self, ignore_haplotype=False, shallow=False): """ Pull out alignments of uniquely-aligning reads :param ignore_haplotype: whether to regard allelic multiread as uniquely-aligning read :param shallow: whether to copy sparse 3D matrix only or not :return...
Prints nonzero rows of the read wanted
def print_read(self, rid): """ Prints nonzero rows of the read wanted """ if self.rname is not None: print self.rname[rid] print '--' r = self.get_read_data(rid) aligned_loci = np.unique(r.nonzero()[1]) for locus in aligned_loci:...
Roman schemes define multiple representations of the same devanAgarI character. This method gets a library - standard representation. data: a text in the given scheme.
def get_standard_form(self, data): """Roman schemes define multiple representations of the same devanAgarI character. This method gets a library-standard representation. data : a text in the given scheme. """ if self.synonym_map is None: return data from indi...
Transliterate data with the given scheme_map. This function is used when the source scheme is a Roman scheme.
def _roman(data, scheme_map, **kw): """Transliterate `data` with the given `scheme_map`. This function is used when the source scheme is a Roman scheme. :param data: the data to transliterate :param scheme_map: a dict that maps between characters in the old scheme and characters in the new...
Given some devanAgarI sanskrit text this function produces a key so that 1 ] The key should be the same for different observed orthographical forms of the same text. For example::: - dharmma vs dharma - rAmaM gacChati vs rAma~N gacChati vs rAma~N gacChati - kurvan eva vs kurvanneva 2 ] The key should be different for d...
def get_approx_deduplicating_key(text, encoding_scheme=sanscript.DEVANAGARI): """ Given some devanAgarI sanskrit text, this function produces a "key" so that 1] The key should be the same for different observed orthographical forms of the same text. For example: :: - "dharmma" v...
Transliterate data with the given scheme_map. This function is used when the source scheme is a Brahmic scheme.
def _brahmic(data, scheme_map, **kw): """Transliterate `data` with the given `scheme_map`. This function is used when the source scheme is a Brahmic scheme. :param data: the data to transliterate :param scheme_map: a dict that maps between characters in the old scheme and characters in the...
Transliterate data with the given parameters::
def transliterate(data, _from=None, _to=None, scheme_map=None, **kw): """Transliterate `data` with the given parameters:: output = transliterate('idam adbhutam', HK, DEVANAGARI) Each time the function is called, a new :class:`SchemeMap` is created to map the input scheme to the output scheme. This operati...
Detect the input s transliteration scheme.
def detect(text): """Detect the input's transliteration scheme. :param text: some text data, either a `unicode` or a `str` encoded in UTF-8. """ if sys.version_info < (3, 0): # Verify encoding try: text = text.decode('utf-8') except UnicodeError: pass # Brahmic s...
Transliterate data with the given parameters:: output = transliterate ( idam adbhutam HK DEVANAGARI ) Each time the function is called a new: class: SchemeMap is created to map the input scheme to the output scheme. This operation is fast enough for most use cases. But for higher performance you can pass a pre - comput...
def transliterate(data, _from=None, _to=None, scheme_map=None, **kw): """Transliterate `data` with the given parameters:: output = transliterate('idam adbhutam', HK, DEVANAGARI) Each time the function is called, a new :class:`SchemeMap` is created to map the input scheme to the output scheme. This...
Add a variety of default schemes.
def _setup(): """Add a variety of default schemes.""" s = str.split if sys.version_info < (3, 0): # noinspection PyUnresolvedReferences s = unicode.split def pop_all(some_dict, some_list): for scheme in some_list: some_dict.pop(scheme) global SCHEMES ...
converts an array of integers to utf8 string
def to_utf8(y): """ converts an array of integers to utf8 string """ out = [] for x in y: if x < 0x080: out.append(x) elif x < 0x0800: out.append((x >> 6) | 0xC0) out.append((x & 0x3F) | 0x80) elif x < 0x10000: out.append((x ...
set the value of delta to reflect the current codepage
def set_script(self, i): """ set the value of delta to reflect the current codepage """ if i in range(1, 10): n = i - 1 else: raise IllegalInput("Invalid Value for ATR %s" % (hex(i))) if n > -1: # n = -1 is the default script .. ...
Handle unrecognised characters.
def _unrecognised(chr): """ Handle unrecognised characters. """ if options['handleUnrecognised'] == UNRECOGNISED_ECHO: return chr elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE: return options['substituteChar'] else: raise (KeyError, chr)
Call transliterator from a command line. python transliterator. py text inputFormat outputFormat... writes the transliterated text to stdout text -- the text to be transliterated OR the name of a file containing the text inputFormat -- the name of the character block or transliteration scheme that the text is to be tra...
def main(argv=None): """ Call transliterator from a command line. python transliterator.py text inputFormat outputFormat ... writes the transliterated text to stdout text -- the text to be transliterated OR the name of a file containing the text inputFormat -- the name of the characte...
Transliterate a devanagari text into the target format. Transliterating a character to or from Devanagari is not a simple lookup: it depends on the preceding and following characters.
def _transliterate(self, text, outFormat): """ Transliterate a devanagari text into the target format. Transliterating a character to or from Devanagari is not a simple lookup: it depends on the preceding and following characters. """ def getResult(): if cu...
Transliterate a Latin character equivalent to Devanagari. Add VIRAMA for ligatures. Convert standalone to dependent vowels.
def _equivalent(self, char, prev, next, implicitA): """ Transliterate a Latin character equivalent to Devanagari. Add VIRAMA for ligatures. Convert standalone to dependent vowels. """ result = [] if char.isVowel == False: result.append(char.c...
A convenience method
def from_devanagari(self, data): """A convenience method""" from indic_transliteration import sanscript return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name)
Load and generate num number of top - level rules from the specified grammar.
def generate(grammar=None, num=1, output=sys.stdout, max_recursion=10, seed=None): """Load and generate ``num`` number of top-level rules from the specified grammar. :param list grammar: The grammar file to load and generate data from :param int num: The number of times to generate data :param output: ...
Build the Quote instance
def build(self, pre=None, shortest=False): """Build the ``Quote`` instance :param list pre: The prerequisites list :param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. """ res = super(Q, self).build(pre, short...
Make the list of verbs into present participles
def make_present_participles(verbs): """Make the list of verbs into present participles E.g.: empower -> empowering drive -> driving """ res = [] for verb in verbs: parts = verb.split() if parts[0].endswith("e"): parts[0] = parts[0][:-1] + "ing" ...
Deletes sent MailerMessage records
def clear_sent_messages(self, offset=None): """ Deletes sent MailerMessage records """ if offset is None: offset = getattr(settings, 'MAILQUEUE_CLEAR_OFFSET', defaults.MAILQUEUE_CLEAR_OFFSET) if type(offset) is int: offset = datetime.timedelta(hours=offset) dele...
Return string with unicodenames ( unless that is disabled )
def unicodevalues_asstring(values): """ Return string with unicodenames (unless that is disabled) """ if not os.environ.get('DISABLE_UNAMES'): return map(lambda x: '%s' % format(x).strip(), values) return map(lambda x: u'U+%04x %s' % (x, unichr(x)), sorted(values))
Load the includes of an encoding Namelist files.
def _loadNamelistIncludes(item, unique_glyphs, cache): """Load the includes of an encoding Namelist files. This is an implementation detail of readNamelist. """ includes = item["includes"] = [] charset = item["charset"] = set() | item["ownCharset"] noCharcode = item["noCharcode"] = set() | item["ownNoChar...
Return a dict with the data of an encoding Namelist file.
def __readNamelist(cache, filename, unique_glyphs): """Return a dict with the data of an encoding Namelist file. This is an implementation detail of readNamelist. """ if filename in cache: item = cache[filename] else: cps, header, noncodes = parseNamelist(filename) item = { "fileName": file...
Detect infinite recursion and prevent it.
def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs): """ Detect infinite recursion and prevent it. This is an implementation detail of readNamelist. Raises NamelistRecursionError if namFilename is in the process of being included """ # normalize filename = os.path.abspath(os.path.norm...
Args: namFilename: The path to the Namelist file. unique_glyphs: Optional whether to only include glyphs unique to subset. cache: Optional a dict used to cache loaded Namelist files
def readNamelist(namFilename, unique_glyphs=False, cache=None): """ Args: namFilename: The path to the Namelist file. unique_glyphs: Optional, whether to only include glyphs unique to subset. cache: Optional, a dict used to cache loaded Namelist files Returns: A dict with following keys: "fileNa...
Returns the set of codepoints contained in a given Namelist file.
def codepointsInNamelist(namFilename, unique_glyphs=False, cache=None): """Returns the set of codepoints contained in a given Namelist file. This is a replacement CodepointsInSubset and implements the "#$ include" header format. Args: namFilename: The path to the Namelist file. unique_glyphs: Optiona...
Returns list of CharsetInfo about supported orthographies
def get_orthographies(self, _library=library): ''' Returns list of CharsetInfo about supported orthographies ''' results = [] for charset in _library.charsets: if self._charsets: cn = getattr(charset, 'common_name', False) abbr = getattr(charset, 'abbr...
Return all XML <scanning - codepoints > in received XML
def get_codepoints(): """ Return all XML <scanning-codepoints> in received XML """ # response = requests.get(EXTENSIS_LANG_XML) # if response.status_code != 200: # return [] path = get_from_cache('languages.xml', EXTENSIS_LANG_XML) try: xml_content = ope...