body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
@property
def available(self) -> bool:
'Return if bulb is available.'
return self._available | -8,593,444,446,007,529,000 | Return if bulb is available. | homeassistant/components/light/yeelight.py | available | DevRGT/home-assistant | python | @property
def available(self) -> bool:
return self._available |
@property
def supported_features(self) -> int:
'Flag supported features.'
return self._supported_features | 8,102,951,252,997,921,000 | Flag supported features. | homeassistant/components/light/yeelight.py | supported_features | DevRGT/home-assistant | python | @property
def supported_features(self) -> int:
return self._supported_features |
@property
def effect_list(self):
'Return the list of supported effects.'
return YEELIGHT_EFFECT_LIST | -6,125,693,931,358,221,000 | Return the list of supported effects. | homeassistant/components/light/yeelight.py | effect_list | DevRGT/home-assistant | python | @property
def effect_list(self):
return YEELIGHT_EFFECT_LIST |
@property
def color_temp(self) -> int:
'Return the color temperature.'
return self._color_temp | 9,105,838,033,052,904,000 | Return the color temperature. | homeassistant/components/light/yeelight.py | color_temp | DevRGT/home-assistant | python | @property
def color_temp(self) -> int:
return self._color_temp |
@property
def name(self) -> str:
'Return the name of the device if any.'
return self._name | -7,564,036,760,381,367,000 | Return the name of the device if any. | homeassistant/components/light/yeelight.py | name | DevRGT/home-assistant | python | @property
def name(self) -> str:
return self._name |
@property
def is_on(self) -> bool:
'Return true if device is on.'
return self._is_on | 2,519,804,288,039,148,000 | Return true if device is on. | homeassistant/components/light/yeelight.py | is_on | DevRGT/home-assistant | python | @property
def is_on(self) -> bool:
return self._is_on |
@property
def brightness(self) -> int:
'Return the brightness of this light between 1..255.'
return self._brightness | -1,115,853,844,080,985,100 | Return the brightness of this light between 1..255. | homeassistant/components/light/yeelight.py | brightness | DevRGT/home-assistant | python | @property
def brightness(self) -> int:
return self._brightness |
@property
def min_mireds(self):
'Return minimum supported color temperature.'
if (self.supported_features & SUPPORT_COLOR_TEMP):
return kelvin_to_mired(YEELIGHT_RGB_MAX_KELVIN)
return kelvin_to_mired(YEELIGHT_MAX_KELVIN) | 4,766,083,804,337,532,000 | Return minimum supported color temperature. | homeassistant/components/light/yeelight.py | min_mireds | DevRGT/home-assistant | python | @property
def min_mireds(self):
if (self.supported_features & SUPPORT_COLOR_TEMP):
return kelvin_to_mired(YEELIGHT_RGB_MAX_KELVIN)
return kelvin_to_mired(YEELIGHT_MAX_KELVIN) |
@property
def max_mireds(self):
'Return maximum supported color temperature.'
if (self.supported_features & SUPPORT_COLOR_TEMP):
return kelvin_to_mired(YEELIGHT_RGB_MIN_KELVIN)
return kelvin_to_mired(YEELIGHT_MIN_KELVIN) | 7,928,850,946,347,256,000 | Return maximum supported color temperature. | homeassistant/components/light/yeelight.py | max_mireds | DevRGT/home-assistant | python | @property
def max_mireds(self):
if (self.supported_features & SUPPORT_COLOR_TEMP):
return kelvin_to_mired(YEELIGHT_RGB_MIN_KELVIN)
return kelvin_to_mired(YEELIGHT_MIN_KELVIN) |
@property
def hs_color(self) -> tuple:
'Return the color property.'
return self._hs | 6,843,634,616,928,289,000 | Return the color property. | homeassistant/components/light/yeelight.py | hs_color | DevRGT/home-assistant | python | @property
def hs_color(self) -> tuple:
return self._hs |
def set_music_mode(self, mode) -> None:
'Set the music mode on or off.'
if mode:
self._bulb.start_music()
else:
self._bulb.stop_music() | 5,503,438,018,378,298,000 | Set the music mode on or off. | homeassistant/components/light/yeelight.py | set_music_mode | DevRGT/home-assistant | python | def set_music_mode(self, mode) -> None:
if mode:
self._bulb.start_music()
else:
self._bulb.stop_music() |
def update(self) -> None:
'Update properties from the bulb.'
import yeelight
try:
self._bulb.get_properties()
if (self._bulb_device.bulb_type == yeelight.BulbType.Color):
self._supported_features = SUPPORT_YEELIGHT_RGB
self._is_on = (self._properties.get('power') == 'on')... | 6,698,611,751,465,550,000 | Update properties from the bulb. | homeassistant/components/light/yeelight.py | update | DevRGT/home-assistant | python | def update(self) -> None:
import yeelight
try:
self._bulb.get_properties()
if (self._bulb_device.bulb_type == yeelight.BulbType.Color):
self._supported_features = SUPPORT_YEELIGHT_RGB
self._is_on = (self._properties.get('power') == 'on')
bright = self._properties... |
@_cmd
def set_brightness(self, brightness, duration) -> None:
'Set bulb brightness.'
if brightness:
_LOGGER.debug('Setting brightness: %s', brightness)
self._bulb.set_brightness(((brightness / 255) * 100), duration=duration) | 8,159,060,235,782,080,000 | Set bulb brightness. | homeassistant/components/light/yeelight.py | set_brightness | DevRGT/home-assistant | python | @_cmd
def set_brightness(self, brightness, duration) -> None:
if brightness:
_LOGGER.debug('Setting brightness: %s', brightness)
self._bulb.set_brightness(((brightness / 255) * 100), duration=duration) |
@_cmd
def set_rgb(self, rgb, duration) -> None:
"Set bulb's color."
if (rgb and (self.supported_features & SUPPORT_COLOR)):
_LOGGER.debug('Setting RGB: %s', rgb)
self._bulb.set_rgb(rgb[0], rgb[1], rgb[2], duration=duration) | -9,165,789,828,462,820,000 | Set bulb's color. | homeassistant/components/light/yeelight.py | set_rgb | DevRGT/home-assistant | python | @_cmd
def set_rgb(self, rgb, duration) -> None:
if (rgb and (self.supported_features & SUPPORT_COLOR)):
_LOGGER.debug('Setting RGB: %s', rgb)
self._bulb.set_rgb(rgb[0], rgb[1], rgb[2], duration=duration) |
@_cmd
def set_colortemp(self, colortemp, duration) -> None:
"Set bulb's color temperature."
if (colortemp and (self.supported_features & SUPPORT_COLOR_TEMP)):
temp_in_k = mired_to_kelvin(colortemp)
_LOGGER.debug('Setting color temp: %s K', temp_in_k)
self._bulb.set_color_temp(temp_in_k, ... | -5,806,106,555,384,193,000 | Set bulb's color temperature. | homeassistant/components/light/yeelight.py | set_colortemp | DevRGT/home-assistant | python | @_cmd
def set_colortemp(self, colortemp, duration) -> None:
if (colortemp and (self.supported_features & SUPPORT_COLOR_TEMP)):
temp_in_k = mired_to_kelvin(colortemp)
_LOGGER.debug('Setting color temp: %s K', temp_in_k)
self._bulb.set_color_temp(temp_in_k, duration=duration) |
@_cmd
def set_default(self) -> None:
'Set current options as default.'
self._bulb.set_default() | -2,304,011,003,329,184,800 | Set current options as default. | homeassistant/components/light/yeelight.py | set_default | DevRGT/home-assistant | python | @_cmd
def set_default(self) -> None:
self._bulb.set_default() |
@_cmd
def set_flash(self, flash) -> None:
'Activate flash.'
if flash:
from yeelight import RGBTransition, SleepTransition, Flow, BulbException
if (self._bulb.last_properties['color_mode'] != 1):
_LOGGER.error('Flash supported currently only in RGB mode.')
return
t... | 5,451,685,536,072,715,000 | Activate flash. | homeassistant/components/light/yeelight.py | set_flash | DevRGT/home-assistant | python | @_cmd
def set_flash(self, flash) -> None:
if flash:
from yeelight import RGBTransition, SleepTransition, Flow, BulbException
if (self._bulb.last_properties['color_mode'] != 1):
_LOGGER.error('Flash supported currently only in RGB mode.')
return
transition = int(s... |
@_cmd
def set_effect(self, effect) -> None:
'Activate effect.'
if effect:
from yeelight import Flow, BulbException
from yeelight.transitions import disco, temp, strobe, pulse, strobe_color, alarm, police, police2, christmas, rgb, randomloop, slowdown
if (effect == EFFECT_STOP):
... | -6,212,819,468,885,633,000 | Activate effect. | homeassistant/components/light/yeelight.py | set_effect | DevRGT/home-assistant | python | @_cmd
def set_effect(self, effect) -> None:
if effect:
from yeelight import Flow, BulbException
from yeelight.transitions import disco, temp, strobe, pulse, strobe_color, alarm, police, police2, christmas, rgb, randomloop, slowdown
if (effect == EFFECT_STOP):
self._bulb.stop... |
def turn_on(self, **kwargs) -> None:
'Turn the bulb on.'
import yeelight
brightness = kwargs.get(ATTR_BRIGHTNESS)
colortemp = kwargs.get(ATTR_COLOR_TEMP)
hs_color = kwargs.get(ATTR_HS_COLOR)
rgb = (color_util.color_hs_to_RGB(*hs_color) if hs_color else None)
flash = kwargs.get(ATTR_FLASH)
... | -3,381,828,197,371,370,500 | Turn the bulb on. | homeassistant/components/light/yeelight.py | turn_on | DevRGT/home-assistant | python | def turn_on(self, **kwargs) -> None:
import yeelight
brightness = kwargs.get(ATTR_BRIGHTNESS)
colortemp = kwargs.get(ATTR_COLOR_TEMP)
hs_color = kwargs.get(ATTR_HS_COLOR)
rgb = (color_util.color_hs_to_RGB(*hs_color) if hs_color else None)
flash = kwargs.get(ATTR_FLASH)
effect = kwargs.g... |
def turn_off(self, **kwargs) -> None:
'Turn off.'
import yeelight
duration = int(self.config[CONF_TRANSITION])
if (ATTR_TRANSITION in kwargs):
duration = int((kwargs.get(ATTR_TRANSITION) * 1000))
try:
self._bulb.turn_off(duration=duration)
except yeelight.BulbException as ex:
... | -5,587,446,905,218,160,000 | Turn off. | homeassistant/components/light/yeelight.py | turn_off | DevRGT/home-assistant | python | def turn_off(self, **kwargs) -> None:
import yeelight
duration = int(self.config[CONF_TRANSITION])
if (ATTR_TRANSITION in kwargs):
duration = int((kwargs.get(ATTR_TRANSITION) * 1000))
try:
self._bulb.turn_off(duration=duration)
except yeelight.BulbException as ex:
_LOGGE... |
def set_mode(self, mode: str):
'Set a power mode.'
import yeelight
try:
self._bulb.set_power_mode(yeelight.enums.PowerMode[mode.upper()])
except yeelight.BulbException as ex:
_LOGGER.error('Unable to set the power mode: %s', ex) | 1,404,244,294,184,249,000 | Set a power mode. | homeassistant/components/light/yeelight.py | set_mode | DevRGT/home-assistant | python | def set_mode(self, mode: str):
import yeelight
try:
self._bulb.set_power_mode(yeelight.enums.PowerMode[mode.upper()])
except yeelight.BulbException as ex:
_LOGGER.error('Unable to set the power mode: %s', ex) |
def addSymbol(self, char):
'Displays the inputted char onto the display'
self.stringContents += char
self.displayStr.set(self.stringContents) | -116,713,786,399,674,820 | Displays the inputted char onto the display | ProgrammingInPython/proj08_daniel_campos.py | addSymbol | spacemanidol/RPICS | python | def addSymbol(self, char):
self.stringContents += char
self.displayStr.set(self.stringContents) |
def addKeyboardSymbol(self, event):
'Displays the inputted char onto the display'
self.stringContents += str(repr(event.char))[1:(- 1)]
self.displayStr.set(self.stringContents) | 8,320,440,915,511,281,000 | Displays the inputted char onto the display | ProgrammingInPython/proj08_daniel_campos.py | addKeyboardSymbol | spacemanidol/RPICS | python | def addKeyboardSymbol(self, event):
self.stringContents += str(repr(event.char))[1:(- 1)]
self.displayStr.set(self.stringContents) |
def evaluate(self, evt=None):
'Evalutes the expression'
try:
self.displayStr.set(eval(self.stringContents))
self.stringContents = str(eval(self.stringContents))
except Exception as e:
self.displayStr.set('Error')
self.stringContents = '' | 5,710,872,660,080,229,000 | Evalutes the expression | ProgrammingInPython/proj08_daniel_campos.py | evaluate | spacemanidol/RPICS | python | def evaluate(self, evt=None):
try:
self.displayStr.set(eval(self.stringContents))
self.stringContents = str(eval(self.stringContents))
except Exception as e:
self.displayStr.set('Error')
self.stringContents = |
def clear(self, evt=None):
'Clears the expression'
self.stringContents = ''
self.displayStr.set(self.stringContents) | 3,363,923,291,867,862,000 | Clears the expression | ProgrammingInPython/proj08_daniel_campos.py | clear | spacemanidol/RPICS | python | def clear(self, evt=None):
self.stringContents =
self.displayStr.set(self.stringContents) |
def backSpace(self, evt=None):
'Backspace on expression'
self.stringContents = self.stringContents[:(- 1)]
self.displayStr.set(self.stringContents) | 7,594,805,476,417,825,000 | Backspace on expression | ProgrammingInPython/proj08_daniel_campos.py | backSpace | spacemanidol/RPICS | python | def backSpace(self, evt=None):
self.stringContents = self.stringContents[:(- 1)]
self.displayStr.set(self.stringContents) |
def count_samples(ns_run, **kwargs):
'Number of samples in run.\n\n Unlike most estimators this does not require log weights, but for\n convenience will not throw an error if they are specified.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing modu... | 4,457,394,597,630,097,400 | Number of samples in run.
Unlike most estimators this does not require log weights, but for
convenience will not throw an error if they are specified.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
Returns
-------
int | nestcheck/estimators.py | count_samples | ThomasEdwardRiley/nestcheck | python | def count_samples(ns_run, **kwargs):
'Number of samples in run.\n\n Unlike most estimators this does not require log weights, but for\n convenience will not throw an error if they are specified.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing modu... |
def logz(ns_run, logw=None, simulate=False):
'Natural log of Bayesian evidence :math:`\\log \\mathcal{Z}`.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n ... | -5,927,102,853,806,405,000 | Natural log of Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if ... | nestcheck/estimators.py | logz | ThomasEdwardRiley/nestcheck | python | def logz(ns_run, logw=None, simulate=False):
'Natural log of Bayesian evidence :math:`\\log \\mathcal{Z}`.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n ... |
def evidence(ns_run, logw=None, simulate=False):
'Bayesian evidence :math:`\\log \\mathcal{Z}`.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n Log weights... | 2,010,785,813,126,751,500 | Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if logw needs to b... | nestcheck/estimators.py | evidence | ThomasEdwardRiley/nestcheck | python | def evidence(ns_run, logw=None, simulate=False):
'Bayesian evidence :math:`\\log \\mathcal{Z}`.\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n Log weights... |
def param_mean(ns_run, logw=None, simulate=False, param_ind=0, handle_indexerror=False):
"Mean of a single parameter (single component of theta).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: Non... | 3,105,416,283,611,357,700 | Mean of a single parameter (single component of theta).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if log... | nestcheck/estimators.py | param_mean | ThomasEdwardRiley/nestcheck | python | def param_mean(ns_run, logw=None, simulate=False, param_ind=0, handle_indexerror=False):
"Mean of a single parameter (single component of theta).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: Non... |
def param_cred(ns_run, logw=None, simulate=False, probability=0.5, param_ind=0):
"One-tailed credible interval on the value of a single parameter\n (component of theta).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for mo... | 4,726,149,972,506,099,000 | One-tailed credible interval on the value of a single parameter
(component of theta).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed t... | nestcheck/estimators.py | param_cred | ThomasEdwardRiley/nestcheck | python | def param_cred(ns_run, logw=None, simulate=False, probability=0.5, param_ind=0):
"One-tailed credible interval on the value of a single parameter\n (component of theta).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for mo... |
def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=0):
"Mean of the square of single parameter (second moment of its\n posterior distribution).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more detail... | 1,526,012,662,973,918,200 | Mean of the square of single parameter (second moment of its
posterior distribution).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed t... | nestcheck/estimators.py | param_squared_mean | ThomasEdwardRiley/nestcheck | python | def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=0):
"Mean of the square of single parameter (second moment of its\n posterior distribution).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more detail... |
def r_mean(ns_run, logw=None, simulate=False):
'Mean of the radial coordinate (magnitude of theta vector).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n ... | -438,064,546,922,247,500 | Mean of the radial coordinate (magnitude of theta vector).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ns_run_utils.get_logw if ... | nestcheck/estimators.py | r_mean | ThomasEdwardRiley/nestcheck | python | def r_mean(ns_run, logw=None, simulate=False):
'Mean of the radial coordinate (magnitude of theta vector).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more details).\n logw: None or 1d numpy array, optional\n ... |
def r_cred(ns_run, logw=None, simulate=False, probability=0.5):
'One-tailed credible interval on the value of the radial coordinate\n (magnitude of theta vector).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more deta... | -7,417,632,296,846,792,000 | One-tailed credible interval on the value of the radial coordinate
(magnitude of theta vector).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
... | nestcheck/estimators.py | r_cred | ThomasEdwardRiley/nestcheck | python | def r_cred(ns_run, logw=None, simulate=False, probability=0.5):
'One-tailed credible interval on the value of the radial coordinate\n (magnitude of theta vector).\n\n Parameters\n ----------\n ns_run: dict\n Nested sampling run dict (see the data_processing module\n docstring for more deta... |
def get_latex_name(func_in, **kwargs):
'\n Produce a latex formatted name for each function for use in labelling\n results.\n\n Parameters\n ----------\n func_in: function\n kwargs: dict, optional\n Kwargs for function.\n\n Returns\n -------\n latex_name: str\n Latex formatt... | 6,843,338,948,465,915,000 | Produce a latex formatted name for each function for use in labelling
results.
Parameters
----------
func_in: function
kwargs: dict, optional
Kwargs for function.
Returns
-------
latex_name: str
Latex formatted name for the function. | nestcheck/estimators.py | get_latex_name | ThomasEdwardRiley/nestcheck | python | def get_latex_name(func_in, **kwargs):
'\n Produce a latex formatted name for each function for use in labelling\n results.\n\n Parameters\n ----------\n func_in: function\n kwargs: dict, optional\n Kwargs for function.\n\n Returns\n -------\n latex_name: str\n Latex formatt... |
def weighted_quantile(probability, values, weights):
'\n Get quantile estimate for input probability given weighted samples using\n linear interpolation.\n\n Parameters\n ----------\n probability: float\n Quantile to estimate - must be in open interval (0, 1).\n For example, use 0.5 for... | -5,182,723,951,505,794,000 | Get quantile estimate for input probability given weighted samples using
linear interpolation.
Parameters
----------
probability: float
Quantile to estimate - must be in open interval (0, 1).
For example, use 0.5 for the median and 0.84 for the upper
84% quantile.
values: 1d numpy array
Sample values.
... | nestcheck/estimators.py | weighted_quantile | ThomasEdwardRiley/nestcheck | python | def weighted_quantile(probability, values, weights):
'\n Get quantile estimate for input probability given weighted samples using\n linear interpolation.\n\n Parameters\n ----------\n probability: float\n Quantile to estimate - must be in open interval (0, 1).\n For example, use 0.5 for... |
def _is_sqlite_json1_enabled():
'Check if SQLite implementation includes JSON1 extension.'
con = sqlite3.connect(':memory:')
try:
con.execute("SELECT json_valid('123')")
except sqlite3.OperationalError:
return False
finally:
con.close()
return True | 7,702,032,116,213,631,000 | Check if SQLite implementation includes JSON1 extension. | toron/_node_schema.py | _is_sqlite_json1_enabled | shawnbrown/gpn | python | def _is_sqlite_json1_enabled():
con = sqlite3.connect(':memory:')
try:
con.execute("SELECT json_valid('123')")
except sqlite3.OperationalError:
return False
finally:
con.close()
return True |
def _is_wellformed_json(x):
'Return 1 if *x* is well-formed JSON or return 0 if *x* is not\n well-formed. This function should be registered with SQLite (via\n the create_function() method) when the JSON1 extension is not\n available.\n\n This function mimics the JSON1 json_valid() function, see:\n ... | -7,860,604,478,455,344,000 | Return 1 if *x* is well-formed JSON or return 0 if *x* is not
well-formed. This function should be registered with SQLite (via
the create_function() method) when the JSON1 extension is not
available.
This function mimics the JSON1 json_valid() function, see:
https://www.sqlite.org/json1.html#jvalid | toron/_node_schema.py | _is_wellformed_json | shawnbrown/gpn | python | def _is_wellformed_json(x):
'Return 1 if *x* is well-formed JSON or return 0 if *x* is not\n well-formed. This function should be registered with SQLite (via\n the create_function() method) when the JSON1 extension is not\n available.\n\n This function mimics the JSON1 json_valid() function, see:\n ... |
def _make_trigger_for_json(insert_or_update, table, column):
'Return a SQL statement for creating a temporary trigger. The\n trigger is used to validate the contents of TEXT_JSON type columns.\n The trigger will pass without error if the JSON is wellformed.\n '
if (insert_or_update.upper() not in {'INS... | -861,732,227,289,730,800 | Return a SQL statement for creating a temporary trigger. The
trigger is used to validate the contents of TEXT_JSON type columns.
The trigger will pass without error if the JSON is wellformed. | toron/_node_schema.py | _make_trigger_for_json | shawnbrown/gpn | python | def _make_trigger_for_json(insert_or_update, table, column):
'Return a SQL statement for creating a temporary trigger. The\n trigger is used to validate the contents of TEXT_JSON type columns.\n The trigger will pass without error if the JSON is wellformed.\n '
if (insert_or_update.upper() not in {'INS... |
def _is_wellformed_user_properties(x):
"Check if *x* is a wellformed TEXT_USERPROPERTIES value.\n A wellformed TEXT_USERPROPERTIES value is a string containing\n a JSON formatted object. Returns 1 if *x* is valid or 0 if\n it's not.\n\n This function should be registered as an application-defined\n S... | -7,747,161,462,159,716,000 | Check if *x* is a wellformed TEXT_USERPROPERTIES value.
A wellformed TEXT_USERPROPERTIES value is a string containing
a JSON formatted object. Returns 1 if *x* is valid or 0 if
it's not.
This function should be registered as an application-defined
SQL function and used in queries when SQLite's JSON1 extension
is not e... | toron/_node_schema.py | _is_wellformed_user_properties | shawnbrown/gpn | python | def _is_wellformed_user_properties(x):
"Check if *x* is a wellformed TEXT_USERPROPERTIES value.\n A wellformed TEXT_USERPROPERTIES value is a string containing\n a JSON formatted object. Returns 1 if *x* is valid or 0 if\n it's not.\n\n This function should be registered as an application-defined\n S... |
def _make_trigger_for_user_properties(insert_or_update, table, column):
'Return a CREATE TRIGGER statement to check TEXT_USERPROPERTIES\n values. This trigger is used to check values before they are saved\n in the database.\n\n A wellformed TEXT_USERPROPERTIES value is a string containing\n a JSON forma... | 6,090,807,620,620,976,000 | Return a CREATE TRIGGER statement to check TEXT_USERPROPERTIES
values. This trigger is used to check values before they are saved
in the database.
A wellformed TEXT_USERPROPERTIES value is a string containing
a JSON formatted object.
The trigger will pass without error if the value is wellformed. | toron/_node_schema.py | _make_trigger_for_user_properties | shawnbrown/gpn | python | def _make_trigger_for_user_properties(insert_or_update, table, column):
'Return a CREATE TRIGGER statement to check TEXT_USERPROPERTIES\n values. This trigger is used to check values before they are saved\n in the database.\n\n A wellformed TEXT_USERPROPERTIES value is a string containing\n a JSON forma... |
def _is_wellformed_attributes(x):
'Returns 1 if *x* is a wellformed TEXT_ATTRIBUTES column\n value else returns 0. TEXT_ATTRIBUTES should be flat, JSON\n object strings. This function should be registered with SQLite\n (via the create_function() method) when the JSON1 extension\n is not available.\n ... | -2,626,542,635,610,831,000 | Returns 1 if *x* is a wellformed TEXT_ATTRIBUTES column
value else returns 0. TEXT_ATTRIBUTES should be flat, JSON
object strings. This function should be registered with SQLite
(via the create_function() method) when the JSON1 extension
is not available. | toron/_node_schema.py | _is_wellformed_attributes | shawnbrown/gpn | python | def _is_wellformed_attributes(x):
'Returns 1 if *x* is a wellformed TEXT_ATTRIBUTES column\n value else returns 0. TEXT_ATTRIBUTES should be flat, JSON\n object strings. This function should be registered with SQLite\n (via the create_function() method) when the JSON1 extension\n is not available.\n ... |
def _make_trigger_for_attributes(insert_or_update, table, column):
'Return a SQL statement for creating a temporary trigger. The\n trigger is used to validate the contents of TEXT_ATTRIBUTES\n type columns.\n\n The trigger will pass without error if the JSON is a wellformed\n "object" containing "text" ... | 8,810,595,410,914,199,000 | Return a SQL statement for creating a temporary trigger. The
trigger is used to validate the contents of TEXT_ATTRIBUTES
type columns.
The trigger will pass without error if the JSON is a wellformed
"object" containing "text" values.
The trigger will raise an error if the value is:
* not wellformed JSON
* not an... | toron/_node_schema.py | _make_trigger_for_attributes | shawnbrown/gpn | python | def _make_trigger_for_attributes(insert_or_update, table, column):
'Return a SQL statement for creating a temporary trigger. The\n trigger is used to validate the contents of TEXT_ATTRIBUTES\n type columns.\n\n The trigger will pass without error if the JSON is a wellformed\n "object" containing "text" ... |
def _add_functions_and_triggers(connection):
'Create triggers and application-defined functions *connection*.\n\n Note: This function must not be executed on an empty connection.\n The table schema must exist before triggers can be created.\n '
if (not SQLITE_JSON1_ENABLED):
try:
co... | -3,662,904,084,164,747,300 | Create triggers and application-defined functions *connection*.
Note: This function must not be executed on an empty connection.
The table schema must exist before triggers can be created. | toron/_node_schema.py | _add_functions_and_triggers | shawnbrown/gpn | python | def _add_functions_and_triggers(connection):
'Create triggers and application-defined functions *connection*.\n\n Note: This function must not be executed on an empty connection.\n The table schema must exist before triggers can be created.\n '
if (not SQLITE_JSON1_ENABLED):
try:
co... |
def _path_to_sqlite_uri(path):
"Convert a path into a SQLite compatible URI.\n\n Unlike pathlib's URI handling, SQLite accepts relative URI paths.\n For details, see:\n\n https://www.sqlite.org/uri.html#the_uri_path\n "
if (os.name == 'nt'):
if re.match('^[a-zA-Z]:', path):
p... | -3,435,782,394,609,266,700 | Convert a path into a SQLite compatible URI.
Unlike pathlib's URI handling, SQLite accepts relative URI paths.
For details, see:
https://www.sqlite.org/uri.html#the_uri_path | toron/_node_schema.py | _path_to_sqlite_uri | shawnbrown/gpn | python | def _path_to_sqlite_uri(path):
"Convert a path into a SQLite compatible URI.\n\n Unlike pathlib's URI handling, SQLite accepts relative URI paths.\n For details, see:\n\n https://www.sqlite.org/uri.html#the_uri_path\n "
if (os.name == 'nt'):
if re.match('^[a-zA-Z]:', path):
p... |
def connect(path, mode='rwc'):
'Returns a sqlite3 connection to a Toron node file.'
uri_path = _path_to_sqlite_uri(path)
uri_path = f'{uri_path}?mode={mode}'
try:
get_connection = (lambda : sqlite3.connect(database=uri_path, detect_types=sqlite3.PARSE_DECLTYPES, isolation_level=None, uri=True))
... | 244,127,551,233,007,550 | Returns a sqlite3 connection to a Toron node file. | toron/_node_schema.py | connect | shawnbrown/gpn | python | def connect(path, mode='rwc'):
uri_path = _path_to_sqlite_uri(path)
uri_path = f'{uri_path}?mode={mode}'
try:
get_connection = (lambda : sqlite3.connect(database=uri_path, detect_types=sqlite3.PARSE_DECLTYPES, isolation_level=None, uri=True))
if os.path.exists(path):
con = g... |
@contextmanager
def transaction(path_or_connection, mode=None):
'A context manager that yields a cursor that runs in an\n isolated transaction. If the context manager exits without\n errors, the transaction is committed. If an exception is\n raised, all changes are rolled-back.\n '
if isinstance(pat... | 4,488,582,226,618,593,300 | A context manager that yields a cursor that runs in an
isolated transaction. If the context manager exits without
errors, the transaction is committed. If an exception is
raised, all changes are rolled-back. | toron/_node_schema.py | transaction | shawnbrown/gpn | python | @contextmanager
def transaction(path_or_connection, mode=None):
'A context manager that yields a cursor that runs in an\n isolated transaction. If the context manager exits without\n errors, the transaction is committed. If an exception is\n raised, all changes are rolled-back.\n '
if isinstance(pat... |
def run(cmd, *args, **kwargs):
'Echo a command before running it'
log.info(('> ' + list2cmdline(cmd)))
kwargs['shell'] = (sys.platform == 'win32')
return check_call(cmd, *args, **kwargs) | -821,275,233,338,806,500 | Echo a command before running it | setupbase.py | run | bualpha/jupyterlab | python | def run(cmd, *args, **kwargs):
log.info(('> ' + list2cmdline(cmd)))
kwargs['shell'] = (sys.platform == 'win32')
return check_call(cmd, *args, **kwargs) |
def find_packages():
'\n Find all of the packages.\n '
packages = []
for (dir, subdirs, files) in os.walk('jupyterlab'):
if ('node_modules' in subdirs):
subdirs.remove('node_modules')
package = dir.replace(osp.sep, '.')
if ('__init__.py' not in files):
c... | 8,569,758,962,851,079,000 | Find all of the packages. | setupbase.py | find_packages | bualpha/jupyterlab | python | def find_packages():
'\n \n '
packages = []
for (dir, subdirs, files) in os.walk('jupyterlab'):
if ('node_modules' in subdirs):
subdirs.remove('node_modules')
package = dir.replace(osp.sep, '.')
if ('__init__.py' not in files):
continue
packages.... |
def find_package_data():
'\n Find package_data.\n '
theme_dirs = []
for (dir, subdirs, files) in os.walk(pjoin('jupyterlab', 'themes')):
slice_len = len(('jupyterlab' + os.sep))
theme_dirs.append(pjoin(dir[slice_len:], '*'))
schema_dirs = []
for (dir, subdirs, files) in os.walk... | -2,900,111,418,617,660,400 | Find package_data. | setupbase.py | find_package_data | bualpha/jupyterlab | python | def find_package_data():
'\n \n '
theme_dirs = []
for (dir, subdirs, files) in os.walk(pjoin('jupyterlab', 'themes')):
slice_len = len(('jupyterlab' + os.sep))
theme_dirs.append(pjoin(dir[slice_len:], '*'))
schema_dirs = []
for (dir, subdirs, files) in os.walk(pjoin('jupyterlab... |
def find_data_files():
'\n Find data_files.\n '
if (not os.path.exists(pjoin('jupyterlab', 'build'))):
return []
files = []
static_files = os.listdir(pjoin('jupyterlab', 'build'))
files.append(('share/jupyter/lab/static', [('jupyterlab/build/%s' % f) for f in static_files]))
for (d... | -157,557,035,968,105,020 | Find data_files. | setupbase.py | find_data_files | bualpha/jupyterlab | python | def find_data_files():
'\n \n '
if (not os.path.exists(pjoin('jupyterlab', 'build'))):
return []
files = []
static_files = os.listdir(pjoin('jupyterlab', 'build'))
files.append(('share/jupyter/lab/static', [('jupyterlab/build/%s' % f) for f in static_files]))
for (dir, subdirs, fna... |
def js_prerelease(command, strict=False):
'decorator for building minified js/css prior to another command'
class DecoratedCommand(command):
def run(self):
jsdeps = self.distribution.get_command_obj('jsdeps')
if ((not is_repo) and all((osp.exists(t) for t in jsdeps.targets))):
... | -9,103,179,315,340,882,000 | decorator for building minified js/css prior to another command | setupbase.py | js_prerelease | bualpha/jupyterlab | python | def js_prerelease(command, strict=False):
class DecoratedCommand(command):
def run(self):
jsdeps = self.distribution.get_command_obj('jsdeps')
if ((not is_repo) and all((osp.exists(t) for t in jsdeps.targets))):
command.run(self)
return
... |
def update_package_data(distribution):
'update build_py options to get package_data changes'
build_py = distribution.get_command_obj('build_py')
build_py.finalize_options() | -7,966,824,714,045,736,000 | update build_py options to get package_data changes | setupbase.py | update_package_data | bualpha/jupyterlab | python | def update_package_data(distribution):
build_py = distribution.get_command_obj('build_py')
build_py.finalize_options() |
@classmethod
def _find_playlist_info(cls, response):
'\n Finds playlist info (type, id) in HTTP response.\n\n :param response: Response object.\n :returns: Dictionary with type and id.\n '
values = {}
matches = cls._playlist_info_re.search(response.text)
if matches:
v... | -5,611,080,266,467,536,000 | Finds playlist info (type, id) in HTTP response.
:param response: Response object.
:returns: Dictionary with type and id. | src/streamlink/plugins/ceskatelevize.py | _find_playlist_info | Erk-/streamlink | python | @classmethod
def _find_playlist_info(cls, response):
'\n Finds playlist info (type, id) in HTTP response.\n\n :param response: Response object.\n :returns: Dictionary with type and id.\n '
values = {}
matches = cls._playlist_info_re.search(response.text)
if matches:
v... |
@classmethod
def _find_player_url(cls, response):
'\n Finds embedded player url in HTTP response.\n\n :param response: Response object.\n :returns: Player url (str).\n '
url = ''
matches = cls._player_re.search(response.text)
if matches:
tmp_url = matches.group(0).rep... | 9,190,241,898,436,455,000 | Finds embedded player url in HTTP response.
:param response: Response object.
:returns: Player url (str). | src/streamlink/plugins/ceskatelevize.py | _find_player_url | Erk-/streamlink | python | @classmethod
def _find_player_url(cls, response):
'\n Finds embedded player url in HTTP response.\n\n :param response: Response object.\n :returns: Player url (str).\n '
url =
matches = cls._player_re.search(response.text)
if matches:
tmp_url = matches.group(0).repla... |
def main():
'Main routine'
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('device', nargs='?', default='ftdi:///?', help='serial port device name')
argparser.add_argument('-x', '--hexdump', action='store_true', help='dump E... | 5,579,499,725,529,677,000 | Main routine | bin/ftconf.py | main | andrario/API_Estacao | python | def main():
debug = False
try:
argparser = ArgumentParser(description=modules[__name__].__doc__)
argparser.add_argument('device', nargs='?', default='ftdi:///?', help='serial port device name')
argparser.add_argument('-x', '--hexdump', action='store_true', help='dump EEPROM content ... |
def _analyze_result_columns(self, query: Query):
'Given info on a list of SELECTs, determine whether to warn.'
if (not query.selectables):
return
for selectable in query.selectables:
self.logger.debug(f'Analyzing query: {selectable.selectable.raw}')
for wildcard in selectable.get_wil... | -8,042,192,610,915,090,000 | Given info on a list of SELECTs, determine whether to warn. | src/sqlfluff/rules/L044.py | _analyze_result_columns | R7L208/sqlfluff | python | def _analyze_result_columns(self, query: Query):
if (not query.selectables):
return
for selectable in query.selectables:
self.logger.debug(f'Analyzing query: {selectable.selectable.raw}')
for wildcard in selectable.get_wildcard_info():
if wildcard.tables:
... |
def _eval(self, context: RuleContext) -> Optional[LintResult]:
'Outermost query should produce known number of columns.'
start_types = ['select_statement', 'set_expression', 'with_compound_statement']
if (context.segment.is_type(*start_types) and (not context.functional.parent_stack.any(sp.is_type(*start_ty... | -4,919,894,665,587,562,000 | Outermost query should produce known number of columns. | src/sqlfluff/rules/L044.py | _eval | R7L208/sqlfluff | python | def _eval(self, context: RuleContext) -> Optional[LintResult]:
start_types = ['select_statement', 'set_expression', 'with_compound_statement']
if (context.segment.is_type(*start_types) and (not context.functional.parent_stack.any(sp.is_type(*start_types)))):
crawler = SelectCrawler(context.segment,... |
def imread(filename, *args, **kwargs):
'Read and decode an image to an NDArray.\n\n Note: `imread` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.\n\n Parameters\n ----------\n filename : str\n Name of the image file to be loaded... | 5,817,983,858,285,566,000 | Read and decode an image to an NDArray.
Note: `imread` uses OpenCV (not the CV2 Python library).
MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.
Parameters
----------
filename : str
Name of the image file to be loaded.
flag : {0, 1}, default 1
1 for three channel color output. 0 for grays... | python/mxnet/image/image.py | imread | Vikas89/private-mxnet | python | def imread(filename, *args, **kwargs):
'Read and decode an image to an NDArray.\n\n Note: `imread` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.\n\n Parameters\n ----------\n filename : str\n Name of the image file to be loaded... |
def imdecode(buf, *args, **kwargs):
'Decode an image to an NDArray.\n\n Note: `imdecode` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.\n\n Parameters\n ----------\n buf : str/bytes or numpy.ndarray\n Binary image data as string... | -3,713,905,794,887,272,400 | Decode an image to an NDArray.
Note: `imdecode` uses OpenCV (not the CV2 Python library).
MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.
Parameters
----------
buf : str/bytes or numpy.ndarray
Binary image data as string or numpy ndarray.
flag : int, optional, default=1
1 for three channe... | python/mxnet/image/image.py | imdecode | Vikas89/private-mxnet | python | def imdecode(buf, *args, **kwargs):
'Decode an image to an NDArray.\n\n Note: `imdecode` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with USE_OPENCV=1 for `imdecode` to work.\n\n Parameters\n ----------\n buf : str/bytes or numpy.ndarray\n Binary image data as string... |
def scale_down(src_size, size):
"Scales down crop size if it's larger than image size.\n\n If width/height of the crop is larger than the width/height of the image,\n sets the width/height to the width/height of the image.\n\n Parameters\n ----------\n src_size : tuple of int\n Size of the ima... | -209,325,311,614,370,940 | Scales down crop size if it's larger than image size.
If width/height of the crop is larger than the width/height of the image,
sets the width/height to the width/height of the image.
Parameters
----------
src_size : tuple of int
Size of the image in (width, height) format.
size : tuple of int
Size of the cro... | python/mxnet/image/image.py | scale_down | Vikas89/private-mxnet | python | def scale_down(src_size, size):
"Scales down crop size if it's larger than image size.\n\n If width/height of the crop is larger than the width/height of the image,\n sets the width/height to the width/height of the image.\n\n Parameters\n ----------\n src_size : tuple of int\n Size of the ima... |
def _get_interp_method(interp, sizes=()):
'Get the interpolation method for resize functions.\n The major purpose of this function is to wrap a random interp method selection\n and a auto-estimation method.\n\n Parameters\n ----------\n interp : int\n interpolation method for all resizing oper... | 4,209,777,761,857,167,000 | Get the interpolation method for resize functions.
The major purpose of this function is to wrap a random interp method selection
and a auto-estimation method.
Parameters
----------
interp : int
interpolation method for all resizing operations
Possible values:
0: Nearest Neighbors Interpolation.
1: Bi... | python/mxnet/image/image.py | _get_interp_method | Vikas89/private-mxnet | python | def _get_interp_method(interp, sizes=()):
'Get the interpolation method for resize functions.\n The major purpose of this function is to wrap a random interp method selection\n and a auto-estimation method.\n\n Parameters\n ----------\n interp : int\n interpolation method for all resizing oper... |
def resize_short(src, size, interp=2):
'Resizes shorter edge to size.\n\n Note: `resize_short` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with OpenCV for `resize_short` to work.\n\n Resizes the original image by setting the shorter edge to size\n and setting the longer edge a... | -4,620,161,702,122,637,000 | Resizes shorter edge to size.
Note: `resize_short` uses OpenCV (not the CV2 Python library).
MXNet must have been built with OpenCV for `resize_short` to work.
Resizes the original image by setting the shorter edge to size
and setting the longer edge accordingly.
Resizing function is called from OpenCV.
Parameters
-... | python/mxnet/image/image.py | resize_short | Vikas89/private-mxnet | python | def resize_short(src, size, interp=2):
'Resizes shorter edge to size.\n\n Note: `resize_short` uses OpenCV (not the CV2 Python library).\n MXNet must have been built with OpenCV for `resize_short` to work.\n\n Resizes the original image by setting the shorter edge to size\n and setting the longer edge a... |
def fixed_crop(src, x0, y0, w, h, size=None, interp=2):
'Crop src at fixed location, and (optionally) resize it to size.\n\n Parameters\n ----------\n src : NDArray\n Input image\n x0 : int\n Left boundary of the cropping area\n y0 : int\n Top boundary of the cropping area\n w... | -4,619,619,017,581,396,000 | Crop src at fixed location, and (optionally) resize it to size.
Parameters
----------
src : NDArray
Input image
x0 : int
Left boundary of the cropping area
y0 : int
Top boundary of the cropping area
w : int
Width of the cropping area
h : int
Height of the cropping area
size : tuple of (w, h)
Op... | python/mxnet/image/image.py | fixed_crop | Vikas89/private-mxnet | python | def fixed_crop(src, x0, y0, w, h, size=None, interp=2):
'Crop src at fixed location, and (optionally) resize it to size.\n\n Parameters\n ----------\n src : NDArray\n Input image\n x0 : int\n Left boundary of the cropping area\n y0 : int\n Top boundary of the cropping area\n w... |
def random_crop(src, size, interp=2):
'Randomly crop `src` with `size` (width, height).\n Upsample result if `src` is smaller than `size`.\n\n Parameters\n ----------\n src: Source image `NDArray`\n size: Size of the crop formatted as (width, height). If the `size` is larger\n than the imag... | -4,275,306,880,614,285,000 | Randomly crop `src` with `size` (width, height).
Upsample result if `src` is smaller than `size`.
Parameters
----------
src: Source image `NDArray`
size: Size of the crop formatted as (width, height). If the `size` is larger
than the image, then the source image is upsampled to `size` and returned.
interp: int,... | python/mxnet/image/image.py | random_crop | Vikas89/private-mxnet | python | def random_crop(src, size, interp=2):
'Randomly crop `src` with `size` (width, height).\n Upsample result if `src` is smaller than `size`.\n\n Parameters\n ----------\n src: Source image `NDArray`\n size: Size of the crop formatted as (width, height). If the `size` is larger\n than the imag... |
def center_crop(src, size, interp=2):
'Crops the image `src` to the given `size` by trimming on all four\n sides and preserving the center of the image. Upsamples if `src` is smaller\n than `size`.\n\n .. note:: This requires MXNet to be compiled with USE_OPENCV.\n\n Parameters\n ----------\n src ... | 6,517,003,938,661,321,000 | Crops the image `src` to the given `size` by trimming on all four
sides and preserving the center of the image. Upsamples if `src` is smaller
than `size`.
.. note:: This requires MXNet to be compiled with USE_OPENCV.
Parameters
----------
src : NDArray
Binary source image data.
size : list or tuple of int
The... | python/mxnet/image/image.py | center_crop | Vikas89/private-mxnet | python | def center_crop(src, size, interp=2):
'Crops the image `src` to the given `size` by trimming on all four\n sides and preserving the center of the image. Upsamples if `src` is smaller\n than `size`.\n\n .. note:: This requires MXNet to be compiled with USE_OPENCV.\n\n Parameters\n ----------\n src ... |
def color_normalize(src, mean, std=None):
'Normalize src with mean and std.\n\n Parameters\n ----------\n src : NDArray\n Input image\n mean : NDArray\n RGB mean to be subtracted\n std : NDArray\n RGB standard deviation to be divided\n\n Returns\n -------\n NDArray\n ... | 1,318,848,124,312,677,400 | Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDArray` containing the normalized image. | python/mxnet/image/image.py | color_normalize | Vikas89/private-mxnet | python | def color_normalize(src, mean, std=None):
'Normalize src with mean and std.\n\n Parameters\n ----------\n src : NDArray\n Input image\n mean : NDArray\n RGB mean to be subtracted\n std : NDArray\n RGB standard deviation to be divided\n\n Returns\n -------\n NDArray\n ... |
def random_size_crop(src, size, area, ratio, interp=2, **kwargs):
'Randomly crop src with size. Randomize area and aspect ratio.\n\n Parameters\n ----------\n src : NDArray\n Input image\n size : tuple of (int, int)\n Size of the crop formatted as (width, height).\n area : float in (0, ... | 6,472,939,180,749,413,000 | Randomly crop src with size. Randomize area and aspect ratio.
Parameters
----------
src : NDArray
Input image
size : tuple of (int, int)
Size of the crop formatted as (width, height).
area : float in (0, 1] or tuple of (float, float)
If tuple, minimum area and maximum area to be maintained after cropping
... | python/mxnet/image/image.py | random_size_crop | Vikas89/private-mxnet | python | def random_size_crop(src, size, area, ratio, interp=2, **kwargs):
'Randomly crop src with size. Randomize area and aspect ratio.\n\n Parameters\n ----------\n src : NDArray\n Input image\n size : tuple of (int, int)\n Size of the crop formatted as (width, height).\n area : float in (0, ... |
def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0, pca_noise=0, rand_gray=0, inter_method=2):
'Creates an augmenter list.\n\n Parameters\n ----------\n data_shape : tuple of int\n Shape ... | 1,781,855,416,623,279,600 | Creates an augmenter list.
Parameters
----------
data_shape : tuple of int
Shape for output data
resize : int
Resize shorter edge if larger than 0 at the begining
rand_crop : bool
Whether to enable random cropping other than center crop
rand_resize : bool
Whether to enable random sized cropping, requir... | python/mxnet/image/image.py | CreateAugmenter | Vikas89/private-mxnet | python | def CreateAugmenter(data_shape, resize=0, rand_crop=False, rand_resize=False, rand_mirror=False, mean=None, std=None, brightness=0, contrast=0, saturation=0, hue=0, pca_noise=0, rand_gray=0, inter_method=2):
'Creates an augmenter list.\n\n Parameters\n ----------\n data_shape : tuple of int\n Shape ... |
def dumps(self):
'Saves the Augmenter to string\n\n Returns\n -------\n str\n JSON formatted string that describes the Augmenter.\n '
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) | 5,340,473,756,469,926,000 | Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter. | python/mxnet/image/image.py | dumps | Vikas89/private-mxnet | python | def dumps(self):
'Saves the Augmenter to string\n\n Returns\n -------\n str\n JSON formatted string that describes the Augmenter.\n '
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) |
def __call__(self, src):
'Abstract implementation body'
raise NotImplementedError('Must override implementation.') | 6,341,831,232,067,915,000 | Abstract implementation body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
raise NotImplementedError('Must override implementation.') |
def dumps(self):
'Override the default to avoid duplicate dump.'
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] | 5,817,320,955,584,513,000 | Override the default to avoid duplicate dump. | python/mxnet/image/image.py | dumps | Vikas89/private-mxnet | python | def dumps(self):
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] |
def __call__(self, src):
'Augmenter body'
for aug in self.ts:
src = aug(src)
return src | -1,729,443,728,950,751,500 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
for aug in self.ts:
src = aug(src)
return src |
def __call__(self, src):
'Augmenter body'
return resize_short(src, self.size, self.interp) | -8,370,831,105,102,411,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
return resize_short(src, self.size, self.interp) |
def __call__(self, src):
'Augmenter body'
sizes = (src.shape[0], src.shape[1], self.size[1], self.size[0])
return imresize(src, *self.size, interp=_get_interp_method(self.interp, sizes)) | -7,340,788,848,155,299,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
sizes = (src.shape[0], src.shape[1], self.size[1], self.size[0])
return imresize(src, *self.size, interp=_get_interp_method(self.interp, sizes)) |
def __call__(self, src):
'Augmenter body'
return random_crop(src, self.size, self.interp)[0] | 2,023,972,826,688,800,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
return random_crop(src, self.size, self.interp)[0] |
def __call__(self, src):
'Augmenter body'
return random_size_crop(src, self.size, self.area, self.ratio, self.interp)[0] | -7,275,055,935,349,442,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
return random_size_crop(src, self.size, self.area, self.ratio, self.interp)[0] |
def __call__(self, src):
'Augmenter body'
return center_crop(src, self.size, self.interp)[0] | -6,424,092,096,283,396,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
return center_crop(src, self.size, self.interp)[0] |
def dumps(self):
'Override the default to avoid duplicate dump.'
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] | 5,817,320,955,584,513,000 | Override the default to avoid duplicate dump. | python/mxnet/image/image.py | dumps | Vikas89/private-mxnet | python | def dumps(self):
return [self.__class__.__name__.lower(), [x.dumps() for x in self.ts]] |
def __call__(self, src):
'Augmenter body'
random.shuffle(self.ts)
for t in self.ts:
src = t(src)
return src | 3,099,077,576,856,897,500 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
random.shuffle(self.ts)
for t in self.ts:
src = t(src)
return src |
def __call__(self, src):
'Augmenter body'
alpha = (1.0 + random.uniform((- self.brightness), self.brightness))
src *= alpha
return src | -4,187,481,208,873,638,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
alpha = (1.0 + random.uniform((- self.brightness), self.brightness))
src *= alpha
return src |
def __call__(self, src):
'Augmenter body'
alpha = (1.0 + random.uniform((- self.contrast), self.contrast))
gray = (src * self.coef)
gray = (((3.0 * (1.0 - alpha)) / gray.size) * nd.sum(gray))
src *= alpha
src += gray
return src | 7,416,574,687,388,400,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
alpha = (1.0 + random.uniform((- self.contrast), self.contrast))
gray = (src * self.coef)
gray = (((3.0 * (1.0 - alpha)) / gray.size) * nd.sum(gray))
src *= alpha
src += gray
return src |
def __call__(self, src):
'Augmenter body'
alpha = (1.0 + random.uniform((- self.saturation), self.saturation))
gray = (src * self.coef)
gray = nd.sum(gray, axis=2, keepdims=True)
gray *= (1.0 - alpha)
src *= alpha
src += gray
return src | -9,177,407,812,149,575,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
alpha = (1.0 + random.uniform((- self.saturation), self.saturation))
gray = (src * self.coef)
gray = nd.sum(gray, axis=2, keepdims=True)
gray *= (1.0 - alpha)
src *= alpha
src += gray
return src |
def __call__(self, src):
'Augmenter body.\n Using approximate linear transfomation described in:\n https://beesbuzz.biz/code/hsv_color_transforms.php\n '
alpha = random.uniform((- self.hue), self.hue)
u = np.cos((alpha * np.pi))
w = np.sin((alpha * np.pi))
bt = np.array([[1.0, 0... | -8,270,626,956,080,227,000 | Augmenter body.
Using approximate linear transfomation described in:
https://beesbuzz.biz/code/hsv_color_transforms.php | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
'Augmenter body.\n Using approximate linear transfomation described in:\n https://beesbuzz.biz/code/hsv_color_transforms.php\n '
alpha = random.uniform((- self.hue), self.hue)
u = np.cos((alpha * np.pi))
w = np.sin((alpha * np.pi))
bt = np.array([[1.0, 0... |
def __call__(self, src):
'Augmenter body'
alpha = np.random.normal(0, self.alphastd, size=(3,))
rgb = np.dot((self.eigvec * alpha), self.eigval)
src += nd.array(rgb)
return src | -2,768,567,695,815,835,600 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
alpha = np.random.normal(0, self.alphastd, size=(3,))
rgb = np.dot((self.eigvec * alpha), self.eigval)
src += nd.array(rgb)
return src |
def __call__(self, src):
'Augmenter body'
return color_normalize(src, self.mean, self.std) | 8,233,329,245,456,983,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
return color_normalize(src, self.mean, self.std) |
def __call__(self, src):
'Augmenter body'
if (random.random() < self.p):
src = nd.dot(src, self.mat)
return src | -7,419,213,170,269,568,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
if (random.random() < self.p):
src = nd.dot(src, self.mat)
return src |
def __call__(self, src):
'Augmenter body'
if (random.random() < self.p):
src = nd.flip(src, axis=1)
return src | -8,938,693,278,912,147,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
if (random.random() < self.p):
src = nd.flip(src, axis=1)
return src |
def __call__(self, src):
'Augmenter body'
src = src.astype(self.typ)
return src | -4,804,264,324,144,117,000 | Augmenter body | python/mxnet/image/image.py | __call__ | Vikas89/private-mxnet | python | def __call__(self, src):
src = src.astype(self.typ)
return src |
def reset(self):
'Resets the iterator to the beginning of the data.'
if ((self.seq is not None) and self.shuffle):
random.shuffle(self.seq)
if ((self.last_batch_handle != 'roll_over') or (self._cache_data is None)):
if (self.imgrec is not None):
self.imgrec.reset()
self.c... | -7,756,397,515,869,751,000 | Resets the iterator to the beginning of the data. | python/mxnet/image/image.py | reset | Vikas89/private-mxnet | python | def reset(self):
if ((self.seq is not None) and self.shuffle):
random.shuffle(self.seq)
if ((self.last_batch_handle != 'roll_over') or (self._cache_data is None)):
if (self.imgrec is not None):
self.imgrec.reset()
self.cur = 0
if (self._allow_read is False):
... |
def hard_reset(self):
'Resets the iterator and ignore roll over data'
if ((self.seq is not None) and self.shuffle):
random.shuffle(self.seq)
if (self.imgrec is not None):
self.imgrec.reset()
self.cur = 0
self._allow_read = True
self._cache_data = None
self._cache_label = None... | 1,775,562,946,994,153,500 | Resets the iterator and ignore roll over data | python/mxnet/image/image.py | hard_reset | Vikas89/private-mxnet | python | def hard_reset(self):
if ((self.seq is not None) and self.shuffle):
random.shuffle(self.seq)
if (self.imgrec is not None):
self.imgrec.reset()
self.cur = 0
self._allow_read = True
self._cache_data = None
self._cache_label = None
self._cache_idx = None |
def next_sample(self):
'Helper function for reading in next sample.'
if (self._allow_read is False):
raise StopIteration
if (self.seq is not None):
if (self.cur < self.num_image):
idx = self.seq[self.cur]
else:
if (self.last_batch_handle != 'discard'):
... | -5,655,445,514,747,744,000 | Helper function for reading in next sample. | python/mxnet/image/image.py | next_sample | Vikas89/private-mxnet | python | def next_sample(self):
if (self._allow_read is False):
raise StopIteration
if (self.seq is not None):
if (self.cur < self.num_image):
idx = self.seq[self.cur]
else:
if (self.last_batch_handle != 'discard'):
self.cur = 0
raise StopI... |
def _batchify(self, batch_data, batch_label, start=0):
'Helper function for batchifying data'
i = start
batch_size = self.batch_size
try:
while (i < batch_size):
(label, s) = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_imag... | 3,709,117,745,405,608,400 | Helper function for batchifying data | python/mxnet/image/image.py | _batchify | Vikas89/private-mxnet | python | def _batchify(self, batch_data, batch_label, start=0):
i = start
batch_size = self.batch_size
try:
while (i < batch_size):
(label, s) = self.next_sample()
data = self.imdecode(s)
try:
self.check_valid_image(data)
except RuntimeErro... |
def next(self):
'Returns the next batch of data.'
batch_size = self.batch_size
(c, h, w) = self.data_shape
if (self._cache_data is not None):
assert (self._cache_label is not None), "_cache_label didn't have values"
assert (self._cache_idx is not None), "_cache_idx didn't have values"
... | 25,468,607,389,459,910 | Returns the next batch of data. | python/mxnet/image/image.py | next | Vikas89/private-mxnet | python | def next(self):
batch_size = self.batch_size
(c, h, w) = self.data_shape
if (self._cache_data is not None):
assert (self._cache_label is not None), "_cache_label didn't have values"
assert (self._cache_idx is not None), "_cache_idx didn't have values"
batch_data = self._cache_da... |
def check_data_shape(self, data_shape):
'Checks if the input data shape is valid'
if (not (len(data_shape) == 3)):
raise ValueError('data_shape should have length 3, with dimensions CxHxW')
if (not (data_shape[0] == 3)):
raise ValueError('This iterator expects inputs to have 3 channels.') | 8,563,661,476,355,520,000 | Checks if the input data shape is valid | python/mxnet/image/image.py | check_data_shape | Vikas89/private-mxnet | python | def check_data_shape(self, data_shape):
if (not (len(data_shape) == 3)):
raise ValueError('data_shape should have length 3, with dimensions CxHxW')
if (not (data_shape[0] == 3)):
raise ValueError('This iterator expects inputs to have 3 channels.') |
def check_valid_image(self, data):
'Checks if the input data is valid'
if (len(data[0].shape) == 0):
raise RuntimeError('Data shape is wrong') | 5,022,741,528,319,668,000 | Checks if the input data is valid | python/mxnet/image/image.py | check_valid_image | Vikas89/private-mxnet | python | def check_valid_image(self, data):
if (len(data[0].shape) == 0):
raise RuntimeError('Data shape is wrong') |
def imdecode(self, s):
'Decodes a string or byte string to an NDArray.\n See mx.img.imdecode for more details.'
def locate():
'Locate the image file/index if decode fails.'
if (self.seq is not None):
idx = self.seq[((self.cur % self.num_image) - 1)]
else:
... | 7,497,748,351,332,963,000 | Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details. | python/mxnet/image/image.py | imdecode | Vikas89/private-mxnet | python | def imdecode(self, s):
'Decodes a string or byte string to an NDArray.\n See mx.img.imdecode for more details.'
def locate():
'Locate the image file/index if decode fails.'
if (self.seq is not None):
idx = self.seq[((self.cur % self.num_image) - 1)]
else:
... |
def read_image(self, fname):
"Reads an input image `fname` and returns the decoded raw bytes.\n Example usage:\n ----------\n >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.\n "
with open(os.path.join(self.path_root, fname), 'rb') as fin:
img = fin.read()
... | -6,715,990,902,793,112,000 | Reads an input image `fname` and returns the decoded raw bytes.
Example usage:
----------
>>> dataIter.read_image('Face.jpg') # returns decoded raw bytes. | python/mxnet/image/image.py | read_image | Vikas89/private-mxnet | python | def read_image(self, fname):
"Reads an input image `fname` and returns the decoded raw bytes.\n Example usage:\n ----------\n >>> dataIter.read_image('Face.jpg') # returns decoded raw bytes.\n "
with open(os.path.join(self.path_root, fname), 'rb') as fin:
img = fin.read()
... |
def augmentation_transform(self, data):
'Transforms input data with specified augmentation.'
for aug in self.auglist:
data = aug(data)
return data | 8,575,387,383,950,764,000 | Transforms input data with specified augmentation. | python/mxnet/image/image.py | augmentation_transform | Vikas89/private-mxnet | python | def augmentation_transform(self, data):
for aug in self.auglist:
data = aug(data)
return data |
def postprocess_data(self, datum):
'Final postprocessing step before image is loaded into the batch.'
return nd.transpose(datum, axes=(2, 0, 1)) | 2,554,523,868,221,964,300 | Final postprocessing step before image is loaded into the batch. | python/mxnet/image/image.py | postprocess_data | Vikas89/private-mxnet | python | def postprocess_data(self, datum):
return nd.transpose(datum, axes=(2, 0, 1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.