repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
jreese/aiosqlite
aiosqlite/core.py
Connection.cursor
python
async def cursor(self) -> Cursor: return Cursor(self, await self._execute(self._conn.cursor))
Create an aiosqlite cursor wrapping a sqlite3 cursor object.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L186-L188
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
jreese/aiosqlite
aiosqlite/core.py
Connection.close
python
async def close(self) -> None: await self._execute(self._conn.close) self._running = False self._connection = None
Complete queued queries/cursors and close the connection.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L198-L202
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
jreese/aiosqlite
aiosqlite/core.py
Connection.execute_insert
python
async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters)
Helper to insert and get the last_insert_rowid.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L213-L219
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
jreese/aiosqlite
aiosqlite/core.py
Connection.execute_fetchall
python
async def execute_fetchall( self, sql: str, parameters: Iterable[Any] = None ) -> Iterable[sqlite3.Row]: if parameters is None: parameters = [] return await self._execute(self._execute_fetchall, sql, parameters)
Helper to execute a query and return all the data.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L222-L228
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
jreese/aiosqlite
aiosqlite/core.py
Connection.executemany
python
async def executemany( self, sql: str, parameters: Iterable[Iterable[Any]] ) -> Cursor: cursor = await self._execute(self._conn.executemany, sql, parameters) return Cursor(self, cursor)
Helper to create a cursor and execute the given multiquery.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L231-L236
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
jreese/aiosqlite
aiosqlite/core.py
Connection.executescript
python
async def executescript(self, sql_script: str) -> Cursor: cursor = await self._execute(self._conn.executescript, sql_script) return Cursor(self, cursor)
Helper to create a cursor and execute a user script.
train
https://github.com/jreese/aiosqlite/blob/3f548b568b8db9a57022b6e2c9627f5cdefb983f/aiosqlite/core.py#L239-L242
[ "async def _execute(self, fn, *args, **kwargs):\n \"\"\"Queue a function with the given arguments for execution.\"\"\"\n function = partial(fn, *args, **kwargs)\n future = self._loop.create_future()\n\n self._tx.put_nowait((future, function))\n\n return await future\n" ]
class Connection(Thread): def __init__( self, connector: Callable[[], sqlite3.Connection], loop: asyncio.AbstractEventLoop, ) -> None: super().__init__() self._running = True self._connection = None # type: Optional[sqlite3.Connection] self._connector = c...
mzucker/noteshrink
noteshrink.py
quantize
python
def quantize(image, bits_per_channel=None): '''Reduces the number of bits per channel in the given image.''' if bits_per_channel is None: bits_per_channel = 6 assert image.dtype == np.uint8 shift = 8-bits_per_channel halfbin = (1 << shift) >> 1 return ((image.astype(int) >> shift) <...
Reduces the number of bits per channel in the given image.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L27-L39
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
pack_rgb
python
def pack_rgb(rgb): '''Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.''' orig_shape = None if isinstance(rgb, np.ndarray): assert rgb.shape[-1] == 3 orig_shape = rgb.shape[:-1] else: assert len(rgb) == 3 rgb = np.array(rgb) rgb =...
Packs a 24-bit RGB triples into a single integer, works on both arrays and tuples.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L43-L66
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
unpack_rgb
python
def unpack_rgb(packed): '''Unpacks a single integer or array of integers into one or more 24-bit RGB values. ''' orig_shape = None if isinstance(packed, np.ndarray): assert packed.dtype == int orig_shape = packed.shape packed = packed.reshape((-1, 1)) rgb = ((packed >> 1...
Unpacks a single integer or array of integers into one or more 24-bit RGB values.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L70-L91
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_bg_color
python
def get_bg_color(image, bits_per_channel=None): '''Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one. ''' assert image.shape[-1] == 3 quantized = quantize(image, bits_per_channel).astype(int) packed = pack_rgb...
Obtains the background color from an image or array of RGB colors by grouping similar colors into bins and finding the most frequent one.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L95-L112
[ "def quantize(image, bits_per_channel=None):\n\n '''Reduces the number of bits per channel in the given image.'''\n\n if bits_per_channel is None:\n bits_per_channel = 6\n\n assert image.dtype == np.uint8\n\n shift = 8-bits_per_channel\n halfbin = (1 << shift) >> 1\n\n return ((image.astype...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
rgb_to_sv
python
def rgb_to_sv(rgb): '''Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value. ''' if not isinstance(rgb, np.ndarray): rgb = np.array(rgb) axis = len(rgb.shape)-1 cmax = rgb.max(axis=axis).astype(np.float...
Convert an RGB image or array of RGB colors to saturation and value, returning each one as a separate 32-bit floating point array or value.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L116-L137
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
postprocess
python
def postprocess(output_filename, options): '''Runs the postprocessing command on the file provided.''' assert options.postprocess_cmd base, _ = os.path.splitext(output_filename) post_filename = base + options.postprocess_ext cmd = options.postprocess_cmd cmd = cmd.replace('%i', output_filena...
Runs the postprocessing command on the file provided.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L141-L182
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_argument_parser
python
def get_argument_parser(): '''Parse the command-line arguments for this program.''' parser = ArgumentParser( description='convert scanned, hand-written notes to PDF') show_default = ' (default %(default)s)' parser.add_argument('filenames', metavar='IMAGE', nargs='+', ...
Parse the command-line arguments for this program.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L192-L277
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_filenames
python
def get_filenames(options): '''Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you ca...
Get the filenames from the command line, optionally sorted by number, so that IMG_10.png is re-arranged to come after IMG_9.png. This is a nice feature because some scanner programs (like Image Capture on Mac OS X) automatically number files without leading zeros, and this way you can supply files using a wildcard and ...
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L281-L307
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
load
python
def load(input_filename): '''Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.''' try: pil_img = Image.open(input_filename) except IOError: sys.stderr.write('warning: error opening {}\n'.format( input_filename)) r...
Load an image with Pillow and convert it to numpy array. Also returns the image DPI in x and y as a tuple.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L311-L333
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
sample_pixels
python
def sample_pixels(img, options): '''Pick a fixed percentage of pixels in the image, returned in random order.''' pixels = img.reshape((-1, 3)) num_pixels = pixels.shape[0] num_samples = int(num_pixels*options.sample_fraction) idx = np.arange(num_pixels) np.random.shuffle(idx) return pixe...
Pick a fixed percentage of pixels in the image, returned in random order.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L337-L349
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_fg_mask
python
def get_fg_mask(bg_color, samples, options): '''Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.''' s_bg, v_bg = rgb_to_sv(bg_color) ...
Determine whether each pixel in a set of samples is foreground by comparing it to the background color. A pixel is classified as a foreground pixel if either its value or saturation differs from the background by a threshold.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L353-L367
[ "def rgb_to_sv(rgb):\n\n '''Convert an RGB image or array of RGB colors to saturation and\nvalue, returning each one as a separate 32-bit floating point array or\nvalue.\n\n '''\n\n if not isinstance(rgb, np.ndarray):\n rgb = np.array(rgb)\n\n axis = len(rgb.shape)-1\n cmax = rgb.max(axis=axis...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_palette
python
def get_palette(samples, options, return_mask=False, kmeans_iter=40): '''Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding ...
Extract the palette for the set of sampled RGB values. The first palette entry is always the background color; the rest are determined from foreground pixels by running K-means clustering. Returns the palette, as well as a mask corresponding to the foreground pixels.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L371-L396
[ "def get_bg_color(image, bits_per_channel=None):\n\n '''Obtains the background color from an image or array of RGB colors\nby grouping similar colors into bins and finding the most frequent\none.\n\n '''\n\n assert image.shape[-1] == 3\n\n quantized = quantize(image, bits_per_channel).astype(int)\n p...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
apply_palette
python
def apply_palette(img, palette, options): '''Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette. ''' if not options.quiet: print(' app...
Apply the pallete to the given image. The first step is to set all background pixels to the background color; then, nearest-neighbor matching is used to map each foreground color to the closest one in the palette.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L400-L427
[ "def get_fg_mask(bg_color, samples, options):\n\n '''Determine whether each pixel in a set of samples is foreground by\ncomparing it to the background color. A pixel is classified as a\nforeground pixel if either its value or saturation differs from the\nbackground by a threshold.'''\n\n s_bg, v_bg = rgb_to_s...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
save
python
def save(output_filename, labels, palette, dpi, options): '''Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white. ''' if not ...
Save the label/palette pair out as an indexed PNG image. This optionally saturates the pallete by mapping the smallest color component to zero and the largest one to 255, and also optionally sets the background color to pure white.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L431-L456
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
get_global_palette
python
def get_global_palette(filenames, options): '''Fetch the global palette for a series of input files by merging their samples together into one large array. ''' input_filenames = [] all_samples = [] if not options.quiet: print('building global palette...') for input_filename in file...
Fetch the global palette for a series of input files by merging their samples together into one large array.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L460-L499
[ "def load(input_filename):\n\n '''Load an image with Pillow and convert it to numpy array. Also\nreturns the image DPI in x and y as a tuple.'''\n\n try:\n pil_img = Image.open(input_filename)\n except IOError:\n sys.stderr.write('warning: error opening {}\\n'.format(\n input_filen...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
emit_pdf
python
def emit_pdf(outputs, options): '''Runs the PDF conversion command to generate the PDF.''' cmd = options.pdf_cmd cmd = cmd.replace('%o', options.pdfname) if len(outputs) > 2: cmd_print = cmd.replace('%i', ' '.join(outputs[:2] + ['...'])) else: cmd_print = cmd.replace('%i', ' '.join...
Runs the PDF conversion command to generate the PDF.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L503-L527
null
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
mzucker/noteshrink
noteshrink.py
notescan_main
python
def notescan_main(options): '''Main function for this program when run as script.''' filenames = get_filenames(options) outputs = [] do_global = options.global_palette and len(filenames) > 1 if do_global: filenames, palette = get_global_palette(filenames, options) do_postprocess = ...
Main function for this program when run as script.
train
https://github.com/mzucker/noteshrink/blob/7d876e5b43923c6bf8d64b7ef18f6855bfb30ce3/noteshrink.py#L531-L578
[ "def get_filenames(options):\n\n '''Get the filenames from the command line, optionally sorted by\nnumber, so that IMG_10.png is re-arranged to come after IMG_9.png.\nThis is a nice feature because some scanner programs (like Image\nCapture on Mac OS X) automatically number files without leading zeros,\nand this...
#!/usr/bin/env python '''Converts sequence of images to compact PDF while removing speckles, bleedthrough, etc. ''' # for some reason pylint complains about members being undefined :( # pylint: disable=E1101 from __future__ import print_function import sys import os import re import subprocess import shlex from a...
SmileyChris/django-countries
django_countries/__init__.py
Countries.get_option
python
def get_option(self, option): value = getattr(self, option, None) if value is not None: return value return getattr(settings, "COUNTRIES_{0}".format(option.upper()))
Get a configuration option, trying the options attribute first and falling back to a Django project setting.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L56-L64
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ @property def countries(self): """ Return the a dictionary of ...
SmileyChris/django-countries
django_countries/__init__.py
Countries.countries
python
def countries(self): if not hasattr(self, "_countries"): only = self.get_option("only") if only: only_choices = True if not isinstance(only, dict): for item in only: if isinstance(item, six.string_types): ...
Return the a dictionary of countries, modified by any overriding options. The result is cached so future lookups are less work intensive.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L67-L116
[ "def get_option(self, option):\n \"\"\"\n Get a configuration option, trying the options attribute first and\n falling back to a Django project setting.\n \"\"\"\n value = getattr(self, option, None)\n if value is not None:\n return value\n return getattr(settings, \"COUNTRIES_{0}\".form...
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.translate_pair
python
def translate_pair(self, code): name = self.countries[code] if code in self.OLD_NAMES: # Check if there's an older translation available if there's no # translation for the newest name. with override(None): source_name = force_text(name) na...
Force a country to the current activated translation. :returns: ``CountryTuple(code, translated_country_name)`` namedtuple
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L137-L160
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.alpha2
python
def alpha2(self, code): code = force_text(code).upper() if code.isdigit(): lookup_code = int(code) def find(alt_codes): return alt_codes[1] == lookup_code elif len(code) == 3: lookup_code = code def find(alt_codes): ...
Return the two letter country code when passed any type of ISO 3166-1 country code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L208-L238
[ "def find(alt_codes):\n return alt_codes[1] == lookup_code\n", "def find(alt_codes):\n return alt_codes[0] == lookup_code\n" ]
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.name
python
def name(self, code): code = self.alpha2(code) if code not in self.countries: return "" return self.translate_pair(code)[1]
Return the name of a country, based on the code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L240-L249
[ "def translate_pair(self, code):\n \"\"\"\n Force a country to the current activated translation.\n\n :returns: ``CountryTuple(code, translated_country_name)`` namedtuple\n \"\"\"\n name = self.countries[code]\n if code in self.OLD_NAMES:\n # Check if there's an older translation available ...
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.by_name
python
def by_name(self, country, language="en"): with override(language): for code, name in self: if name.lower() == country.lower(): return code if code in self.OLD_NAMES: for old_name in self.OLD_NAMES[code]: ...
Fetch a country's ISO3166-1 two letter country code from its name. An optional language parameter is also available. Warning: This depends on the quality of the available translations. If no match is found, returns an empty string. ..warning:: Be cautious about relying on this returni...
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L251-L272
null
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.alpha3
python
def alpha3(self, code): code = self.alpha2(code) try: return self.alt_codes[code][0] except KeyError: return ""
Return the ISO 3166-1 three letter country code matching the provided country code. If no match is found, returns an empty string.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L274-L285
[ "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_c...
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/__init__.py
Countries.numeric
python
def numeric(self, code, padded=False): code = self.alpha2(code) try: num = self.alt_codes[code][1] except KeyError: return None if padded: return "%03d" % num return num
Return the ISO 3166-1 numeric country code matching the provided country code. If no match is found, returns ``None``. :param padded: Pass ``True`` to return a 0-padded three character string, otherwise an integer will be returned.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/__init__.py#L287-L304
[ "def alpha2(self, code):\n \"\"\"\n Return the two letter country code when passed any type of ISO 3166-1\n country code.\n\n If no match is found, returns an empty string.\n \"\"\"\n code = force_text(code).upper()\n if code.isdigit():\n lookup_code = int(code)\n\n def find(alt_c...
class Countries(CountriesBase): """ An object containing a list of ISO3166-1 countries. Iterating this object will return the countries as namedtuples (of the country ``code`` and ``name``), sorted by name. """ def get_option(self, option): """ Get a configuration option, tryin...
SmileyChris/django-countries
django_countries/widgets.py
LazyChoicesMixin.choices
python
def choices(self): if isinstance(self._choices, Promise): self._choices = list(self._choices) return self._choices
When it's time to get the choices, if it was a lazy then figure it out now and memoize the result.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/widgets.py#L26-L33
[ "def _set_choices(self, value):\n self._choices = value\n" ]
class LazyChoicesMixin(object): @property @choices.setter def choices(self, value): self._set_choices(value) def _set_choices(self, value): self._choices = value
SmileyChris/django-countries
django_countries/ioc_data.py
check_ioc_countries
python
def check_ioc_countries(verbosity=1): from django_countries.data import COUNTRIES if verbosity: # pragma: no cover print("Checking if all IOC codes map correctly") for key in ISO_TO_IOC: assert COUNTRIES.get(key), "No ISO code for %s" % key if verbosity: # pragma: no cover pri...
Check if all IOC codes map to ISO codes correctly
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/ioc_data.py#L318-L329
null
IOC_TO_ISO = { "AFG": "AF", "ALB": "AL", "ALG": "DZ", "AND": "AD", "ANG": "AO", "ANT": "AG", "ARG": "AR", "ARM": "AM", "ARU": "AW", "ASA": "AS", "AUS": "AU", "AUT": "AT", "AZE": "AZ", "BAH": "BS", "BAN": "BD", "BAR": "BB", "BDI": "BI", "BEL": "BE",...
SmileyChris/django-countries
django_countries/data.py
self_generate
python
def self_generate(output_filename, filename="iso3166-1.csv"): # pragma: no cover import csv import re countries = [] alt_codes = [] with open(filename, "r") as csv_file: for row in csv.reader(csv_file): name = row[0].rstrip("*") name = re.sub(r"\(the\)", "", name) ...
The following code can be used for self-generation of this file. It requires a UTF-8 CSV file containing the short ISO name and two letter country code as the first two columns.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/data.py#L538-L585
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a self-generating script that contains all of the iso3166-1 data. To regenerate, a CSV file must be created that contains the latest data. Here's how to do that: 1. Visit https://www.iso.org/obp 2. Click the "Country Codes" radio option and click the search bu...
SmileyChris/django-countries
django_countries/fields.py
LazyChoicesMixin._set_choices
python
def _set_choices(self, value): super(LazyChoicesMixin, self)._set_choices(value) self.widget.choices = value
Also update the widget's choices.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L235-L240
null
class LazyChoicesMixin(widgets.LazyChoicesMixin):
SmileyChris/django-countries
django_countries/fields.py
CountryField.pre_save
python
def pre_save(self, *args, **kwargs): "Returns field's value just before saving." value = super(CharField, self).pre_save(*args, **kwargs) return self.get_prep_value(value)
Returns field's value just before saving.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L310-L313
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class...
SmileyChris/django-countries
django_countries/fields.py
CountryField.get_prep_value
python
def get_prep_value(self, value): "Returns field's value prepared for saving into a database." value = self.get_clean_value(value) if self.multiple: if value: value = ",".join(value) else: value = "" return super(CharField, self).get...
Returns field's value prepared for saving into a database.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L315-L323
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class...
SmileyChris/django-countries
django_countries/fields.py
CountryField.deconstruct
python
def deconstruct(self): name, path, args, kwargs = super(CountryField, self).deconstruct() kwargs.pop("choices") if self.multiple: # multiple determines the length of the field kwargs["multiple"] = self.multiple if self.countries is not countries: # Include the co...
Remove choices from deconstructed field, as this is the country list and not user editable. Not including the ``blank_label`` property, as this isn't database related.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L337-L353
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class...
SmileyChris/django-countries
django_countries/fields.py
CountryField.validate
python
def validate(self, value, model_instance): if not self.multiple: return super(CountryField, self).validate(value, model_instance) if not self.editable: # Skip validation for non-editable fields. return if value: choices = [option_key for option_k...
Use custom validation for when using a multiple countries field.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L391-L413
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class...
SmileyChris/django-countries
django_countries/fields.py
CountryField.value_to_string
python
def value_to_string(self, obj): value = self.value_from_object(obj) return self.get_prep_value(value)
Ensure data is serialized correctly.
train
https://github.com/SmileyChris/django-countries/blob/68b0934e8180d47bc15eff2887b6887aaa6e0228/django_countries/fields.py#L415-L420
null
class CountryField(CharField): """ A country field for Django models that provides all ISO 3166-1 countries as choices. """ descriptor_class = CountryDescriptor def __init__(self, *args, **kwargs): countries_class = kwargs.pop("countries", None) self.countries = countries_class...
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.process_line
python
def process_line(self, idx, line): if '///' in line: # 注释 py_line = '#' + line[3:] # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==> # /// <summary> # /// 投资者范围类型 # /// </summary>""" if py_line.find('是一个') > 0: ...
处理每行
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L56-L125
[ "def process_typedef(self, line):\n \"\"\"处理类型申明\"\"\"\n content = line.split(' ')\n type_ = self.type_dict[content[1]]\n\n if type_ == 'c_char' and '[' in line:\n # type_ = 'string'\n type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')])\n\n keyword = content[2]\n if ...
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_en...
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.process_typedef
python
def process_typedef(self, line): content = line.split(' ') type_ = self.type_dict[content[1]] if type_ == 'c_char' and '[' in line: # type_ = 'string' type_ = '%s*%s' % (type_, line[line.index('[') + 1:line.index(']')]) keyword = content[2] if '[' in key...
处理类型申明
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L127-L145
null
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_en...
haifengat/hf_ctp_py_proxy
generate/generate_enum_cs.py
Generate.run
python
def run(self): # try: self.fenum.write('\n') self.fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiDataType.h'), 'r') for idx, line in enumerate(self.fcpp): l = self.process_line(idx, line) self.f_data_type.write(l) self.fcpp.clos...
主函数
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_enum_cs.py#L147-L161
[ "def process_line(self, idx, line):\n \"\"\"处理每行\"\"\"\n if '///' in line: # 注释\n py_line = '#' + line[3:]\n\n # /// [T去掉ftdc前的内容,方便后面比对]FtdcInvestorRangeType是一个投资者范围类型 ==>\n # /// <summary>\n # /// 投资者范围类型\n # /// </summary>\"\"\"\n if py_line.find('是一个') > 0:\n ...
class Generate(): def __init__(self, dir, out_path): self.ctp_dir = dir # C++和python类型的映射字典 self.type_dict = {'int': 'c_int32', 'char': 'c_char', 'double': 'c_double', 'short': 'c_short', 'string': 'c_char_p'} self.define = [] self.fenum = open(os.path.join(out_path, 'ctp_en...
haifengat/hf_ctp_py_proxy
generate/generate_struct_cs.py
Generate.run
python
def run(self): fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'ThostFtdcUserApiStruct.h'), 'r') fpy = open(os.path.join(self.out_path, 'ctp_struct.cs'), 'w', encoding='utf-8') fpy.write('\n') fpy.write('using System.Runtime.InteropServices;\n') fpy.write('\n') ...
主函数
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/generate/generate_struct_cs.py#L47-L135
null
class Generate: def __init__(self, dir, out_path): self.ctp_dir = dir self.out_path = out_path
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._qry
python
def _qry(self): # restart 模式, 待rtnorder 处理完毕后再进行查询,否则会造成position混乱 ord_cnt = 0 trd_cnt = 0 while True: time.sleep(0.5) if len(self.orders) == ord_cnt and len(self.trades) == trd_cnt: break ord_cnt = len(self.orders) trd_cnt ...
查询帐号相关信息
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L103-L134
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._OnRspQryPositionDetail
python
def _OnRspQryPositionDetail(self, pInvestorPositionDetail: CThostFtdcInvestorPositionDetailField, pRspInfo: CThostFtdcRspInfoField, nRequestID: int, bIsLast: bool): if pInvestorPositionDetail.getInstrumentID() == '': return detail = PositionDetail() detail.Instrument = pInvestorPosit...
持仓明细
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L203-L217
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade._OnRtnNotice
python
def _OnRtnNotice(self, pTradingNoticeInfo: CThostFtdcTradingNoticeInfoField): '''交易提醒''' msg = pTradingNoticeInfo.getFieldContent() if len(msg) > 0: threading.Thread(target=self.OnRtnNotice, args=(self, pTradingNoticeInfo.getSendTime(), msg)).start()
交易提醒
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L384-L388
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqConnect
python
def ReqConnect(self, front: str): self.t.CreateApi() spi = self.t.CreateSpi() self.t.RegisterSpi(spi) self.t.OnFrontConnected = self._OnFrontConnected self.t.OnRspUserLogin = self._OnRspUserLogin self.t.OnFrontDisconnected = self._OnFrontDisconnected # self.t.OnR...
连接交易前置 :param front:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L405-L439
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqUserLogin
python
def ReqUserLogin(self, user: str, pwd: str, broker: str): self.broker = broker self.investor = user self.password = pwd self.t.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)
登录 :param user: :param pwd: :param broker:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L442-L452
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqOrderInsert
python
def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0): OrderPriceType = TThostFtdcOrderPriceTypeType.THOST_FTDC_OPT_AnyPrice TimeCondition = TThostFtdcTimeConditionType.THOST_FT...
委托 :param pInstrument: :param pDirection: :param pOffset: :param pPrice: :param pVolume: :param pType: :param pCustom: :return:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L454-L513
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqOrderAction
python
def ReqOrderAction(self, OrderID: str): of = self.orders[OrderID] if not of: return -1 else: pOrderId = of.OrderID return self.t.ReqOrderAction( self.broker, self.investor, OrderRef=pOrderId.split('|')[2], ...
撤单 :param OrderID:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L515-L533
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.ReqUserLogout
python
def ReqUserLogout(self): self.logined = False time.sleep(3) self.t.ReqUserLogout(BrokerID=self.broker, UserID=self.investor) self.t.RegisterSpi(None) self.t.Release() threading.Thread(target=self.OnDisConnected, args=(self, 0)).start()
退出接口
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L535-L542
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.OnErrCancel
python
def OnErrCancel(self, obj, f: OrderField, info: InfoField): print('=== [TRADE] OnErrCancel ===\n{0}'.format(f.__dict__)) print(info)
撤单失败 :param self: :param obj: :param f:OrderField: :param info:InfoField:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L592-L601
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/trade.py
CtpTrade.OnInstrumentStatus
python
def OnInstrumentStatus(self, obj, inst: str, status: InstrumentStatus): print('{}:{}'.format(inst, str(status).strip().split('.')[-1]))
交易状态 :param self: :param obj: :param inst:str: :param status:InstrumentStatus:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/trade.py#L614-L622
null
class CtpTrade(): """""" def __init__(self): self.front_address = '' self.investor = '' self.password = '' self.broker = '' self.logined = False self.tradingday = '' self.instruments = {} self.orders = {} self.trades = {} self.acc...
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqConnect
python
def ReqConnect(self, pAddress: str): self.q.CreateApi() spi = self.q.CreateSpi() self.q.RegisterSpi(spi) self.q.OnFrontConnected = self._OnFrontConnected self.q.OnFrontDisconnected = self._OnFrontDisConnected self.q.OnRspUserLogin = self._OnRspUserLogin self.q.On...
连接行情前置 :param pAddress:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L26-L44
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqUserLogin(self, user: str, pwd: str, broker: str): """登录 :param user: :param pwd: :param broker: """ self.q.ReqUserL...
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqUserLogin
python
def ReqUserLogin(self, user: str, pwd: str, broker: str): self.q.ReqUserLogin(BrokerID=broker, UserID=user, Password=pwd)
登录 :param user: :param pwd: :param broker:
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L46-L53
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqConnect(self, pAddress: str): """连接行情前置 :param pAddress: """ self.q.CreateApi() spi = self.q.CreateSpi() self.q.Regis...
haifengat/hf_ctp_py_proxy
py_ctp/quote.py
CtpQuote.ReqUserLogout
python
def ReqUserLogout(self): self.q.Release() # 确保隔夜或重新登录时的第1个tick不被发送到客户端 self.inst_tick.clear() self.logined = False threading.Thread(target=self.OnDisConnected, args=(self, 0)).start()
退出接口(正常退出,不会触发OnFrontDisconnected)
train
https://github.com/haifengat/hf_ctp_py_proxy/blob/c2dc6dbde45aa6b097f75380474e91510d3f5d12/py_ctp/quote.py#L62-L69
null
class CtpQuote(object): """""" def __init__(self): self.q = Quote() self.inst_tick = {} self.logined = False def ReqConnect(self, pAddress: str): """连接行情前置 :param pAddress: """ self.q.CreateApi() spi = self.q.CreateSpi() self.q.Regis...
outini/python-pylls
pylls/cachet.py
Components.groups
python
def groups(self): if not self._groups: self._groups = ComponentGroups(self.api_client) return self._groups
Component groups Special property which point to a :class:`~pylls.cachet.ComponentGroups` instance for convenience. This instance is initialized on first call.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L86-L94
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def get(self, component_id=None, **kwargs): "...
outini/python-pylls
pylls/cachet.py
Components.get
python
def get(self, component_id=None, **kwargs): path = 'components' if component_id is not None: path += '/%s' % component_id return self.paginate_get(path, data=kwargs)
Get components :param component_id: Component ID (optional) :return: Components data (:class:`Generator`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L96-L111
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups ...
outini/python-pylls
pylls/cachet.py
Components.create
python
def create(self, name, status, description="", link="", order=0, group_id=0, enabled=True): data = ApiParams() data['name'] = name data['status'] = status data['description'] = description data['link'] = link data['order'] = order data['group_id'] =...
Create a new component :param str name: Name of the component :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) :param int order: Order of the component (option...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L113-L137
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups ...
outini/python-pylls
pylls/cachet.py
Components.update
python
def update(self, component_id, name=None, status=None, description=None, link=None, order=None, group_id=None, enabled=True): data = ApiParams() data['component'] = component_id data['name'] = name data['status'] = status data['description'] = description d...
Update a component :param int component_id: Component ID :param str name: Name of the component (optional) :param int status: Status of the component; 1-4 :param str description: Description of the component (optional) :param str link: A hyperlink to the component (optional) ...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L139-L165
null
class Components(client.CachetAPIEndPoint): """Components API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Components, self).__init__(*args, **kwargs) self._groups = None @property def groups(self): """Component groups ...
outini/python-pylls
pylls/cachet.py
ComponentGroups.get
python
def get(self, group_id=None, **kwargs): path = 'components/groups' if group_id is not None: path += '/%s' % group_id return self.paginate_get(path, data=kwargs)
Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/r...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L185-L200
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def create(self, name, order=None, collapsed=None): """Create a new Comp...
outini/python-pylls
pylls/cachet.py
ComponentGroups.create
python
def create(self, name, order=None, collapsed=None): data = ApiParams() data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._post('components/groups', data=data)['data']
Create a new Component Group :param str name: Name of the component group :param int order: Order of the component group :param int collapsed: Collapse the group? 0-2 :return: Created component group data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#post-comp...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L202-L216
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def get(self, group_id=None, **kwargs): """Get component groups ...
outini/python-pylls
pylls/cachet.py
ComponentGroups.update
python
def update(self, group_id, name=None, order=None, collapsed=None): data = ApiParams() data['group'] = group_id data['name'] = name data['order'] = order data['collapsed'] = collapsed return self._put('components/groups/%s' % group_id, data=data)['data']
Update a Component Group :param int group_id: Component Group ID :param str name: Name of the component group :param int order: Order of the group :param int collapsed: Collapse the group? :return: Updated component group data (:class:`dict`) .. seealso:: https://docs.c...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L218-L234
null
class ComponentGroups(client.CachetAPIEndPoint): """Component groups API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(ComponentGroups, self).__init__(*args, **kwargs) def get(self, group_id=None, **kwargs): """Get component groups ...
outini/python-pylls
pylls/cachet.py
Incidents.get
python
def get(self, incident_id=None, **kwargs): path = 'incidents' if incident_id is not None: path += '/%s' % incident_id return self.paginate_get(path, data=kwargs)
Get incidents :param int incident_id: :return: Incidents data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-incidents .. see...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L254-L269
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def create(self, name, message, status, visible, component_id=None, component_status...
outini/python-pylls
pylls/cachet.py
Incidents.create
python
def create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None): data = ApiParams() data['name'] = name data['message'] = message data['status'] = status data['visi...
Create a new Incident :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: Component to update :param int com...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L271-L301
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def get(self, incident_id=None, **kwargs): """Get incidents :param int incident_id:...
outini/python-pylls
pylls/cachet.py
Incidents.update
python
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template=None, tpl_vars=None): data = ApiParams() data['name'] = name data['message'] = message data['st...
Update an Incident :param int incident_id: Incident ID :param str name: Name of the incident :param str message: Incident explanation message :param int status: Status of the incident :param int visible: Whether the incident is publicly visible :param int component_id: C...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L303-L334
null
class Incidents(client.CachetAPIEndPoint): """Incidents API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Incidents, self).__init__(*args, **kwargs) def get(self, incident_id=None, **kwargs): """Get incidents :param int incident_id:...
outini/python-pylls
pylls/cachet.py
Metrics.points
python
def points(self): if not self._points: self._points = MetricPoints(self.api_client) return self._points
Metric points Special property which point to a :class:`~pylls.cachet.MetricPoints` instance for convenience. This instance is initialized on first call.
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L356-L364
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def get(self, metric_id=None, **kwargs): """Get metric...
outini/python-pylls
pylls/cachet.py
Metrics.get
python
def get(self, metric_id=None, **kwargs): path = 'metrics' if metric_id is not None: path += '/%s' % metric_id return self.paginate_get(path, data=kwargs)
Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-metrics .. s...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L366-L381
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def points(self): """Metric points Special prop...
outini/python-pylls
pylls/cachet.py
Metrics.create
python
def create(self, name, suffix, description, default_value, display=None): data = ApiParams() data['name'] = name data['suffix'] = suffix data['description'] = description data['default_value'] = default_value data['display'] = display return self._post('metrics', ...
Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :param str description: Description of what the metric is measuring :param int default_value: Default value to use when a point is added :param int display: Display the chart on the status page ...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L383-L401
null
class Metrics(client.CachetAPIEndPoint): """Metrics API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Metrics, self).__init__(*args, **kwargs) self._points = None @property def points(self): """Metric points Special prop...
outini/python-pylls
pylls/cachet.py
MetricPoints.create
python
def create(self, metric_id, value, timestamp=None): data = ApiParams() data['value'] = value data['timestamp'] = timestamp return self._post('metrics/%s/points' % metric_id, data=data)['data']
Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metric graph :param str timestamp: Unix timestamp of the point was measured :return: Created metric point data (:class:`dict`) .. seealso:: https://docs.cachethq.io/reference#p...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L431-L444
null
class MetricPoints(client.CachetAPIEndPoint): """MetricPoints API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(MetricPoints, self).__init__(*args, **kwargs) def get(self, metric_id, **kwargs): """Get Points for a Metric :param int ...
outini/python-pylls
pylls/cachet.py
Subscribers.create
python
def create(self, email, verify=None, components=None): data = ApiParams() data['email'] = email data['verify'] = verify data['components'] = components return self._post('subscribers', data=data)['data']
Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to send verification email :param list components: Components ID list, defaults to all :return: Created subscriber data (:class:`dict`) .. seealso:: https://docs.cachethq.io/referen...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L479-L493
null
class Subscribers(client.CachetAPIEndPoint): """Subscribers API endpoint """ def __init__(self, *args, **kwargs): """Initialization method""" super(Subscribers, self).__init__(*args, **kwargs) def get(self, **kwargs): """Returns all subscribers :return: Subscribers data...
outini/python-pylls
pylls/client.py
CachetAPIClient.request
python
def request(self, path, method, data=None, **kwargs): if self.api_token: self.request_headers['X-Cachet-Token'] = self.api_token if not path.startswith('http://') and not path.startswith('https://'): url = "%s/%s" % (self.api_endpoint, path) else: url = path ...
Handle requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Parsed json response as :class:`dict` Additional named argument may be passed and are directly transmitted to ...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/client.py#L86-L121
null
class CachetAPIClient(object): """Simple Cachet API client It implements common HTTP methods GET, POST, PUT and DELETE This client is using :mod:`requests` package. Please see http://docs.python-requests.org/ for more information. :param bool verify: Control SSL certificate validation :param ...
outini/python-pylls
pylls/client.py
CachetAPIClient.paginate_request
python
def paginate_request(self, path, method, data=None, **kwargs): next_page = path while next_page: response = self.request(next_page, method, data=data, **kwargs) if not isinstance(response.get('data'), list): next_page = None yield response['data']...
Handle paginated requests to API :param str path: API endpoint's path to request :param str method: HTTP method to use :param dict data: Data to send (optional) :return: Response data items (:class:`Generator`) Cachet pagination is handled and next pages requested on demand. ...
train
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/client.py#L123-L152
[ "def request(self, path, method, data=None, **kwargs):\n \"\"\"Handle requests to API\n\n :param str path: API endpoint's path to request\n :param str method: HTTP method to use\n :param dict data: Data to send (optional)\n :return: Parsed json response as :class:`dict`\n\n Additional named argume...
class CachetAPIClient(object): """Simple Cachet API client It implements common HTTP methods GET, POST, PUT and DELETE This client is using :mod:`requests` package. Please see http://docs.python-requests.org/ for more information. :param bool verify: Control SSL certificate validation :param ...
what-studio/smartformat
smartformat/dotnet.py
modify_number_pattern
python
def modify_number_pattern(number_pattern, **kwargs): params = ['pattern', 'prefix', 'suffix', 'grouping', 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus'] for param in params: if param in kwargs: continue kwargs[param] = getattr(number_pattern, param) return NumberP...
Modifies a number pattern by specified keyword arguments.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L31-L39
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_currency_field
python
def format_currency_field(__, prec, number, locale): locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_formats['standard'] pattern ...
Formats a currency field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L58-L70
[ "def modify_number_pattern(number_pattern, **kwargs):\n \"\"\"Modifies a number pattern by specified keyword arguments.\"\"\"\n params = ['pattern', 'prefix', 'suffix', 'grouping',\n 'int_prec', 'frac_prec', 'exp_prec', 'exp_plus']\n for param in params:\n if param in kwargs:\n ...
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_decimal_field
python
def format_decimal_field(__, prec, number, locale): prec = 0 if prec is None else int(prec) if number < 0: prec += 1 return format(number, u'0%dd' % prec)
Formats a decimal field: .. sourcecode:: 1234 ('D') -> 1234 -1234 ('D6') -> -001234
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L75-L87
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_float_field
python
def format_float_field(__, prec, number, locale): format_ = u'0.' if prec is None: format_ += u'#' * NUMBER_DECIMAL_DIGITS else: format_ += u'0' * int(prec) pattern = parse_pattern(format_) return pattern.apply(number, locale)
Formats a fixed-point field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L103-L111
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_number_field
python
def format_number_field(__, prec, number, locale): prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a number field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L116-L121
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_percent_field
python
def format_percent_field(__, prec, number, locale): prec = PERCENT_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.percent_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a percent field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L126-L131
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
format_hexadecimal_field
python
def format_hexadecimal_field(spec, prec, number, locale): if number < 0: # Take two's complement. number &= (1 << (8 * int(math.log(-number, 1 << 8) + 1))) - 1 format_ = u'0%d%s' % (int(prec or 0), spec) return format(number, format_)
Formats a hexadeciaml field.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L136-L142
null
# -*- coding: utf-8 -*- """ smartformat.dotnet ~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import math from numbers import Number from babel import Locale from babel.numbers import ( format_currency, get_decimal_symbol, get_territory_curren...
what-studio/smartformat
smartformat/dotnet.py
DotNetFormatter.format_field
python
def format_field(self, value, format_spec): if format_spec: spec, arg = format_spec[0], format_spec[1:] arg = arg or None else: spec = arg = None return self._format_field(spec, arg, value, self.numeric_locale)
Format specifiers are described in :func:`format_field` which is a static function.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/dotnet.py#L173-L182
null
class DotNetFormatter(LocalFormatter): """A string formatter like `String.Format` in .NET Framework.""" _format_field = staticmethod(format_field) def vformat(self, format_string, args, kwargs): if not format_string: return u'' base = super(DotNetFormatter, self) return...
what-studio/smartformat
smartformat/builtin.py
plural
python
def plural(formatter, value, name, option, format): # Extract the plural words from the format string. words = format.split('|') # This extension requires at least two plural words. if not name and len(words) == 1: return # This extension only formats numbers. try: number = decim...
Chooses different textension for locale-specific pluralization rules. Spec: `{:[p[lural]][(locale)]:msgstr0|msgstr1|...}` Example:: >>> smart.format(u'There {num:is an item|are {} items}.', num=1} There is an item. >>> smart.format(u'There {num:is an item|are {} items}.', num=10} ...
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L26-L53
[ "def get_plural_tag_index(number, locale):\n \"\"\"Gets the plural tag index of a number on the plural rule of a locale::\n\n >>> get_plural_tag_index(1, 'en_US')\n 0\n >>> get_plural_tag_index(2, 'en_US')\n 1\n >>> get_plural_tag_index(100, 'en_US')\n 1\n\n \"\"\"\n loc...
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_typ...
what-studio/smartformat
smartformat/builtin.py
get_choice
python
def get_choice(value): if value is None: return 'null' for attr in ['__name__', 'name']: if hasattr(value, attr): return getattr(value, attr) return str(value)
Gets a key to choose a choice from any value.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L56-L63
null
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_typ...
what-studio/smartformat
smartformat/builtin.py
choose
python
def choose(formatter, value, name, option, format): if not option: return words = format.split('|') num_words = len(words) if num_words < 2: return choices = option.split('|') num_choices = len(choices) # If the words has 1 more item than the choices, the last word will be ...
Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=4) u'other'
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L67-L100
[ "def get_choice(value):\n \"\"\"Gets a key to choose a choice from any value.\"\"\"\n if value is None:\n return 'null'\n for attr in ['__name__', 'name']:\n if hasattr(value, attr):\n return getattr(value, attr)\n return str(value)\n" ]
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_typ...
what-studio/smartformat
smartformat/builtin.py
list_
python
def list_(formatter, value, name, option, format): if not format: return if not hasattr(value, '__getitem__') or isinstance(value, string_types): return words = format.split(u'|', 4) num_words = len(words) if num_words < 2: # Require at least two words for item format and spa...
Repeats the items of an array. Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}` Example:: >>> fruits = [u'apple', u'banana', u'coconut'] >>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits) u'apple, banana, and coconut' >>> smart.format(u'{fruits:list:{}...
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/builtin.py#L112-L156
null
# -*- coding: utf-8 -*- """ smartformat.builtin ~~~~~~~~~~~~~~~~~~~ Built-in extensions from SmartFormat.NET, the original implementation. :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ import decimal import io from babel import Locale from six import string_typ...
what-studio/smartformat
smartformat/utils.py
get_plural_tag_index
python
def get_plural_tag_index(number, locale): locale = Locale.parse(locale) plural_rule = locale.plural_form used_tags = plural_rule.tags | set([_fallback_tag]) tag, index = plural_rule(number), 0 for _tag in _plural_tags: if _tag == tag: return index if _tag in used_tags: ...
Gets the plural tag index of a number on the plural rule of a locale:: >>> get_plural_tag_index(1, 'en_US') 0 >>> get_plural_tag_index(2, 'en_US') 1 >>> get_plural_tag_index(100, 'en_US') 1
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/utils.py#L17-L36
null
# -*- coding: utf-8 -*- """ smartformat.utils ~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ from babel import Locale from babel.plural import _fallback_tag, _plural_tags __all__ = ['get_plural_tag_index']
what-studio/smartformat
smartformat/smart.py
extension
python
def extension(names): for name in names: if not NAME_PATTERN.match(name): raise ValueError('invalid extension name: %s' % name) def decorator(f, names=names): return Extension(f, names=names) return decorator
Makes a function to be an extension.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L190-L197
null
# -*- coding: utf-8 -*- """ smartformat.smart ~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by What! Studio :license: BSD, see LICENSE for more details. """ from collections import deque import io import re import string import sys from types import MethodType from six import reraise, text_type from .dotnet im...
what-studio/smartformat
smartformat/smart.py
SmartFormatter.register
python
def register(self, extensions): for ext in reversed(extensions): for name in ext.names: try: self._extensions[name].appendleft(ext) except KeyError: self._extensions[name] = deque([ext])
Registers extensions.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L75-L82
null
class SmartFormatter(DotNetFormatter): def __init__(self, locale=None, extensions=(), register_default=True, errors='strict'): super(SmartFormatter, self).__init__(locale) # Set error action. try: _format_error = self._error_formatters[errors] except Key...
what-studio/smartformat
smartformat/smart.py
SmartFormatter.eval_extensions
python
def eval_extensions(self, value, name, option, format): try: exts = self._extensions[name] except KeyError: raise ValueError('no suitable extension: %s' % name) for ext in exts: rv = ext(self, value, name, option, format) if rv is not None: ...
Evaluates extensions in the registry. If some extension handles the format string, it returns a string. Otherwise, returns ``None``.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/smart.py#L95-L106
null
class SmartFormatter(DotNetFormatter): def __init__(self, locale=None, extensions=(), register_default=True, errors='strict'): super(SmartFormatter, self).__init__(locale) # Set error action. try: _format_error = self._error_formatters[errors] except Key...
what-studio/smartformat
smartformat/local.py
LocalFormatter.format_field_by_match
python
def format_field_by_match(self, value, match): groups = match.groups() fill, align, sign, sharp, zero, width, comma, prec, type_ = groups if not comma and not prec and type_ not in list('fF%'): return None if math.isnan(value) or math.isinf(value): return None ...
Formats a field by a Regex match of the format spec pattern.
train
https://github.com/what-studio/smartformat/blob/5731203cbf29617ab8d42542f9dac03d5e34b217/smartformat/local.py#L102-L133
null
class LocalFormatter(string.Formatter): """A formatter which keeps a locale.""" def __init__(self, locale): self.locale = Locale.parse(locale) @property def numeric_locale(self): return self.locale or LC_NUMERIC def format_field(self, value, format_spec): match = FORMAT_SP...
BrianHicks/emit
examples/regex/graph.py
parse_querystring
python
def parse_querystring(msg): 'parse a querystring into keys and values' for part in msg.querystring.strip().lstrip('?').split('&'): key, value = part.split('=') yield key, value
parse a querystring into keys and values
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/examples/regex/graph.py#L14-L18
null
from emit import Router from emit.message import NoResult from redis import Redis router = Router() redis = Redis() def prefix(name): return '%s.%s' % (__name__, name) @router.node(('key', 'value'), entry_point=True) @router.node(('key', 'value', 'count'), prefix('parse_querystring')) def count_keyval(msg):...
BrianHicks/emit
emit/router/core.py
Router.wrap_as_node
python
def wrap_as_node(self, func): 'wrap a function as a node' name = self.get_name(func) @wraps(func) def wrapped(*args, **kwargs): 'wrapped version of func' message = self.get_message_from_call(*args, **kwargs) self.logger.info('calling "%s" with %r', na...
wrap a function as a node
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L61-L105
[ "def get_name(self, func):\n '''\n Get the name to reference a function by\n\n :param func: function to get the name of\n :type func: callable\n '''\n if hasattr(func, 'name'):\n return func.name\n\n return '%s.%s' % (\n func.__module__,\n func.__name__\n )\n" ]
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.node
python
def node(self, fields, subscribe_to=None, entry_point=False, ignore=None, **wrapper_options): '''\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a ...
\ Decorate a function to make it a node. .. note:: decorating as a node changes the function signature. Nodes should accept a single argument, which will be a :py:class:`emit.message.Message`. Nodes can be called directly by providing a dictionary argument or...
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L107-L159
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.resolve_node_modules
python
def resolve_node_modules(self): 'import the modules specified in init' if not self.resolved_node_modules: try: self.resolved_node_modules = [ importlib.import_module(mod, self.node_package) for mod in self.node_modules ]...
import the modules specified in init
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L161-L173
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.get_message_from_call
python
def get_message_from_call(self, *args, **kwargs): '''\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single...
\ Get message object from a call. :raises: :py:exc:`TypeError` (if the format is not what we expect) This is where arguments to nodes are turned into Messages. Arguments are parsed in the following order: - A single positional argument (a :py:class:`dict`) - No posit...
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L175-L203
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.register
python
def register(self, name, func, fields, subscribe_to, entry_point, ignore): ''' Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscrib...
Register a named function in the graph :param name: name to register :type name: :py:class:`str` :param func: function to remember and call :type func: callable ``fields``, ``subscribe_to`` and ``entry_point`` are the same as in :py:meth:`Router.node`.
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L205-L228
[ "def add_entry_point(self, destination):\n '''\\\n Add an entry point\n\n :param destination: node to route to initially\n :type destination: str\n '''\n self.routes.setdefault('__entry_point', set()).add(destination)\n return self.routes['__entry_point']\n", "def register_route(self, origins...
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.add_entry_point
python
def add_entry_point(self, destination): '''\ Add an entry point :param destination: node to route to initially :type destination: str ''' self.routes.setdefault('__entry_point', set()).add(destination) return self.routes['__entry_point']
\ Add an entry point :param destination: node to route to initially :type destination: str
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L230-L238
null
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.register_route
python
def register_route(self, origins, destination): ''' Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type dest...
Add routes to the routing dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` or None :param destination: where the origins should point to :type destination: :py:class:`str` Routing dictionary takes the follo...
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L240-L265
[ "def regenerate_routes(self):\n 'regenerate the routes after a new route is added'\n for destination, origins in self.regexes.items():\n # we want only the names that match the destination regexes.\n resolved = [\n name for name in self.names\n if name is not destination\n ...
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...
BrianHicks/emit
emit/router/core.py
Router.register_ignore
python
def register_ignore(self, origins, destination): ''' Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination:...
Add routes to the ignore dictionary :param origins: a number of origins to register :type origins: :py:class:`str` or iterable of :py:class:`str` :param destination: where the origins should point to :type destination: :py:class:`str` Ignore dictionary takes the following form:...
train
https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L267-L288
[ "def regenerate_routes(self):\n 'regenerate the routes after a new route is added'\n for destination, origins in self.regexes.items():\n # we want only the names that match the destination regexes.\n resolved = [\n name for name in self.names\n if name is not destination\n ...
class Router(object): 'A router object. Holds routes and references to functions for dispatch' def __init__(self, message_class=None, node_modules=None, node_package=None): '''\ Create a new router object. All parameters are optional. :param message_class: wrapper class for messages pas...