repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
panosl/django-currencies
currencies/management/commands/currencies.py
Command.get_handler
def get_handler(self, options): """Return the specified handler""" # Import the CurrencyHandler and get an instance handler_module = import_module(sources[options[self._source_param]], self._package_name) return handler_module.CurrencyHandler(self.log)
python
def get_handler(self, options): """Return the specified handler""" # Import the CurrencyHandler and get an instance handler_module = import_module(sources[options[self._source_param]], self._package_name) return handler_module.CurrencyHandler(self.log)
[ "def", "get_handler", "(", "self", ",", "options", ")", ":", "# Import the CurrencyHandler and get an instance", "handler_module", "=", "import_module", "(", "sources", "[", "options", "[", "self", ".", "_source_param", "]", "]", ",", "self", ".", "_package_name", ...
Return the specified handler
[ "Return", "the", "specified", "handler" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/currencies.py#L95-L99
train
31,500
panosl/django-currencies
currencies/management/commands/_openexchangerates.py
CurrencyHandler.check_rates
def check_rates(self, rates, base): """Local helper function for validating rates response""" if "rates" not in rates: raise RuntimeError("%s: 'rates' not found in results" % self.name) if "base" not in rates or rates["base"] != base or base not in rates["rates"]: self.log(logging.WARNING, "%s: 'base' not found in results", self.name) self.rates = rates
python
def check_rates(self, rates, base): """Local helper function for validating rates response""" if "rates" not in rates: raise RuntimeError("%s: 'rates' not found in results" % self.name) if "base" not in rates or rates["base"] != base or base not in rates["rates"]: self.log(logging.WARNING, "%s: 'base' not found in results", self.name) self.rates = rates
[ "def", "check_rates", "(", "self", ",", "rates", ",", "base", ")", ":", "if", "\"rates\"", "not", "in", "rates", ":", "raise", "RuntimeError", "(", "\"%s: 'rates' not found in results\"", "%", "self", ".", "name", ")", "if", "\"base\"", "not", "in", "rates",...
Local helper function for validating rates response
[ "Local", "helper", "function", "for", "validating", "rates", "response" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates.py#L48-L55
train
31,501
panosl/django-currencies
currencies/management/commands/_openexchangerates.py
CurrencyHandler.get_ratefactor
def get_ratefactor(self, base, code): """Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError""" self.get_latestcurrencyrates(base) try: ratefactor = self.rates["rates"][code] except KeyError: raise RuntimeError("%s: %s not found" % (self.name, code)) if base == self.base: return ratefactor else: return self.ratechangebase(ratefactor, self.base, base)
python
def get_ratefactor(self, base, code): """Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError""" self.get_latestcurrencyrates(base) try: ratefactor = self.rates["rates"][code] except KeyError: raise RuntimeError("%s: %s not found" % (self.name, code)) if base == self.base: return ratefactor else: return self.ratechangebase(ratefactor, self.base, base)
[ "def", "get_ratefactor", "(", "self", ",", "base", ",", "code", ")", ":", "self", ".", "get_latestcurrencyrates", "(", "base", ")", "try", ":", "ratefactor", "=", "self", ".", "rates", "[", "\"rates\"", "]", "[", "code", "]", "except", "KeyError", ":", ...
Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError
[ "Return", "the", "Decimal", "currency", "exchange", "rate", "factor", "of", "code", "compared", "to", "1", "base", "unit", "or", "RuntimeError" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates.py#L88-L99
train
31,502
panosl/django-currencies
currencies/management/commands/_currencyhandler.py
BaseHandler.get_currencysymbol
def get_currencysymbol(self, code): """Retrieve the currency symbol from the local file""" if not self._symbols: symbolpath = os.path.join(self._dir, 'currencies.json') with open(symbolpath, encoding='utf8') as df: self._symbols = json.load(df) return self._symbols.get(code)
python
def get_currencysymbol(self, code): """Retrieve the currency symbol from the local file""" if not self._symbols: symbolpath = os.path.join(self._dir, 'currencies.json') with open(symbolpath, encoding='utf8') as df: self._symbols = json.load(df) return self._symbols.get(code)
[ "def", "get_currencysymbol", "(", "self", ",", "code", ")", ":", "if", "not", "self", ".", "_symbols", ":", "symbolpath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_dir", ",", "'currencies.json'", ")", "with", "open", "(", "symbolpath", "...
Retrieve the currency symbol from the local file
[ "Retrieve", "the", "currency", "symbol", "from", "the", "local", "file" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyhandler.py#L40-L46
train
31,503
panosl/django-currencies
currencies/management/commands/_currencyhandler.py
BaseHandler.ratechangebase
def ratechangebase(self, ratefactor, current_base, new_base): """ Local helper function for changing currency base, returns new rate in new base Defaults to ROUND_HALF_EVEN """ if self._multiplier is None: self.log(logging.WARNING, "CurrencyHandler: changing base ourselves") # Check the current base is 1 if Decimal(1) != self.get_ratefactor(current_base, current_base): raise RuntimeError("CurrencyHandler: current baserate: %s not 1" % current_base) self._multiplier = Decimal(1) / self.get_ratefactor(current_base, new_base) return (ratefactor * self._multiplier).quantize(Decimal(".0001"))
python
def ratechangebase(self, ratefactor, current_base, new_base): """ Local helper function for changing currency base, returns new rate in new base Defaults to ROUND_HALF_EVEN """ if self._multiplier is None: self.log(logging.WARNING, "CurrencyHandler: changing base ourselves") # Check the current base is 1 if Decimal(1) != self.get_ratefactor(current_base, current_base): raise RuntimeError("CurrencyHandler: current baserate: %s not 1" % current_base) self._multiplier = Decimal(1) / self.get_ratefactor(current_base, new_base) return (ratefactor * self._multiplier).quantize(Decimal(".0001"))
[ "def", "ratechangebase", "(", "self", ",", "ratefactor", ",", "current_base", ",", "new_base", ")", ":", "if", "self", ".", "_multiplier", "is", "None", ":", "self", ".", "log", "(", "logging", ".", "WARNING", ",", "\"CurrencyHandler: changing base ourselves\"",...
Local helper function for changing currency base, returns new rate in new base Defaults to ROUND_HALF_EVEN
[ "Local", "helper", "function", "for", "changing", "currency", "base", "returns", "new", "rate", "in", "new", "base", "Defaults", "to", "ROUND_HALF_EVEN" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyhandler.py#L49-L60
train
31,504
jmoiron/johnny-cache
johnny/cache.py
disallowed_table
def disallowed_table(*tables): """Returns True if a set of tables is in the blacklist or, if a whitelist is set, any of the tables is not in the whitelist. False otherwise.""" # XXX: When using a black or white list, this has to be done EVERY query; # It'd be nice to make this as fast as possible. In general, queries # should have relatively few tables involved, and I don't imagine that # blacklists would grow very vast. The fastest i've been able to come # up with is to pre-create a blacklist set and use intersect. return not bool(settings.WHITELIST.issuperset(tables)) if settings.WHITELIST\ else bool(settings.BLACKLIST.intersection(tables))
python
def disallowed_table(*tables): """Returns True if a set of tables is in the blacklist or, if a whitelist is set, any of the tables is not in the whitelist. False otherwise.""" # XXX: When using a black or white list, this has to be done EVERY query; # It'd be nice to make this as fast as possible. In general, queries # should have relatively few tables involved, and I don't imagine that # blacklists would grow very vast. The fastest i've been able to come # up with is to pre-create a blacklist set and use intersect. return not bool(settings.WHITELIST.issuperset(tables)) if settings.WHITELIST\ else bool(settings.BLACKLIST.intersection(tables))
[ "def", "disallowed_table", "(", "*", "tables", ")", ":", "# XXX: When using a black or white list, this has to be done EVERY query;", "# It'd be nice to make this as fast as possible. In general, queries", "# should have relatively few tables involved, and I don't imagine that", "# blacklists w...
Returns True if a set of tables is in the blacklist or, if a whitelist is set, any of the tables is not in the whitelist. False otherwise.
[ "Returns", "True", "if", "a", "set", "of", "tables", "is", "in", "the", "blacklist", "or", "if", "a", "whitelist", "is", "set", "any", "of", "the", "tables", "is", "not", "in", "the", "whitelist", ".", "False", "otherwise", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L25-L34
train
31,505
jmoiron/johnny-cache
johnny/cache.py
invalidate
def invalidate(*tables, **kwargs): """Invalidate the current generation for one or more tables. The arguments can be either strings representing database table names or models. Pass in kwarg ``using`` to set the database.""" backend = get_backend() db = kwargs.get('using', 'default') if backend._patched: for t in map(resolve_table, tables): backend.keyhandler.invalidate_table(t, db)
python
def invalidate(*tables, **kwargs): """Invalidate the current generation for one or more tables. The arguments can be either strings representing database table names or models. Pass in kwarg ``using`` to set the database.""" backend = get_backend() db = kwargs.get('using', 'default') if backend._patched: for t in map(resolve_table, tables): backend.keyhandler.invalidate_table(t, db)
[ "def", "invalidate", "(", "*", "tables", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "get_backend", "(", ")", "db", "=", "kwargs", ".", "get", "(", "'using'", ",", "'default'", ")", "if", "backend", ".", "_patched", ":", "for", "t", "in", "m...
Invalidate the current generation for one or more tables. The arguments can be either strings representing database table names or models. Pass in kwarg ``using`` to set the database.
[ "Invalidate", "the", "current", "generation", "for", "one", "or", "more", "tables", ".", "The", "arguments", "can", "be", "either", "strings", "representing", "database", "table", "names", "or", "models", ".", "Pass", "in", "kwarg", "using", "to", "set", "th...
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L67-L76
train
31,506
jmoiron/johnny-cache
johnny/cache.py
KeyGen.gen_key
def gen_key(self, *values): """Generate a key from one or more values.""" key = md5() KeyGen._recursive_convert(values, key) return key.hexdigest()
python
def gen_key(self, *values): """Generate a key from one or more values.""" key = md5() KeyGen._recursive_convert(values, key) return key.hexdigest()
[ "def", "gen_key", "(", "self", ",", "*", "values", ")", ":", "key", "=", "md5", "(", ")", "KeyGen", ".", "_recursive_convert", "(", "values", ",", "key", ")", "return", "key", ".", "hexdigest", "(", ")" ]
Generate a key from one or more values.
[ "Generate", "a", "key", "from", "one", "or", "more", "values", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L199-L203
train
31,507
jmoiron/johnny-cache
johnny/cache.py
KeyHandler.get_generation
def get_generation(self, *tables, **kwargs): """Get the generation key for any number of tables.""" db = kwargs.get('db', 'default') if len(tables) > 1: return self.get_multi_generation(tables, db) return self.get_single_generation(tables[0], db)
python
def get_generation(self, *tables, **kwargs): """Get the generation key for any number of tables.""" db = kwargs.get('db', 'default') if len(tables) > 1: return self.get_multi_generation(tables, db) return self.get_single_generation(tables[0], db)
[ "def", "get_generation", "(", "self", ",", "*", "tables", ",", "*", "*", "kwargs", ")", ":", "db", "=", "kwargs", ".", "get", "(", "'db'", ",", "'default'", ")", "if", "len", "(", "tables", ")", ">", "1", ":", "return", "self", ".", "get_multi_gene...
Get the generation key for any number of tables.
[ "Get", "the", "generation", "key", "for", "any", "number", "of", "tables", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L215-L220
train
31,508
jmoiron/johnny-cache
johnny/cache.py
KeyHandler.get_single_generation
def get_single_generation(self, table, db='default'): """Creates a random generation value for a single table name""" key = self.keygen.gen_table_key(table, db) val = self.cache_backend.get(key, None, db) #if local.get('in_test', None): print force_bytes(val).ljust(32), key if val is None: val = self.keygen.random_generator() self.cache_backend.set(key, val, settings.MIDDLEWARE_SECONDS, db) return val
python
def get_single_generation(self, table, db='default'): """Creates a random generation value for a single table name""" key = self.keygen.gen_table_key(table, db) val = self.cache_backend.get(key, None, db) #if local.get('in_test', None): print force_bytes(val).ljust(32), key if val is None: val = self.keygen.random_generator() self.cache_backend.set(key, val, settings.MIDDLEWARE_SECONDS, db) return val
[ "def", "get_single_generation", "(", "self", ",", "table", ",", "db", "=", "'default'", ")", ":", "key", "=", "self", ".", "keygen", ".", "gen_table_key", "(", "table", ",", "db", ")", "val", "=", "self", ".", "cache_backend", ".", "get", "(", "key", ...
Creates a random generation value for a single table name
[ "Creates", "a", "random", "generation", "value", "for", "a", "single", "table", "name" ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L222-L230
train
31,509
jmoiron/johnny-cache
johnny/cache.py
KeyHandler.get_multi_generation
def get_multi_generation(self, tables, db='default'): """Takes a list of table names and returns an aggregate value for the generation""" generations = [] for table in tables: generations.append(self.get_single_generation(table, db)) key = self.keygen.gen_multi_key(generations, db) val = self.cache_backend.get(key, None, db) #if local.get('in_test', None): print force_bytes(val).ljust(32), key if val is None: val = self.keygen.random_generator() self.cache_backend.set(key, val, settings.MIDDLEWARE_SECONDS, db) return val
python
def get_multi_generation(self, tables, db='default'): """Takes a list of table names and returns an aggregate value for the generation""" generations = [] for table in tables: generations.append(self.get_single_generation(table, db)) key = self.keygen.gen_multi_key(generations, db) val = self.cache_backend.get(key, None, db) #if local.get('in_test', None): print force_bytes(val).ljust(32), key if val is None: val = self.keygen.random_generator() self.cache_backend.set(key, val, settings.MIDDLEWARE_SECONDS, db) return val
[ "def", "get_multi_generation", "(", "self", ",", "tables", ",", "db", "=", "'default'", ")", ":", "generations", "=", "[", "]", "for", "table", "in", "tables", ":", "generations", ".", "append", "(", "self", ".", "get_single_generation", "(", "table", ",",...
Takes a list of table names and returns an aggregate value for the generation
[ "Takes", "a", "list", "of", "table", "names", "and", "returns", "an", "aggregate", "value", "for", "the", "generation" ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L232-L244
train
31,510
jmoiron/johnny-cache
johnny/cache.py
KeyHandler.sql_key
def sql_key(self, generation, sql, params, order, result_type, using='default'): """ Return the specific cache key for the sql query described by the pieces of the query and the generation key. """ # these keys will always look pretty opaque suffix = self.keygen.gen_key(sql, params, order, result_type) using = settings.DB_CACHE_KEYS[using] return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)
python
def sql_key(self, generation, sql, params, order, result_type, using='default'): """ Return the specific cache key for the sql query described by the pieces of the query and the generation key. """ # these keys will always look pretty opaque suffix = self.keygen.gen_key(sql, params, order, result_type) using = settings.DB_CACHE_KEYS[using] return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)
[ "def", "sql_key", "(", "self", ",", "generation", ",", "sql", ",", "params", ",", "order", ",", "result_type", ",", "using", "=", "'default'", ")", ":", "# these keys will always look pretty opaque", "suffix", "=", "self", ".", "keygen", ".", "gen_key", "(", ...
Return the specific cache key for the sql query described by the pieces of the query and the generation key.
[ "Return", "the", "specific", "cache", "key", "for", "the", "sql", "query", "described", "by", "the", "pieces", "of", "the", "query", "and", "the", "generation", "key", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L255-L264
train
31,511
jmoiron/johnny-cache
johnny/cache.py
QueryCacheBackend.unpatch
def unpatch(self): """un-applies this patch.""" if not self._patched: return for func in self._read_compilers + self._write_compilers: func.execute_sql = self._original[func] self.cache_backend.unpatch() self._patched = False
python
def unpatch(self): """un-applies this patch.""" if not self._patched: return for func in self._read_compilers + self._write_compilers: func.execute_sql = self._original[func] self.cache_backend.unpatch() self._patched = False
[ "def", "unpatch", "(", "self", ")", ":", "if", "not", "self", ".", "_patched", ":", "return", "for", "func", "in", "self", ".", "_read_compilers", "+", "self", ".", "_write_compilers", ":", "func", ".", "execute_sql", "=", "self", ".", "_original", "[", ...
un-applies this patch.
[ "un", "-", "applies", "this", "patch", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/cache.py#L431-L438
train
31,512
panosl/django-currencies
currencies/templatetags/currency.py
memoize_nullary
def memoize_nullary(f): """ Memoizes a function that takes no arguments. The memoization lasts only as long as we hold a reference to the returned function. """ def func(): if not hasattr(func, 'retval'): func.retval = f() return func.retval return func
python
def memoize_nullary(f): """ Memoizes a function that takes no arguments. The memoization lasts only as long as we hold a reference to the returned function. """ def func(): if not hasattr(func, 'retval'): func.retval = f() return func.retval return func
[ "def", "memoize_nullary", "(", "f", ")", ":", "def", "func", "(", ")", ":", "if", "not", "hasattr", "(", "func", ",", "'retval'", ")", ":", "func", ".", "retval", "=", "f", "(", ")", "return", "func", ".", "retval", "return", "func" ]
Memoizes a function that takes no arguments. The memoization lasts only as long as we hold a reference to the returned function.
[ "Memoizes", "a", "function", "that", "takes", "no", "arguments", ".", "The", "memoization", "lasts", "only", "as", "long", "as", "we", "hold", "a", "reference", "to", "the", "returned", "function", "." ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/templatetags/currency.py#L47-L56
train
31,513
panosl/django-currencies
currencies/templatetags/currency.py
currency_context
def currency_context(context): """ Use instead of context processor Context variables are only valid within the block scope """ request = context['request'] currency_code = memoize_nullary(lambda: get_currency_code(request)) context['CURRENCIES'] = Currency.active.all() # querysets are already lazy context['CURRENCY_CODE'] = currency_code # lazy context['CURRENCY'] = memoize_nullary(lambda: get_currency(currency_code)) # lazy return ''
python
def currency_context(context): """ Use instead of context processor Context variables are only valid within the block scope """ request = context['request'] currency_code = memoize_nullary(lambda: get_currency_code(request)) context['CURRENCIES'] = Currency.active.all() # querysets are already lazy context['CURRENCY_CODE'] = currency_code # lazy context['CURRENCY'] = memoize_nullary(lambda: get_currency(currency_code)) # lazy return ''
[ "def", "currency_context", "(", "context", ")", ":", "request", "=", "context", "[", "'request'", "]", "currency_code", "=", "memoize_nullary", "(", "lambda", ":", "get_currency_code", "(", "request", ")", ")", "context", "[", "'CURRENCIES'", "]", "=", "Curren...
Use instead of context processor Context variables are only valid within the block scope
[ "Use", "instead", "of", "context", "processor", "Context", "variables", "are", "only", "valid", "within", "the", "block", "scope" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/templatetags/currency.py#L71-L83
train
31,514
panosl/django-currencies
currencies/management/commands/_openexchangerates_client.py
OpenExchangeRatesClient.currencies
def currencies(self): """Fetches current currency data of the service :Example Data: { AED: "United Arab Emirates Dirham", AFN: "Afghan Afghani", ALL: "Albanian Lek", AMD: "Armenian Dram", ANG: "Netherlands Antillean Guilder", AOA: "Angolan Kwanza", ARS: "Argentine Peso", AUD: "Australian Dollar", AWG: "Aruban Florin", AZN: "Azerbaijani Manat" ... } """ try: resp = self.client.get(self.ENDPOINT_CURRENCIES) except requests.exceptions.RequestException as e: raise OpenExchangeRatesClientException(e) return resp.json()
python
def currencies(self): """Fetches current currency data of the service :Example Data: { AED: "United Arab Emirates Dirham", AFN: "Afghan Afghani", ALL: "Albanian Lek", AMD: "Armenian Dram", ANG: "Netherlands Antillean Guilder", AOA: "Angolan Kwanza", ARS: "Argentine Peso", AUD: "Australian Dollar", AWG: "Aruban Florin", AZN: "Azerbaijani Manat" ... } """ try: resp = self.client.get(self.ENDPOINT_CURRENCIES) except requests.exceptions.RequestException as e: raise OpenExchangeRatesClientException(e) return resp.json()
[ "def", "currencies", "(", "self", ")", ":", "try", ":", "resp", "=", "self", ".", "client", ".", "get", "(", "self", ".", "ENDPOINT_CURRENCIES", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "OpenExchangeRa...
Fetches current currency data of the service :Example Data: { AED: "United Arab Emirates Dirham", AFN: "Afghan Afghani", ALL: "Albanian Lek", AMD: "Armenian Dram", ANG: "Netherlands Antillean Guilder", AOA: "Angolan Kwanza", ARS: "Argentine Peso", AUD: "Australian Dollar", AWG: "Aruban Florin", AZN: "Azerbaijani Manat" ... }
[ "Fetches", "current", "currency", "data", "of", "the", "service" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates_client.py#L57-L81
train
31,515
panosl/django-currencies
currencies/management/commands/_openexchangerates_client.py
OpenExchangeRatesClient.historical
def historical(self, date, base='USD'): """Fetches historical exchange rate data from service :Example Data: { disclaimer: "<Disclaimer data>", license: "<License data>", timestamp: 1358150409, base: "USD", rates: { AED: 3.666311, AFN: 51.2281, ALL: 104.748751, AMD: 406.919999, ANG: 1.7831, ... } } """ try: resp = self.client.get(self.ENDPOINT_HISTORICAL % date.strftime("%Y-%m-%d"), params={'base': base}) resp.raise_for_status() except requests.exceptions.RequestException as e: raise OpenExchangeRatesClientException(e) return resp.json(parse_int=decimal.Decimal, parse_float=decimal.Decimal)
python
def historical(self, date, base='USD'): """Fetches historical exchange rate data from service :Example Data: { disclaimer: "<Disclaimer data>", license: "<License data>", timestamp: 1358150409, base: "USD", rates: { AED: 3.666311, AFN: 51.2281, ALL: 104.748751, AMD: 406.919999, ANG: 1.7831, ... } } """ try: resp = self.client.get(self.ENDPOINT_HISTORICAL % date.strftime("%Y-%m-%d"), params={'base': base}) resp.raise_for_status() except requests.exceptions.RequestException as e: raise OpenExchangeRatesClientException(e) return resp.json(parse_int=decimal.Decimal, parse_float=decimal.Decimal)
[ "def", "historical", "(", "self", ",", "date", ",", "base", "=", "'USD'", ")", ":", "try", ":", "resp", "=", "self", ".", "client", ".", "get", "(", "self", ".", "ENDPOINT_HISTORICAL", "%", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", ",", "par...
Fetches historical exchange rate data from service :Example Data: { disclaimer: "<Disclaimer data>", license: "<License data>", timestamp: 1358150409, base: "USD", rates: { AED: 3.666311, AFN: 51.2281, ALL: 104.748751, AMD: 406.919999, ANG: 1.7831, ... } }
[ "Fetches", "historical", "exchange", "rate", "data", "from", "service" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_openexchangerates_client.py#L83-L110
train
31,516
panosl/django-currencies
currencies/utils.py
calculate
def calculate(price, to_code, **kwargs): """Converts a price in the default currency to another currency""" qs = kwargs.get('qs', get_active_currencies_qs()) kwargs['qs'] = qs default_code = qs.default().code return convert(price, default_code, to_code, **kwargs)
python
def calculate(price, to_code, **kwargs): """Converts a price in the default currency to another currency""" qs = kwargs.get('qs', get_active_currencies_qs()) kwargs['qs'] = qs default_code = qs.default().code return convert(price, default_code, to_code, **kwargs)
[ "def", "calculate", "(", "price", ",", "to_code", ",", "*", "*", "kwargs", ")", ":", "qs", "=", "kwargs", ".", "get", "(", "'qs'", ",", "get_active_currencies_qs", "(", ")", ")", "kwargs", "[", "'qs'", "]", "=", "qs", "default_code", "=", "qs", ".", ...
Converts a price in the default currency to another currency
[ "Converts", "a", "price", "in", "the", "default", "currency", "to", "another", "currency" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L11-L16
train
31,517
panosl/django-currencies
currencies/utils.py
convert
def convert(amount, from_code, to_code, decimals=2, qs=None): """Converts from any currency to any currency""" if from_code == to_code: return amount if qs is None: qs = get_active_currencies_qs() from_, to = qs.get(code=from_code), qs.get(code=to_code) amount = D(amount) * (to.factor / from_.factor) return price_rounding(amount, decimals=decimals)
python
def convert(amount, from_code, to_code, decimals=2, qs=None): """Converts from any currency to any currency""" if from_code == to_code: return amount if qs is None: qs = get_active_currencies_qs() from_, to = qs.get(code=from_code), qs.get(code=to_code) amount = D(amount) * (to.factor / from_.factor) return price_rounding(amount, decimals=decimals)
[ "def", "convert", "(", "amount", ",", "from_code", ",", "to_code", ",", "decimals", "=", "2", ",", "qs", "=", "None", ")", ":", "if", "from_code", "==", "to_code", ":", "return", "amount", "if", "qs", "is", "None", ":", "qs", "=", "get_active_currencie...
Converts from any currency to any currency
[ "Converts", "from", "any", "currency", "to", "any", "currency" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L19-L30
train
31,518
panosl/django-currencies
currencies/utils.py
price_rounding
def price_rounding(price, decimals=2): """Takes a decimal price and rounds to a number of decimal places""" try: exponent = D('.' + decimals * '0') except InvalidOperation: # Currencies with no decimal places, ex. JPY, HUF exponent = D() return price.quantize(exponent, rounding=ROUND_UP)
python
def price_rounding(price, decimals=2): """Takes a decimal price and rounds to a number of decimal places""" try: exponent = D('.' + decimals * '0') except InvalidOperation: # Currencies with no decimal places, ex. JPY, HUF exponent = D() return price.quantize(exponent, rounding=ROUND_UP)
[ "def", "price_rounding", "(", "price", ",", "decimals", "=", "2", ")", ":", "try", ":", "exponent", "=", "D", "(", "'.'", "+", "decimals", "*", "'0'", ")", "except", "InvalidOperation", ":", "# Currencies with no decimal places, ex. JPY, HUF", "exponent", "=", ...
Takes a decimal price and rounds to a number of decimal places
[ "Takes", "a", "decimal", "price", "and", "rounds", "to", "a", "number", "of", "decimal", "places" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/utils.py#L48-L55
train
31,519
panosl/django-currencies
currencies/management/commands/_currencyiso.py
CurrencyHandler.get_currencies
def get_currencies(self): """Downloads xml currency data or if not available tries to use cached file copy""" try: resp = get(self.endpoint) resp.raise_for_status() except exceptions.RequestException as e: self.log(logging.ERROR, "%s: Problem whilst contacting endpoint:\n%s", self.name, e) else: with open(self._cached_currency_file, 'wb') as fd: fd.write(resp.content) try: root = ET.parse(self._cached_currency_file).getroot() except FileNotFoundError as e: raise RuntimeError("%s: XML not found at endpoint or as cached file:\n%s" % (self.name, e)) return root
python
def get_currencies(self): """Downloads xml currency data or if not available tries to use cached file copy""" try: resp = get(self.endpoint) resp.raise_for_status() except exceptions.RequestException as e: self.log(logging.ERROR, "%s: Problem whilst contacting endpoint:\n%s", self.name, e) else: with open(self._cached_currency_file, 'wb') as fd: fd.write(resp.content) try: root = ET.parse(self._cached_currency_file).getroot() except FileNotFoundError as e: raise RuntimeError("%s: XML not found at endpoint or as cached file:\n%s" % (self.name, e)) return root
[ "def", "get_currencies", "(", "self", ")", ":", "try", ":", "resp", "=", "get", "(", "self", ".", "endpoint", ")", "resp", ".", "raise_for_status", "(", ")", "except", "exceptions", ".", "RequestException", "as", "e", ":", "self", ".", "log", "(", "log...
Downloads xml currency data or if not available tries to use cached file copy
[ "Downloads", "xml", "currency", "data", "or", "if", "not", "available", "tries", "to", "use", "cached", "file", "copy" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L38-L54
train
31,520
panosl/django-currencies
currencies/management/commands/_currencyiso.py
CurrencyHandler._check_doc
def _check_doc(self, root): """Validates the xml tree and returns the published date""" if (root.tag != 'ISO_4217' or root[0].tag != 'CcyTbl' or root[0][0].tag != 'CcyNtry' or not root.attrib['Pblshd'] or # Actual length in Oct 2016: 279 len(root[0]) < 270): raise TypeError("%s: XML %s appears to be invalid" % (self.name, self._cached_currency_file)) return datetime.strptime(root.attrib['Pblshd'], '%Y-%m-%d').date()
python
def _check_doc(self, root): """Validates the xml tree and returns the published date""" if (root.tag != 'ISO_4217' or root[0].tag != 'CcyTbl' or root[0][0].tag != 'CcyNtry' or not root.attrib['Pblshd'] or # Actual length in Oct 2016: 279 len(root[0]) < 270): raise TypeError("%s: XML %s appears to be invalid" % (self.name, self._cached_currency_file)) return datetime.strptime(root.attrib['Pblshd'], '%Y-%m-%d').date()
[ "def", "_check_doc", "(", "self", ",", "root", ")", ":", "if", "(", "root", ".", "tag", "!=", "'ISO_4217'", "or", "root", "[", "0", "]", ".", "tag", "!=", "'CcyTbl'", "or", "root", "[", "0", "]", "[", "0", "]", ".", "tag", "!=", "'CcyNtry'", "o...
Validates the xml tree and returns the published date
[ "Validates", "the", "xml", "tree", "and", "returns", "the", "published", "date" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L56-L67
train
31,521
panosl/django-currencies
currencies/management/commands/_currencyiso.py
CurrencyHandler.get_allcurrencycodes
def get_allcurrencycodes(self): """Return an iterable of distinct 3 character ISO 4217 currency codes""" foundcodes = [] codeelements = self.currencies[0].iter('Ccy') for codeelement in codeelements: code = codeelement.text if code not in foundcodes: foundcodes += [code] yield code
python
def get_allcurrencycodes(self): """Return an iterable of distinct 3 character ISO 4217 currency codes""" foundcodes = [] codeelements = self.currencies[0].iter('Ccy') for codeelement in codeelements: code = codeelement.text if code not in foundcodes: foundcodes += [code] yield code
[ "def", "get_allcurrencycodes", "(", "self", ")", ":", "foundcodes", "=", "[", "]", "codeelements", "=", "self", ".", "currencies", "[", "0", "]", ".", "iter", "(", "'Ccy'", ")", "for", "codeelement", "in", "codeelements", ":", "code", "=", "codeelement", ...
Return an iterable of distinct 3 character ISO 4217 currency codes
[ "Return", "an", "iterable", "of", "distinct", "3", "character", "ISO", "4217", "currency", "codes" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_currencyiso.py#L69-L77
train
31,522
jmoiron/johnny-cache
johnny/utils.py
celery_enable_all
def celery_enable_all(): """Enable johnny-cache in all celery tasks, clearing the local-store after each task.""" from celery.signals import task_prerun, task_postrun, task_failure task_prerun.connect(prerun_handler) task_postrun.connect(postrun_handler) # Also have to cleanup on failure. task_failure.connect(postrun_handler)
python
def celery_enable_all(): """Enable johnny-cache in all celery tasks, clearing the local-store after each task.""" from celery.signals import task_prerun, task_postrun, task_failure task_prerun.connect(prerun_handler) task_postrun.connect(postrun_handler) # Also have to cleanup on failure. task_failure.connect(postrun_handler)
[ "def", "celery_enable_all", "(", ")", ":", "from", "celery", ".", "signals", "import", "task_prerun", ",", "task_postrun", ",", "task_failure", "task_prerun", ".", "connect", "(", "prerun_handler", ")", "task_postrun", ".", "connect", "(", "postrun_handler", ")", ...
Enable johnny-cache in all celery tasks, clearing the local-store after each task.
[ "Enable", "johnny", "-", "cache", "in", "all", "celery", "tasks", "clearing", "the", "local", "-", "store", "after", "each", "task", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/utils.py#L22-L29
train
31,523
jmoiron/johnny-cache
johnny/utils.py
celery_task_wrapper
def celery_task_wrapper(f): """ Provides a task wrapper for celery that sets up cache and ensures that the local store is cleared after completion """ from celery.utils import fun_takes_kwargs @wraps(f, assigned=available_attrs(f)) def newf(*args, **kwargs): backend = get_backend() was_patched = backend._patched get_backend().patch() # since this function takes all keyword arguments, # we will pass only the ones the function below accepts, # just as celery does supported_keys = fun_takes_kwargs(f, kwargs) new_kwargs = dict((key, val) for key, val in kwargs.items() if key in supported_keys) try: ret = f(*args, **new_kwargs) finally: local.clear() if not was_patched: get_backend().unpatch() return ret return newf
python
def celery_task_wrapper(f): """ Provides a task wrapper for celery that sets up cache and ensures that the local store is cleared after completion """ from celery.utils import fun_takes_kwargs @wraps(f, assigned=available_attrs(f)) def newf(*args, **kwargs): backend = get_backend() was_patched = backend._patched get_backend().patch() # since this function takes all keyword arguments, # we will pass only the ones the function below accepts, # just as celery does supported_keys = fun_takes_kwargs(f, kwargs) new_kwargs = dict((key, val) for key, val in kwargs.items() if key in supported_keys) try: ret = f(*args, **new_kwargs) finally: local.clear() if not was_patched: get_backend().unpatch() return ret return newf
[ "def", "celery_task_wrapper", "(", "f", ")", ":", "from", "celery", ".", "utils", "import", "fun_takes_kwargs", "@", "wraps", "(", "f", ",", "assigned", "=", "available_attrs", "(", "f", ")", ")", "def", "newf", "(", "*", "args", ",", "*", "*", "kwargs...
Provides a task wrapper for celery that sets up cache and ensures that the local store is cleared after completion
[ "Provides", "a", "task", "wrapper", "for", "celery", "that", "sets", "up", "cache", "and", "ensures", "that", "the", "local", "store", "is", "cleared", "after", "completion" ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/utils.py#L31-L57
train
31,524
jmoiron/johnny-cache
johnny/settings.py
_get_backend
def _get_backend(): """ Returns the actual django cache object johnny is configured to use. This relies on the settings only; the actual active cache can theoretically be changed at runtime. """ enabled = [n for n, c in sorted(CACHES.items()) if c.get('JOHNNY_CACHE', False)] if len(enabled) > 1: warn("Multiple caches configured for johnny-cache; using %s." % enabled[0]) if enabled: return get_cache(enabled[0]) if CACHE_BACKEND: backend = get_cache(CACHE_BACKEND) if backend not in CACHES: from django.core import signals # Some caches -- python-memcached in particular -- need to do a # cleanup at the end of a request cycle. If the cache provides a # close() method, wire it up here. if hasattr(backend, 'close'): signals.request_finished.connect(backend.close) return backend return cache
python
def _get_backend(): """ Returns the actual django cache object johnny is configured to use. This relies on the settings only; the actual active cache can theoretically be changed at runtime. """ enabled = [n for n, c in sorted(CACHES.items()) if c.get('JOHNNY_CACHE', False)] if len(enabled) > 1: warn("Multiple caches configured for johnny-cache; using %s." % enabled[0]) if enabled: return get_cache(enabled[0]) if CACHE_BACKEND: backend = get_cache(CACHE_BACKEND) if backend not in CACHES: from django.core import signals # Some caches -- python-memcached in particular -- need to do a # cleanup at the end of a request cycle. If the cache provides a # close() method, wire it up here. if hasattr(backend, 'close'): signals.request_finished.connect(backend.close) return backend return cache
[ "def", "_get_backend", "(", ")", ":", "enabled", "=", "[", "n", "for", "n", ",", "c", "in", "sorted", "(", "CACHES", ".", "items", "(", ")", ")", "if", "c", ".", "get", "(", "'JOHNNY_CACHE'", ",", "False", ")", "]", "if", "len", "(", "enabled", ...
Returns the actual django cache object johnny is configured to use. This relies on the settings only; the actual active cache can theoretically be changed at runtime.
[ "Returns", "the", "actual", "django", "cache", "object", "johnny", "is", "configured", "to", "use", ".", "This", "relies", "on", "the", "settings", "only", ";", "the", "actual", "active", "cache", "can", "theoretically", "be", "changed", "at", "runtime", "."...
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/settings.py#L29-L52
train
31,525
panosl/django-currencies
currencies/management/commands/updatecurrencies.py
Command.add_arguments
def add_arguments(self, parser): """Add command arguments""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', help= 'Supply the base currency as code or a settings variable name. ' 'The default is taken from settings CURRENCIES_BASE or SHOP_DEFAULT_CURRENCY, ' 'or the db, otherwise USD')
python
def add_arguments(self, parser): """Add command arguments""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', help= 'Supply the base currency as code or a settings variable name. ' 'The default is taken from settings CURRENCIES_BASE or SHOP_DEFAULT_CURRENCY, ' 'or the db, otherwise USD')
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "self", ".", "_source_param", ",", "*", "*", "self", ".", "_source_kwargs", ")", "parser", ".", "add_argument", "(", "'--base'", ",", "'-b'", ",", "action", ...
Add command arguments
[ "Add", "command", "arguments" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/updatecurrencies.py#L15-L21
train
31,526
panosl/django-currencies
currencies/management/commands/updatecurrencies.py
Command.get_base
def get_base(self, option): """ Parse the base command option. Can be supplied as a 3 character code or a settings variable name If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY """ if option: if option.isupper(): if len(option) > 3: return getattr(settings, option), True elif len(option) == 3: return option, True raise ImproperlyConfigured("Invalid currency code found: %s" % option) for attr in ('CURRENCIES_BASE', 'SHOP_DEFAULT_CURRENCY'): try: return getattr(settings, attr), True except AttributeError: continue return 'USD', False
python
def get_base(self, option): """ Parse the base command option. Can be supplied as a 3 character code or a settings variable name If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY """ if option: if option.isupper(): if len(option) > 3: return getattr(settings, option), True elif len(option) == 3: return option, True raise ImproperlyConfigured("Invalid currency code found: %s" % option) for attr in ('CURRENCIES_BASE', 'SHOP_DEFAULT_CURRENCY'): try: return getattr(settings, attr), True except AttributeError: continue return 'USD', False
[ "def", "get_base", "(", "self", ",", "option", ")", ":", "if", "option", ":", "if", "option", ".", "isupper", "(", ")", ":", "if", "len", "(", "option", ")", ">", "3", ":", "return", "getattr", "(", "settings", ",", "option", ")", ",", "True", "e...
Parse the base command option. Can be supplied as a 3 character code or a settings variable name If base is not supplied, looks for settings CURRENCIES_BASE and SHOP_DEFAULT_CURRENCY
[ "Parse", "the", "base", "command", "option", ".", "Can", "be", "supplied", "as", "a", "3", "character", "code", "or", "a", "settings", "variable", "name", "If", "base", "is", "not", "supplied", "looks", "for", "settings", "CURRENCIES_BASE", "and", "SHOP_DEFA...
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/updatecurrencies.py#L23-L40
train
31,527
jmoiron/johnny-cache
johnny/transaction.py
TransactionManager.set
def set(self, key, val, timeout=None, using=None): """ Set will be using the generational key, so if another thread bumps this key, the localstore version will still be invalid. If the key is bumped during a transaction it will be new to the global cache on commit, so it will still be a bump. """ if timeout is None: timeout = self.timeout if self.is_managed(using=using) and self._patched_var: self.local[key] = val else: self.cache_backend.set(key, val, timeout)
python
def set(self, key, val, timeout=None, using=None): """ Set will be using the generational key, so if another thread bumps this key, the localstore version will still be invalid. If the key is bumped during a transaction it will be new to the global cache on commit, so it will still be a bump. """ if timeout is None: timeout = self.timeout if self.is_managed(using=using) and self._patched_var: self.local[key] = val else: self.cache_backend.set(key, val, timeout)
[ "def", "set", "(", "self", ",", "key", ",", "val", ",", "timeout", "=", "None", ",", "using", "=", "None", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "timeout", "if", "self", ".", "is_managed", "(", "using", "=", "...
Set will be using the generational key, so if another thread bumps this key, the localstore version will still be invalid. If the key is bumped during a transaction it will be new to the global cache on commit, so it will still be a bump.
[ "Set", "will", "be", "using", "the", "generational", "key", "so", "if", "another", "thread", "bumps", "this", "key", "the", "localstore", "version", "will", "still", "be", "invalid", ".", "If", "the", "key", "is", "bumped", "during", "a", "transaction", "i...
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/transaction.py#L81-L93
train
31,528
jmoiron/johnny-cache
johnny/transaction.py
TransactionManager._flush
def _flush(self, commit=True, using=None): """ Flushes the internal cache, either to the memcache or rolls back """ if commit: # XXX: multi-set? if self._uses_savepoints(): self._commit_all_savepoints(using) c = self.local.mget('%s_%s_*' % (self.prefix, self._trunc_using(using))) for key, value in c.items(): self.cache_backend.set(key, value, self.timeout) else: if self._uses_savepoints(): self._rollback_all_savepoints(using) self._clear(using) self._clear_sid_stack(using)
python
def _flush(self, commit=True, using=None): """ Flushes the internal cache, either to the memcache or rolls back """ if commit: # XXX: multi-set? if self._uses_savepoints(): self._commit_all_savepoints(using) c = self.local.mget('%s_%s_*' % (self.prefix, self._trunc_using(using))) for key, value in c.items(): self.cache_backend.set(key, value, self.timeout) else: if self._uses_savepoints(): self._rollback_all_savepoints(using) self._clear(using) self._clear_sid_stack(using)
[ "def", "_flush", "(", "self", ",", "commit", "=", "True", ",", "using", "=", "None", ")", ":", "if", "commit", ":", "# XXX: multi-set?", "if", "self", ".", "_uses_savepoints", "(", ")", ":", "self", ".", "_commit_all_savepoints", "(", "using", ")", "c", ...
Flushes the internal cache, either to the memcache or rolls back
[ "Flushes", "the", "internal", "cache", "either", "to", "the", "memcache", "or", "rolls", "back" ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/transaction.py#L99-L115
train
31,529
jmoiron/johnny-cache
johnny/localstore.py
LocalStore.clear
def clear(self, pat=None): """ Minor diversion with built-in dict here; clear can take a glob style expression and remove keys based on that expression. """ if pat is None: return self.__dict__.clear() expr = re.compile(fnmatch.translate(pat)) for key in tuple(self.keys()): #make sure the key is a str first if isinstance(key, string_types): if expr.match(key): del self.__dict__[key]
python
def clear(self, pat=None): """ Minor diversion with built-in dict here; clear can take a glob style expression and remove keys based on that expression. """ if pat is None: return self.__dict__.clear() expr = re.compile(fnmatch.translate(pat)) for key in tuple(self.keys()): #make sure the key is a str first if isinstance(key, string_types): if expr.match(key): del self.__dict__[key]
[ "def", "clear", "(", "self", ",", "pat", "=", "None", ")", ":", "if", "pat", "is", "None", ":", "return", "self", ".", "__dict__", ".", "clear", "(", ")", "expr", "=", "re", ".", "compile", "(", "fnmatch", ".", "translate", "(", "pat", ")", ")", ...
Minor diversion with built-in dict here; clear can take a glob style expression and remove keys based on that expression.
[ "Minor", "diversion", "with", "built", "-", "in", "dict", "here", ";", "clear", "can", "take", "a", "glob", "style", "expression", "and", "remove", "keys", "based", "on", "that", "expression", "." ]
d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c
https://github.com/jmoiron/johnny-cache/blob/d96ea94c5dfcde517ff8f65d6ba4e435d8a0168c/johnny/localstore.py#L92-L105
train
31,530
panosl/django-currencies
currencies/management/commands/_yahoofinance.py
CurrencyHandler.get_bulkcurrencies
def get_bulkcurrencies(self): """ Get the supported currencies Scraped from a JSON object on the html page in javascript tag """ start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\(' _json = r'\[[^\]]*\]' try: resp = get(self.currencies_url) resp.raise_for_status() except exceptions.RequestException as e: self.log(logging.ERROR, "%s Deprecated: API withdrawn in February 2018:\n%s", self.name, e) else: # Find the javascript that contains the json object soup = BS4(resp.text, 'html.parser') re_start = re.compile(start) try: jscript = soup.find('script', type='text/javascript', text=re_start).string except AttributeError: self.log(logging.WARNING, "%s: Live currency data not found, using cached copy.", self.name) else: # Separate the json object re_json = re.compile(_json) match = re_json.search(jscript) if match: json_str = match.group(0) with open(self._cached_currency_file, 'w') as fd: fd.write(json_str.encode('utf-8')) # Parse the json file try: with open(self._cached_currency_file, 'r') as fd: j = json.load(fd) except FileNotFoundError: j = None if not j: raise RuntimeError("%s: JSON not found at endpoint or as cached file:\n%s" % ( self.name, self._cached_currency_file)) return j
python
def get_bulkcurrencies(self): """ Get the supported currencies Scraped from a JSON object on the html page in javascript tag """ start = r'YAHOO\.Finance\.CurrencyConverter\.addCurrencies\(' _json = r'\[[^\]]*\]' try: resp = get(self.currencies_url) resp.raise_for_status() except exceptions.RequestException as e: self.log(logging.ERROR, "%s Deprecated: API withdrawn in February 2018:\n%s", self.name, e) else: # Find the javascript that contains the json object soup = BS4(resp.text, 'html.parser') re_start = re.compile(start) try: jscript = soup.find('script', type='text/javascript', text=re_start).string except AttributeError: self.log(logging.WARNING, "%s: Live currency data not found, using cached copy.", self.name) else: # Separate the json object re_json = re.compile(_json) match = re_json.search(jscript) if match: json_str = match.group(0) with open(self._cached_currency_file, 'w') as fd: fd.write(json_str.encode('utf-8')) # Parse the json file try: with open(self._cached_currency_file, 'r') as fd: j = json.load(fd) except FileNotFoundError: j = None if not j: raise RuntimeError("%s: JSON not found at endpoint or as cached file:\n%s" % ( self.name, self._cached_currency_file)) return j
[ "def", "get_bulkcurrencies", "(", "self", ")", ":", "start", "=", "r'YAHOO\\.Finance\\.CurrencyConverter\\.addCurrencies\\('", "_json", "=", "r'\\[[^\\]]*\\]'", "try", ":", "resp", "=", "get", "(", "self", ".", "currencies_url", ")", "resp", ".", "raise_for_status", ...
Get the supported currencies Scraped from a JSON object on the html page in javascript tag
[ "Get", "the", "supported", "currencies", "Scraped", "from", "a", "JSON", "object", "on", "the", "html", "page", "in", "javascript", "tag" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L62-L100
train
31,531
panosl/django-currencies
currencies/management/commands/_yahoofinance.py
CurrencyHandler.get_bulkrates
def get_bulkrates(self): """Get & format the rates dict""" try: resp = get(self.bulk_url) resp.raise_for_status() except exceptions.RequestException as e: raise RuntimeError(e) return resp.json()
python
def get_bulkrates(self): """Get & format the rates dict""" try: resp = get(self.bulk_url) resp.raise_for_status() except exceptions.RequestException as e: raise RuntimeError(e) return resp.json()
[ "def", "get_bulkrates", "(", "self", ")", ":", "try", ":", "resp", "=", "get", "(", "self", ".", "bulk_url", ")", "resp", ".", "raise_for_status", "(", ")", "except", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "RuntimeError", "(", "e...
Get & format the rates dict
[ "Get", "&", "format", "the", "rates", "dict" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L102-L109
train
31,532
panosl/django-currencies
currencies/management/commands/_yahoofinance.py
CurrencyHandler.get_singlerate
def get_singlerate(self, base, code): """Get a single rate, used as fallback""" try: url = self.onerate_url % (base, code) resp = get(url) resp.raise_for_status() except exceptions.HTTPError as e: self.log(logging.ERROR, "%s: problem with %s:\n%s", self.name, url, e) return None rate = resp.text.rstrip() if rate == 'N/A': raise RuntimeError("%s: %s not found" % (self.name, code)) else: return Decimal(rate)
python
def get_singlerate(self, base, code): """Get a single rate, used as fallback""" try: url = self.onerate_url % (base, code) resp = get(url) resp.raise_for_status() except exceptions.HTTPError as e: self.log(logging.ERROR, "%s: problem with %s:\n%s", self.name, url, e) return None rate = resp.text.rstrip() if rate == 'N/A': raise RuntimeError("%s: %s not found" % (self.name, code)) else: return Decimal(rate)
[ "def", "get_singlerate", "(", "self", ",", "base", ",", "code", ")", ":", "try", ":", "url", "=", "self", ".", "onerate_url", "%", "(", "base", ",", "code", ")", "resp", "=", "get", "(", "url", ")", "resp", ".", "raise_for_status", "(", ")", "excep...
Get a single rate, used as fallback
[ "Get", "a", "single", "rate", "used", "as", "fallback" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L111-L125
train
31,533
panosl/django-currencies
currencies/management/commands/_yahoofinance.py
CurrencyHandler.get_baserate
def get_baserate(self): """Helper function to populate the base rate""" rateslist = self.rates['list']['resources'] for rate in rateslist: rateobj = rate['resource']['fields'] if rateobj['symbol'].partition('=')[0] == rateobj['name']: return rateobj['name'] raise RuntimeError("%s: baserate not found" % self.name)
python
def get_baserate(self): """Helper function to populate the base rate""" rateslist = self.rates['list']['resources'] for rate in rateslist: rateobj = rate['resource']['fields'] if rateobj['symbol'].partition('=')[0] == rateobj['name']: return rateobj['name'] raise RuntimeError("%s: baserate not found" % self.name)
[ "def", "get_baserate", "(", "self", ")", ":", "rateslist", "=", "self", ".", "rates", "[", "'list'", "]", "[", "'resources'", "]", "for", "rate", "in", "rateslist", ":", "rateobj", "=", "rate", "[", "'resource'", "]", "[", "'fields'", "]", "if", "rateo...
Helper function to populate the base rate
[ "Helper", "function", "to", "populate", "the", "base", "rate" ]
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L185-L192
train
31,534
panosl/django-currencies
currencies/management/commands/_yahoofinance.py
CurrencyHandler.get_ratefactor
def get_ratefactor(self, base, code): """ Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError Yahoo currently uses USD as base currency, but here we detect it with get_baserate """ raise RuntimeError("%s Deprecated: API withdrawn in February 2018" % self.name) try: rate = self.get_rate(code) except RuntimeError: # fallback return self.get_singlerate(base, code) self.check_ratebase(rate) ratefactor = Decimal(rate['price']) if base == self.base: return ratefactor else: return self.ratechangebase(ratefactor, self.base, base)
python
def get_ratefactor(self, base, code): """ Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError Yahoo currently uses USD as base currency, but here we detect it with get_baserate """ raise RuntimeError("%s Deprecated: API withdrawn in February 2018" % self.name) try: rate = self.get_rate(code) except RuntimeError: # fallback return self.get_singlerate(base, code) self.check_ratebase(rate) ratefactor = Decimal(rate['price']) if base == self.base: return ratefactor else: return self.ratechangebase(ratefactor, self.base, base)
[ "def", "get_ratefactor", "(", "self", ",", "base", ",", "code", ")", ":", "raise", "RuntimeError", "(", "\"%s Deprecated: API withdrawn in February 2018\"", "%", "self", ".", "name", ")", "try", ":", "rate", "=", "self", ".", "get_rate", "(", "code", ")", "e...
Return the Decimal currency exchange rate factor of 'code' compared to 1 'base' unit, or RuntimeError Yahoo currently uses USD as base currency, but here we detect it with get_baserate
[ "Return", "the", "Decimal", "currency", "exchange", "rate", "factor", "of", "code", "compared", "to", "1", "base", "unit", "or", "RuntimeError", "Yahoo", "currently", "uses", "USD", "as", "base", "currency", "but", "here", "we", "detect", "it", "with", "get_...
8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/_yahoofinance.py#L219-L237
train
31,535
awesmubarak/markdown_strings
markdown_strings/__init__.py
header
def header(heading_text, header_level, style="atx"): """Return a header of specified level. Keyword arguments: style -- Specifies the header style (default atx). The "atx" style uses hash signs, and has 6 levels. The "setext" style uses dashes or equals signs for headers of levels 1 and 2 respectively, and is limited to those two levels. Specifying a level outside of the style's range results in a ValueError. >>> header("Main Title", 1) '# Main Title' >>> header("Smaller subtitle", 4) '#### Smaller subtitle' >>> header("Setext style", 2, style="setext") 'Setext style\\n---' """ if not isinstance(header_level, int): raise TypeError("header_level must be int") if style not in ["atx", "setext"]: raise ValueError("Invalid style %s (choose 'atx' or 'setext')" % style) if style == "atx": if not 1 <= header_level <= 6: raise ValueError("Invalid level %d for atx" % header_level) return ("#" * header_level) + " " + esc_format(heading_text) else: if not 0 < header_level < 3: raise ValueError("Invalid level %d for setext" % header_level) header_character = "=" if header_level == 1 else "-" return esc_format(heading_text) + ("\n%s" % (header_character * 3))
python
def header(heading_text, header_level, style="atx"): """Return a header of specified level. Keyword arguments: style -- Specifies the header style (default atx). The "atx" style uses hash signs, and has 6 levels. The "setext" style uses dashes or equals signs for headers of levels 1 and 2 respectively, and is limited to those two levels. Specifying a level outside of the style's range results in a ValueError. >>> header("Main Title", 1) '# Main Title' >>> header("Smaller subtitle", 4) '#### Smaller subtitle' >>> header("Setext style", 2, style="setext") 'Setext style\\n---' """ if not isinstance(header_level, int): raise TypeError("header_level must be int") if style not in ["atx", "setext"]: raise ValueError("Invalid style %s (choose 'atx' or 'setext')" % style) if style == "atx": if not 1 <= header_level <= 6: raise ValueError("Invalid level %d for atx" % header_level) return ("#" * header_level) + " " + esc_format(heading_text) else: if not 0 < header_level < 3: raise ValueError("Invalid level %d for setext" % header_level) header_character = "=" if header_level == 1 else "-" return esc_format(heading_text) + ("\n%s" % (header_character * 3))
[ "def", "header", "(", "heading_text", ",", "header_level", ",", "style", "=", "\"atx\"", ")", ":", "if", "not", "isinstance", "(", "header_level", ",", "int", ")", ":", "raise", "TypeError", "(", "\"header_level must be int\"", ")", "if", "style", "not", "in...
Return a header of specified level. Keyword arguments: style -- Specifies the header style (default atx). The "atx" style uses hash signs, and has 6 levels. The "setext" style uses dashes or equals signs for headers of levels 1 and 2 respectively, and is limited to those two levels. Specifying a level outside of the style's range results in a ValueError. >>> header("Main Title", 1) '# Main Title' >>> header("Smaller subtitle", 4) '#### Smaller subtitle' >>> header("Setext style", 2, style="setext") 'Setext style\\n---'
[ "Return", "a", "header", "of", "specified", "level", "." ]
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L39-L69
train
31,536
awesmubarak/markdown_strings
markdown_strings/__init__.py
code_block
def code_block(text, language=""): """Return a code block. If a language is specified a fenced code block is produced, otherwise the block is indented by four spaces. Keyword arguments: language -- Specifies the language to fence the code in (default blank). >>> code_block("This is a simple codeblock.") ' This is a simple codeblock.' >>> code_block("This is a simple codeblock.\\nBut it has a linebreak!") ' This is a simple codeblock.\\n But it has a linebreak!' >>> code_block("This block of code has a specified language.", "python") '```python\\nThis block of code has a specified language.\\n```' >>> code_block("So\\nmany\\nlinebreaks.", "python") '```python\\nSo\\nmany\\nlinebreaks.\\n```' """ if language: return "```" + language + "\n" + text + "\n```" return "\n".join([" " + item for item in text.split("\n")])
python
def code_block(text, language=""): """Return a code block. If a language is specified a fenced code block is produced, otherwise the block is indented by four spaces. Keyword arguments: language -- Specifies the language to fence the code in (default blank). >>> code_block("This is a simple codeblock.") ' This is a simple codeblock.' >>> code_block("This is a simple codeblock.\\nBut it has a linebreak!") ' This is a simple codeblock.\\n But it has a linebreak!' >>> code_block("This block of code has a specified language.", "python") '```python\\nThis block of code has a specified language.\\n```' >>> code_block("So\\nmany\\nlinebreaks.", "python") '```python\\nSo\\nmany\\nlinebreaks.\\n```' """ if language: return "```" + language + "\n" + text + "\n```" return "\n".join([" " + item for item in text.split("\n")])
[ "def", "code_block", "(", "text", ",", "language", "=", "\"\"", ")", ":", "if", "language", ":", "return", "\"```\"", "+", "language", "+", "\"\\n\"", "+", "text", "+", "\"\\n```\"", "return", "\"\\n\"", ".", "join", "(", "[", "\" \"", "+", "item", ...
Return a code block. If a language is specified a fenced code block is produced, otherwise the block is indented by four spaces. Keyword arguments: language -- Specifies the language to fence the code in (default blank). >>> code_block("This is a simple codeblock.") ' This is a simple codeblock.' >>> code_block("This is a simple codeblock.\\nBut it has a linebreak!") ' This is a simple codeblock.\\n But it has a linebreak!' >>> code_block("This block of code has a specified language.", "python") '```python\\nThis block of code has a specified language.\\n```' >>> code_block("So\\nmany\\nlinebreaks.", "python") '```python\\nSo\\nmany\\nlinebreaks.\\n```'
[ "Return", "a", "code", "block", "." ]
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L106-L126
train
31,537
awesmubarak/markdown_strings
markdown_strings/__init__.py
image
def image(alt_text, link_url, title=""): """Return an inline image. Keyword arguments: title -- Specify the title of the image, as seen when hovering over it. >>> image("This is an image", "https://tinyurl.com/bright-green-tree") '![This is an image](https://tinyurl.com/bright-green-tree)' >>> image("This is an image", "https://tinyurl.com/bright-green-tree", "tree") '![This is an image](https://tinyurl.com/bright-green-tree) "tree"' """ image_string = "![" + esc_format(alt_text) + "](" + link_url + ")" if title: image_string += ' "' + esc_format(title) + '"' return image_string
python
def image(alt_text, link_url, title=""): """Return an inline image. Keyword arguments: title -- Specify the title of the image, as seen when hovering over it. >>> image("This is an image", "https://tinyurl.com/bright-green-tree") '![This is an image](https://tinyurl.com/bright-green-tree)' >>> image("This is an image", "https://tinyurl.com/bright-green-tree", "tree") '![This is an image](https://tinyurl.com/bright-green-tree) "tree"' """ image_string = "![" + esc_format(alt_text) + "](" + link_url + ")" if title: image_string += ' "' + esc_format(title) + '"' return image_string
[ "def", "image", "(", "alt_text", ",", "link_url", ",", "title", "=", "\"\"", ")", ":", "image_string", "=", "\"![\"", "+", "esc_format", "(", "alt_text", ")", "+", "\"](\"", "+", "link_url", "+", "\")\"", "if", "title", ":", "image_string", "+=", "' \"'"...
Return an inline image. Keyword arguments: title -- Specify the title of the image, as seen when hovering over it. >>> image("This is an image", "https://tinyurl.com/bright-green-tree") '![This is an image](https://tinyurl.com/bright-green-tree)' >>> image("This is an image", "https://tinyurl.com/bright-green-tree", "tree") '![This is an image](https://tinyurl.com/bright-green-tree) "tree"'
[ "Return", "an", "inline", "image", "." ]
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L141-L155
train
31,538
awesmubarak/markdown_strings
markdown_strings/__init__.py
ordered_list
def ordered_list(text_array): """Return an ordered list from an array. >>> ordered_list(["first", "second", "third", "fourth"]) '1. first\\n2. second\\n3. third\\n4. fourth' """ text_list = [] for number, item in enumerate(text_array): text_list.append( (esc_format(number + 1) + ".").ljust(3) + " " + esc_format(item) ) return "\n".join(text_list)
python
def ordered_list(text_array): """Return an ordered list from an array. >>> ordered_list(["first", "second", "third", "fourth"]) '1. first\\n2. second\\n3. third\\n4. fourth' """ text_list = [] for number, item in enumerate(text_array): text_list.append( (esc_format(number + 1) + ".").ljust(3) + " " + esc_format(item) ) return "\n".join(text_list)
[ "def", "ordered_list", "(", "text_array", ")", ":", "text_list", "=", "[", "]", "for", "number", ",", "item", "in", "enumerate", "(", "text_array", ")", ":", "text_list", ".", "append", "(", "(", "esc_format", "(", "number", "+", "1", ")", "+", "\".\""...
Return an ordered list from an array. >>> ordered_list(["first", "second", "third", "fourth"]) '1. first\\n2. second\\n3. third\\n4. fourth'
[ "Return", "an", "ordered", "list", "from", "an", "array", "." ]
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L172-L183
train
31,539
awesmubarak/markdown_strings
markdown_strings/__init__.py
task_list
def task_list(task_array): """Return a task list. The task_array should be 2-dimensional; the first item should be the task text, and the second the boolean completion state. >>> task_list([["Be born", True], ["Be dead", False]]) '- [X] Be born\\n- [ ] Be dead' When displayed using `print`, this will appear as: - [X] Be born - [ ] Be dead """ tasks = [] for item, completed in task_array: task = "- [ ] " + esc_format(item) if completed: task = task[:3] + "X" + task[4:] tasks.append(task) return "\n".join(tasks)
python
def task_list(task_array): """Return a task list. The task_array should be 2-dimensional; the first item should be the task text, and the second the boolean completion state. >>> task_list([["Be born", True], ["Be dead", False]]) '- [X] Be born\\n- [ ] Be dead' When displayed using `print`, this will appear as: - [X] Be born - [ ] Be dead """ tasks = [] for item, completed in task_array: task = "- [ ] " + esc_format(item) if completed: task = task[:3] + "X" + task[4:] tasks.append(task) return "\n".join(tasks)
[ "def", "task_list", "(", "task_array", ")", ":", "tasks", "=", "[", "]", "for", "item", ",", "completed", "in", "task_array", ":", "task", "=", "\"- [ ] \"", "+", "esc_format", "(", "item", ")", "if", "completed", ":", "task", "=", "task", "[", ":", ...
Return a task list. The task_array should be 2-dimensional; the first item should be the task text, and the second the boolean completion state. >>> task_list([["Be born", True], ["Be dead", False]]) '- [X] Be born\\n- [ ] Be dead' When displayed using `print`, this will appear as: - [X] Be born - [ ] Be dead
[ "Return", "a", "task", "list", "." ]
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L231-L251
train
31,540
awesmubarak/markdown_strings
markdown_strings/__init__.py
table
def table(big_array): """Return a formatted table, generated from arrays representing columns. The function requires a 2-dimensional array, where each array is a column of the table. This will be used to generate a formatted table in string format. The number of items in each columns does not need to be consitent. >>> table([["Name", "abactel", "Bob"], ["User", "4b4c73l", ""]]) '| Name | User |\\n| ------- | ------- |\\n| abactel | 4b4c73l |\\n| Bob | |' When displayed using `print`, this will appear: | Name | User | | ------- | ------- | | abactel | 4b4c73l | | Bob | | """ number_of_columns = len(big_array) number_of_rows_in_column = [len(column) for column in big_array] max_cell_size = [len(max(column, key=len)) for column in big_array] table = [] # title row row_array = [column[0] for column in big_array] table.append(table_row(row_array, pad=max_cell_size)) # delimiter row row_array = [] for column_number in range(number_of_columns): row_array.append("-" * max_cell_size[column_number]) table.append(table_row(row_array, pad=max_cell_size)) # body rows for row in range(1, max(number_of_rows_in_column)): row_array = [] for column_number in range(number_of_columns): if number_of_rows_in_column[column_number] > row: row_array.append(big_array[column_number][row]) else: row_array.append() table.append(table_row(row_array, pad=max_cell_size)) return "\n".join(table)
python
def table(big_array): """Return a formatted table, generated from arrays representing columns. The function requires a 2-dimensional array, where each array is a column of the table. This will be used to generate a formatted table in string format. The number of items in each columns does not need to be consitent. >>> table([["Name", "abactel", "Bob"], ["User", "4b4c73l", ""]]) '| Name | User |\\n| ------- | ------- |\\n| abactel | 4b4c73l |\\n| Bob | |' When displayed using `print`, this will appear: | Name | User | | ------- | ------- | | abactel | 4b4c73l | | Bob | | """ number_of_columns = len(big_array) number_of_rows_in_column = [len(column) for column in big_array] max_cell_size = [len(max(column, key=len)) for column in big_array] table = [] # title row row_array = [column[0] for column in big_array] table.append(table_row(row_array, pad=max_cell_size)) # delimiter row row_array = [] for column_number in range(number_of_columns): row_array.append("-" * max_cell_size[column_number]) table.append(table_row(row_array, pad=max_cell_size)) # body rows for row in range(1, max(number_of_rows_in_column)): row_array = [] for column_number in range(number_of_columns): if number_of_rows_in_column[column_number] > row: row_array.append(big_array[column_number][row]) else: row_array.append() table.append(table_row(row_array, pad=max_cell_size)) return "\n".join(table)
[ "def", "table", "(", "big_array", ")", ":", "number_of_columns", "=", "len", "(", "big_array", ")", "number_of_rows_in_column", "=", "[", "len", "(", "column", ")", "for", "column", "in", "big_array", "]", "max_cell_size", "=", "[", "len", "(", "max", "(",...
Return a formatted table, generated from arrays representing columns. The function requires a 2-dimensional array, where each array is a column of the table. This will be used to generate a formatted table in string format. The number of items in each columns does not need to be consitent. >>> table([["Name", "abactel", "Bob"], ["User", "4b4c73l", ""]]) '| Name | User |\\n| ------- | ------- |\\n| abactel | 4b4c73l |\\n| Bob | |' When displayed using `print`, this will appear: | Name | User | | ------- | ------- | | abactel | 4b4c73l | | Bob | |
[ "Return", "a", "formatted", "table", "generated", "from", "arrays", "representing", "columns", ".", "The", "function", "requires", "a", "2", "-", "dimensional", "array", "where", "each", "array", "is", "a", "column", "of", "the", "table", ".", "This", "will"...
569e225e7a8f23469efe8df244d3d3fd0e8c3b3e
https://github.com/awesmubarak/markdown_strings/blob/569e225e7a8f23469efe8df244d3d3fd0e8c3b3e/markdown_strings/__init__.py#L285-L324
train
31,541
DinoTools/python-ssdeep
src/ssdeep/__init__.py
compare
def compare(sig1, sig2): """ Computes the match score between two fuzzy hash signatures. Returns a value from zero to 100 indicating the match score of the two signatures. A match score of zero indicates the signatures did not match. :param Bytes|String sig1: First fuzzy hash signature :param Bytes|String sig2: Second fuzzy hash signature :return: Match score (0-100) :rtype: Integer :raises InternalError: If lib returns an internal error :raises TypeError: If sig is not String, Unicode or Bytes """ if isinstance(sig1, six.text_type): sig1 = sig1.encode("ascii") if isinstance(sig2, six.text_type): sig2 = sig2.encode("ascii") if not isinstance(sig1, six.binary_type): raise TypeError( "First argument must be of string, unicode or bytes type not " "'%s'" % type(sig1) ) if not isinstance(sig2, six.binary_type): raise TypeError( "Second argument must be of string, unicode or bytes type not " "'%r'" % type(sig2) ) res = binding.lib.fuzzy_compare(sig1, sig2) if res < 0: raise InternalError("Function returned an unexpected error code") return res
python
def compare(sig1, sig2): """ Computes the match score between two fuzzy hash signatures. Returns a value from zero to 100 indicating the match score of the two signatures. A match score of zero indicates the signatures did not match. :param Bytes|String sig1: First fuzzy hash signature :param Bytes|String sig2: Second fuzzy hash signature :return: Match score (0-100) :rtype: Integer :raises InternalError: If lib returns an internal error :raises TypeError: If sig is not String, Unicode or Bytes """ if isinstance(sig1, six.text_type): sig1 = sig1.encode("ascii") if isinstance(sig2, six.text_type): sig2 = sig2.encode("ascii") if not isinstance(sig1, six.binary_type): raise TypeError( "First argument must be of string, unicode or bytes type not " "'%s'" % type(sig1) ) if not isinstance(sig2, six.binary_type): raise TypeError( "Second argument must be of string, unicode or bytes type not " "'%r'" % type(sig2) ) res = binding.lib.fuzzy_compare(sig1, sig2) if res < 0: raise InternalError("Function returned an unexpected error code") return res
[ "def", "compare", "(", "sig1", ",", "sig2", ")", ":", "if", "isinstance", "(", "sig1", ",", "six", ".", "text_type", ")", ":", "sig1", "=", "sig1", ".", "encode", "(", "\"ascii\"", ")", "if", "isinstance", "(", "sig2", ",", "six", ".", "text_type", ...
Computes the match score between two fuzzy hash signatures. Returns a value from zero to 100 indicating the match score of the two signatures. A match score of zero indicates the signatures did not match. :param Bytes|String sig1: First fuzzy hash signature :param Bytes|String sig2: Second fuzzy hash signature :return: Match score (0-100) :rtype: Integer :raises InternalError: If lib returns an internal error :raises TypeError: If sig is not String, Unicode or Bytes
[ "Computes", "the", "match", "score", "between", "two", "fuzzy", "hash", "signatures", "." ]
c17b3dc0f53514afff59eca67717291ccd206b7c
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L150-L188
train
31,542
DinoTools/python-ssdeep
src/ssdeep/__init__.py
hash
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isinstance(buf, six.text_type): buf = buf.encode(encoding) if not isinstance(buf, six.binary_type): raise TypeError( "Argument must be of string, unicode or bytes type not " "'%r'" % type(buf) ) # allocate memory for result result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_hash_buf(buf, len(buf), result) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
python
def hash(buf, encoding="utf-8"): """ Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes """ if isinstance(buf, six.text_type): buf = buf.encode(encoding) if not isinstance(buf, six.binary_type): raise TypeError( "Argument must be of string, unicode or bytes type not " "'%r'" % type(buf) ) # allocate memory for result result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_hash_buf(buf, len(buf), result) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
[ "def", "hash", "(", "buf", ",", "encoding", "=", "\"utf-8\"", ")", ":", "if", "isinstance", "(", "buf", ",", "six", ".", "text_type", ")", ":", "buf", "=", "buf", ".", "encode", "(", "encoding", ")", "if", "not", "isinstance", "(", "buf", ",", "six...
Compute the fuzzy hash of a buffer :param String|Bytes buf: The data to be fuzzy hashed :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error :raises TypeError: If buf is not String or Bytes
[ "Compute", "the", "fuzzy", "hash", "of", "a", "buffer" ]
c17b3dc0f53514afff59eca67717291ccd206b7c
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L191-L217
train
31,543
DinoTools/python-ssdeep
src/ssdeep/__init__.py
hash_from_file
def hash_from_file(filename): """ Compute the fuzzy hash of a file. Opens, reads, and hashes the contents of the file 'filename' :param String|Bytes filename: The name of the file to be hashed :return: The fuzzy hash of the file :rtype: String :raises IOError: If Python is unable to read the file :raises InternalError: If lib returns an internal error """ if not os.path.exists(filename): raise IOError("Path not found") if not os.path.isfile(filename): raise IOError("File not found") if not os.access(filename, os.R_OK): raise IOError("File is not readable") result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_hash_filename(filename.encode("utf-8"), result) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
python
def hash_from_file(filename): """ Compute the fuzzy hash of a file. Opens, reads, and hashes the contents of the file 'filename' :param String|Bytes filename: The name of the file to be hashed :return: The fuzzy hash of the file :rtype: String :raises IOError: If Python is unable to read the file :raises InternalError: If lib returns an internal error """ if not os.path.exists(filename): raise IOError("Path not found") if not os.path.isfile(filename): raise IOError("File not found") if not os.access(filename, os.R_OK): raise IOError("File is not readable") result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_hash_filename(filename.encode("utf-8"), result) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
[ "def", "hash_from_file", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOError", "(", "\"Path not found\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", ...
Compute the fuzzy hash of a file. Opens, reads, and hashes the contents of the file 'filename' :param String|Bytes filename: The name of the file to be hashed :return: The fuzzy hash of the file :rtype: String :raises IOError: If Python is unable to read the file :raises InternalError: If lib returns an internal error
[ "Compute", "the", "fuzzy", "hash", "of", "a", "file", "." ]
c17b3dc0f53514afff59eca67717291ccd206b7c
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L220-L245
train
31,544
DinoTools/python-ssdeep
src/ssdeep/__init__.py
Hash.digest
def digest(self, elimseq=False, notrunc=False): """ Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error """ if self._state == ffi.NULL: raise InternalError("State object is NULL") flags = (binding.lib.FUZZY_FLAG_ELIMSEQ if elimseq else 0) | \ (binding.lib.FUZZY_FLAG_NOTRUNC if notrunc else 0) result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_digest(self._state, result, flags) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
python
def digest(self, elimseq=False, notrunc=False): """ Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error """ if self._state == ffi.NULL: raise InternalError("State object is NULL") flags = (binding.lib.FUZZY_FLAG_ELIMSEQ if elimseq else 0) | \ (binding.lib.FUZZY_FLAG_NOTRUNC if notrunc else 0) result = ffi.new("char[]", binding.lib.FUZZY_MAX_RESULT) if binding.lib.fuzzy_digest(self._state, result, flags) != 0: raise InternalError("Function returned an unexpected error code") return ffi.string(result).decode("ascii")
[ "def", "digest", "(", "self", ",", "elimseq", "=", "False", ",", "notrunc", "=", "False", ")", ":", "if", "self", ".", "_state", "==", "ffi", ".", "NULL", ":", "raise", "InternalError", "(", "\"State object is NULL\"", ")", "flags", "=", "(", "binding", ...
Obtain the fuzzy hash. This operation does not change the state at all. It reports the hash for the concatenation of the data previously fed using update(). :return: The fuzzy hash :rtype: String :raises InternalError: If lib returns an internal error
[ "Obtain", "the", "fuzzy", "hash", "." ]
c17b3dc0f53514afff59eca67717291ccd206b7c
https://github.com/DinoTools/python-ssdeep/blob/c17b3dc0f53514afff59eca67717291ccd206b7c/src/ssdeep/__init__.py#L74-L97
train
31,545
Pythonity/icon-font-to-png
icon_font_to_png/icon_font.py
IconFont.load_css
def load_css(self): """ Creates a dict of all icons available in CSS file, and finds out what's their common prefix. :returns sorted icons dict, common icon prefix """ icons = dict() common_prefix = None parser = tinycss.make_parser('page3') stylesheet = parser.parse_stylesheet_file(self.css_file) is_icon = re.compile("\.(.*):before,?") for rule in stylesheet.rules: selector = rule.selector.as_css() # Skip CSS classes that are not icons if not is_icon.match(selector): continue # Find out what the common prefix is if common_prefix is None: common_prefix = selector[1:] else: common_prefix = os.path.commonprefix((common_prefix, selector[1:])) for match in is_icon.finditer(selector): name = match.groups()[0] for declaration in rule.declarations: if declaration.name == "content": val = declaration.value.as_css() # Strip quotation marks if re.match("^['\"].*['\"]$", val): val = val[1:-1] icons[name] = unichr(int(val[1:], 16)) common_prefix = common_prefix or '' # Remove common prefix if not self.keep_prefix and len(common_prefix) > 0: non_prefixed_icons = {} for name in icons.keys(): non_prefixed_icons[name[len(common_prefix):]] = icons[name] icons = non_prefixed_icons sorted_icons = OrderedDict(sorted(icons.items(), key=lambda t: t[0])) return sorted_icons, common_prefix
python
def load_css(self): """ Creates a dict of all icons available in CSS file, and finds out what's their common prefix. :returns sorted icons dict, common icon prefix """ icons = dict() common_prefix = None parser = tinycss.make_parser('page3') stylesheet = parser.parse_stylesheet_file(self.css_file) is_icon = re.compile("\.(.*):before,?") for rule in stylesheet.rules: selector = rule.selector.as_css() # Skip CSS classes that are not icons if not is_icon.match(selector): continue # Find out what the common prefix is if common_prefix is None: common_prefix = selector[1:] else: common_prefix = os.path.commonprefix((common_prefix, selector[1:])) for match in is_icon.finditer(selector): name = match.groups()[0] for declaration in rule.declarations: if declaration.name == "content": val = declaration.value.as_css() # Strip quotation marks if re.match("^['\"].*['\"]$", val): val = val[1:-1] icons[name] = unichr(int(val[1:], 16)) common_prefix = common_prefix or '' # Remove common prefix if not self.keep_prefix and len(common_prefix) > 0: non_prefixed_icons = {} for name in icons.keys(): non_prefixed_icons[name[len(common_prefix):]] = icons[name] icons = non_prefixed_icons sorted_icons = OrderedDict(sorted(icons.items(), key=lambda t: t[0])) return sorted_icons, common_prefix
[ "def", "load_css", "(", "self", ")", ":", "icons", "=", "dict", "(", ")", "common_prefix", "=", "None", "parser", "=", "tinycss", ".", "make_parser", "(", "'page3'", ")", "stylesheet", "=", "parser", ".", "parse_stylesheet_file", "(", "self", ".", "css_fil...
Creates a dict of all icons available in CSS file, and finds out what's their common prefix. :returns sorted icons dict, common icon prefix
[ "Creates", "a", "dict", "of", "all", "icons", "available", "in", "CSS", "file", "and", "finds", "out", "what", "s", "their", "common", "prefix", "." ]
4851fe15c077402749f843d43fbc10d28f6c655d
https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/icon_font.py#L27-L76
train
31,546
Pythonity/icon-font-to-png
icon_font_to_png/icon_font.py
IconFont.export_icon
def export_icon(self, icon, size, color='black', scale='auto', filename=None, export_dir='exported'): """ Exports given icon with provided parameters. If the desired icon size is less than 150x150 pixels, we will first create a 150x150 pixels image and then scale it down, so that it's much less likely that the edges of the icon end up cropped. :param icon: valid icon name :param filename: name of the output file :param size: icon size in pixels :param color: color name or hex value :param scale: scaling factor between 0 and 1, or 'auto' for automatic scaling :param export_dir: path to export directory """ org_size = size size = max(150, size) image = Image.new("RGBA", (size, size), color=(0, 0, 0, 0)) draw = ImageDraw.Draw(image) if scale == 'auto': scale_factor = 1 else: scale_factor = float(scale) font = ImageFont.truetype(self.ttf_file, int(size * scale_factor)) width, height = draw.textsize(self.css_icons[icon], font=font) # If auto-scaling is enabled, we need to make sure the resulting # graphic fits inside the boundary. The values are rounded and may be # off by a pixel or two, so we may need to do a few iterations. # The use of a decrementing multiplication factor protects us from # getting into an infinite loop. if scale == 'auto': iteration = 0 factor = 1 while True: width, height = draw.textsize(self.css_icons[icon], font=font) # Check if the image fits dim = max(width, height) if dim > size: font = ImageFont.truetype(self.ttf_file, int(size * size/dim * factor)) else: break # Adjust the factor every two iterations iteration += 1 if iteration % 2 == 0: factor *= 0.99 draw.text((float(size - width) / 2, float(size - height) / 2), self.css_icons[icon], font=font, fill=color) # Get bounding box bbox = image.getbbox() # Create an alpha mask image_mask = Image.new("L", (size, size), 0) draw_mask = ImageDraw.Draw(image_mask) # Draw the icon on the mask draw_mask.text((float(size - width) / 2, float(size - height) / 2), self.css_icons[icon], font=font, fill=255) # Create a solid color image and apply the mask icon_image = Image.new("RGBA", (size, size), color) icon_image.putalpha(image_mask) if bbox: icon_image = icon_image.crop(bbox) border_w = int((size - (bbox[2] - bbox[0])) / 2) border_h = int((size - (bbox[3] - bbox[1])) / 2) # Create output image out_image = Image.new("RGBA", (size, size), (0, 0, 0, 0)) out_image.paste(icon_image, (border_w, border_h)) # If necessary, scale the image to the target size if org_size != size: out_image = out_image.resize((org_size, org_size), Image.ANTIALIAS) # Make sure export directory exists if not os.path.exists(export_dir): os.makedirs(export_dir) # Default filename if not filename: filename = icon + '.png' # Save file out_image.save(os.path.join(export_dir, filename))
python
def export_icon(self, icon, size, color='black', scale='auto', filename=None, export_dir='exported'): """ Exports given icon with provided parameters. If the desired icon size is less than 150x150 pixels, we will first create a 150x150 pixels image and then scale it down, so that it's much less likely that the edges of the icon end up cropped. :param icon: valid icon name :param filename: name of the output file :param size: icon size in pixels :param color: color name or hex value :param scale: scaling factor between 0 and 1, or 'auto' for automatic scaling :param export_dir: path to export directory """ org_size = size size = max(150, size) image = Image.new("RGBA", (size, size), color=(0, 0, 0, 0)) draw = ImageDraw.Draw(image) if scale == 'auto': scale_factor = 1 else: scale_factor = float(scale) font = ImageFont.truetype(self.ttf_file, int(size * scale_factor)) width, height = draw.textsize(self.css_icons[icon], font=font) # If auto-scaling is enabled, we need to make sure the resulting # graphic fits inside the boundary. The values are rounded and may be # off by a pixel or two, so we may need to do a few iterations. # The use of a decrementing multiplication factor protects us from # getting into an infinite loop. if scale == 'auto': iteration = 0 factor = 1 while True: width, height = draw.textsize(self.css_icons[icon], font=font) # Check if the image fits dim = max(width, height) if dim > size: font = ImageFont.truetype(self.ttf_file, int(size * size/dim * factor)) else: break # Adjust the factor every two iterations iteration += 1 if iteration % 2 == 0: factor *= 0.99 draw.text((float(size - width) / 2, float(size - height) / 2), self.css_icons[icon], font=font, fill=color) # Get bounding box bbox = image.getbbox() # Create an alpha mask image_mask = Image.new("L", (size, size), 0) draw_mask = ImageDraw.Draw(image_mask) # Draw the icon on the mask draw_mask.text((float(size - width) / 2, float(size - height) / 2), self.css_icons[icon], font=font, fill=255) # Create a solid color image and apply the mask icon_image = Image.new("RGBA", (size, size), color) icon_image.putalpha(image_mask) if bbox: icon_image = icon_image.crop(bbox) border_w = int((size - (bbox[2] - bbox[0])) / 2) border_h = int((size - (bbox[3] - bbox[1])) / 2) # Create output image out_image = Image.new("RGBA", (size, size), (0, 0, 0, 0)) out_image.paste(icon_image, (border_w, border_h)) # If necessary, scale the image to the target size if org_size != size: out_image = out_image.resize((org_size, org_size), Image.ANTIALIAS) # Make sure export directory exists if not os.path.exists(export_dir): os.makedirs(export_dir) # Default filename if not filename: filename = icon + '.png' # Save file out_image.save(os.path.join(export_dir, filename))
[ "def", "export_icon", "(", "self", ",", "icon", ",", "size", ",", "color", "=", "'black'", ",", "scale", "=", "'auto'", ",", "filename", "=", "None", ",", "export_dir", "=", "'exported'", ")", ":", "org_size", "=", "size", "size", "=", "max", "(", "1...
Exports given icon with provided parameters. If the desired icon size is less than 150x150 pixels, we will first create a 150x150 pixels image and then scale it down, so that it's much less likely that the edges of the icon end up cropped. :param icon: valid icon name :param filename: name of the output file :param size: icon size in pixels :param color: color name or hex value :param scale: scaling factor between 0 and 1, or 'auto' for automatic scaling :param export_dir: path to export directory
[ "Exports", "given", "icon", "with", "provided", "parameters", "." ]
4851fe15c077402749f843d43fbc10d28f6c655d
https://github.com/Pythonity/icon-font-to-png/blob/4851fe15c077402749f843d43fbc10d28f6c655d/icon_font_to_png/icon_font.py#L78-L175
train
31,547
alaudet/hcsr04sensor
hcsr04sensor/sensor.py
basic_distance
def basic_distance(trig_pin, echo_pin, celsius=20): '''Return an unformatted distance in cm's as read directly from RPi.GPIO.''' speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15)) GPIO.setup(trig_pin, GPIO.OUT) GPIO.setup(echo_pin, GPIO.IN) GPIO.output(trig_pin, GPIO.LOW) time.sleep(0.1) GPIO.output(trig_pin, True) time.sleep(0.00001) GPIO.output(trig_pin, False) echo_status_counter = 1 while GPIO.input(echo_pin) == 0: if echo_status_counter < 1000: sonar_signal_off = time.time() echo_status_counter += 1 else: raise SystemError('Echo pulse was not received') while GPIO.input(echo_pin) == 1: sonar_signal_on = time.time() time_passed = sonar_signal_on - sonar_signal_off return time_passed * ((speed_of_sound * 100) / 2)
python
def basic_distance(trig_pin, echo_pin, celsius=20): '''Return an unformatted distance in cm's as read directly from RPi.GPIO.''' speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15)) GPIO.setup(trig_pin, GPIO.OUT) GPIO.setup(echo_pin, GPIO.IN) GPIO.output(trig_pin, GPIO.LOW) time.sleep(0.1) GPIO.output(trig_pin, True) time.sleep(0.00001) GPIO.output(trig_pin, False) echo_status_counter = 1 while GPIO.input(echo_pin) == 0: if echo_status_counter < 1000: sonar_signal_off = time.time() echo_status_counter += 1 else: raise SystemError('Echo pulse was not received') while GPIO.input(echo_pin) == 1: sonar_signal_on = time.time() time_passed = sonar_signal_on - sonar_signal_off return time_passed * ((speed_of_sound * 100) / 2)
[ "def", "basic_distance", "(", "trig_pin", ",", "echo_pin", ",", "celsius", "=", "20", ")", ":", "speed_of_sound", "=", "331.3", "*", "math", ".", "sqrt", "(", "1", "+", "(", "celsius", "/", "273.15", ")", ")", "GPIO", ".", "setup", "(", "trig_pin", "...
Return an unformatted distance in cm's as read directly from RPi.GPIO.
[ "Return", "an", "unformatted", "distance", "in", "cm", "s", "as", "read", "directly", "from", "RPi", ".", "GPIO", "." ]
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/hcsr04sensor/sensor.py#L127-L150
train
31,548
alaudet/hcsr04sensor
hcsr04sensor/sensor.py
Measurement.raw_distance
def raw_distance(self, sample_size=11, sample_wait=0.1): '''Return an error corrected unrounded distance, in cm, of an object adjusted for temperature in Celcius. The distance calculated is the median value of a sample of `sample_size` readings. Speed of readings is a result of two variables. The sample_size per reading and the sample_wait (interval between individual samples). Example: To use a sample size of 5 instead of 11 will increase the speed of your reading but could increase variance in readings; value = sensor.Measurement(trig_pin, echo_pin) r = value.raw_distance(sample_size=5) Adjusting the interval between individual samples can also increase the speed of the reading. Increasing the speed will also increase CPU usage. Setting it too low will cause errors. A default of sample_wait=0.1 is a good balance between speed and minimizing CPU usage. It is also a safe setting that should not cause errors. e.g. r = value.raw_distance(sample_wait=0.03) ''' if self.unit == 'imperial': self.temperature = (self.temperature - 32) * 0.5556 elif self.unit == 'metric': pass else: raise ValueError( 'Wrong Unit Type. Unit Must be imperial or metric') speed_of_sound = 331.3 * math.sqrt(1+(self.temperature / 273.15)) sample = [] # setup input/output pins GPIO.setwarnings(False) GPIO.setmode(self.gpio_mode) GPIO.setup(self.trig_pin, GPIO.OUT) GPIO.setup(self.echo_pin, GPIO.IN) for distance_reading in range(sample_size): GPIO.output(self.trig_pin, GPIO.LOW) time.sleep(sample_wait) GPIO.output(self.trig_pin, True) time.sleep(0.00001) GPIO.output(self.trig_pin, False) echo_status_counter = 1 while GPIO.input(self.echo_pin) == 0: if echo_status_counter < 1000: sonar_signal_off = time.time() echo_status_counter += 1 else: raise SystemError('Echo pulse was not received') while GPIO.input(self.echo_pin) == 1: sonar_signal_on = time.time() time_passed = sonar_signal_on - sonar_signal_off distance_cm = time_passed * ((speed_of_sound * 100) / 2) sample.append(distance_cm) sorted_sample = sorted(sample) # Only cleanup the pins used to prevent clobbering # any others in use by the program GPIO.cleanup((self.trig_pin, self.echo_pin)) return sorted_sample[sample_size // 2]
python
def raw_distance(self, sample_size=11, sample_wait=0.1): '''Return an error corrected unrounded distance, in cm, of an object adjusted for temperature in Celcius. The distance calculated is the median value of a sample of `sample_size` readings. Speed of readings is a result of two variables. The sample_size per reading and the sample_wait (interval between individual samples). Example: To use a sample size of 5 instead of 11 will increase the speed of your reading but could increase variance in readings; value = sensor.Measurement(trig_pin, echo_pin) r = value.raw_distance(sample_size=5) Adjusting the interval between individual samples can also increase the speed of the reading. Increasing the speed will also increase CPU usage. Setting it too low will cause errors. A default of sample_wait=0.1 is a good balance between speed and minimizing CPU usage. It is also a safe setting that should not cause errors. e.g. r = value.raw_distance(sample_wait=0.03) ''' if self.unit == 'imperial': self.temperature = (self.temperature - 32) * 0.5556 elif self.unit == 'metric': pass else: raise ValueError( 'Wrong Unit Type. Unit Must be imperial or metric') speed_of_sound = 331.3 * math.sqrt(1+(self.temperature / 273.15)) sample = [] # setup input/output pins GPIO.setwarnings(False) GPIO.setmode(self.gpio_mode) GPIO.setup(self.trig_pin, GPIO.OUT) GPIO.setup(self.echo_pin, GPIO.IN) for distance_reading in range(sample_size): GPIO.output(self.trig_pin, GPIO.LOW) time.sleep(sample_wait) GPIO.output(self.trig_pin, True) time.sleep(0.00001) GPIO.output(self.trig_pin, False) echo_status_counter = 1 while GPIO.input(self.echo_pin) == 0: if echo_status_counter < 1000: sonar_signal_off = time.time() echo_status_counter += 1 else: raise SystemError('Echo pulse was not received') while GPIO.input(self.echo_pin) == 1: sonar_signal_on = time.time() time_passed = sonar_signal_on - sonar_signal_off distance_cm = time_passed * ((speed_of_sound * 100) / 2) sample.append(distance_cm) sorted_sample = sorted(sample) # Only cleanup the pins used to prevent clobbering # any others in use by the program GPIO.cleanup((self.trig_pin, self.echo_pin)) return sorted_sample[sample_size // 2]
[ "def", "raw_distance", "(", "self", ",", "sample_size", "=", "11", ",", "sample_wait", "=", "0.1", ")", ":", "if", "self", ".", "unit", "==", "'imperial'", ":", "self", ".", "temperature", "=", "(", "self", ".", "temperature", "-", "32", ")", "*", "0...
Return an error corrected unrounded distance, in cm, of an object adjusted for temperature in Celcius. The distance calculated is the median value of a sample of `sample_size` readings. Speed of readings is a result of two variables. The sample_size per reading and the sample_wait (interval between individual samples). Example: To use a sample size of 5 instead of 11 will increase the speed of your reading but could increase variance in readings; value = sensor.Measurement(trig_pin, echo_pin) r = value.raw_distance(sample_size=5) Adjusting the interval between individual samples can also increase the speed of the reading. Increasing the speed will also increase CPU usage. Setting it too low will cause errors. A default of sample_wait=0.1 is a good balance between speed and minimizing CPU usage. It is also a safe setting that should not cause errors. e.g. r = value.raw_distance(sample_wait=0.03)
[ "Return", "an", "error", "corrected", "unrounded", "distance", "in", "cm", "of", "an", "object", "adjusted", "for", "temperature", "in", "Celcius", ".", "The", "distance", "calculated", "is", "the", "median", "value", "of", "a", "sample", "of", "sample_size", ...
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/hcsr04sensor/sensor.py#L36-L100
train
31,549
alaudet/hcsr04sensor
recipes/metric_depth.py
main
def main(): '''Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 # round_to = 1 hole_depth = 80 # centimeters # Create a distance reading with the hcsr04 sensor module value = sensor.Measurement(trig_pin, echo_pin ) raw_measurement = value.raw_distance() # To overide default values you can pass the following to value # value = sensor.Measurement(trig_pin, # echo_pin, # temperature=10, # round_to=2 # ) # Calculate the liquid depth, in centimeters, of a hole filled # with liquid liquid_depth = value.depth_metric(raw_measurement, hole_depth) print("Depth = {} centimeters".format(liquid_depth))
python
def main(): '''Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 # round_to = 1 hole_depth = 80 # centimeters # Create a distance reading with the hcsr04 sensor module value = sensor.Measurement(trig_pin, echo_pin ) raw_measurement = value.raw_distance() # To overide default values you can pass the following to value # value = sensor.Measurement(trig_pin, # echo_pin, # temperature=10, # round_to=2 # ) # Calculate the liquid depth, in centimeters, of a hole filled # with liquid liquid_depth = value.depth_metric(raw_measurement, hole_depth) print("Depth = {} centimeters".format(liquid_depth))
[ "def", "main", "(", ")", ":", "trig_pin", "=", "17", "echo_pin", "=", "27", "# Default values", "# unit = 'metric'", "# temperature = 20", "# round_to = 1", "hole_depth", "=", "80", "# centimeters", "# Create a distance reading with the hcsr04 sensor module", "value", "=", ...
Calculate the depth of a liquid in centimeters using a HCSR04 sensor and a Raspberry Pi
[ "Calculate", "the", "depth", "of", "a", "liquid", "in", "centimeters", "using", "a", "HCSR04", "sensor", "and", "a", "Raspberry", "Pi" ]
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/metric_depth.py#L6-L38
train
31,550
alaudet/hcsr04sensor
recipes/sample_speed.py
main
def main(): '''Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi. This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at quicker intervals.''' trig_pin = 17 echo_pin = 27 # Create a distance reading with the hcsr04 sensor module value = sensor.Measurement(trig_pin, echo_pin) # The default sample_size is 11 and sample_wait is 0.1 # Increase speed by lowering the sample_size and sample_wait # The effect of reducing sample_size is larger variance in readings # The effect of lowering sample_wait is higher cpu usage and sensor # instability if you push it with too fast of a value. # These two options have been added to allow you to tweak a # more optimal setting for your application. # e.g. raw_measurement = value.raw_distance(sample_size=5, sample_wait=0.03) # Calculate the distance in centimeters metric_distance = value.distance_metric(raw_measurement) print("The Distance = {} centimeters".format(metric_distance))
python
def main(): '''Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi. This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at quicker intervals.''' trig_pin = 17 echo_pin = 27 # Create a distance reading with the hcsr04 sensor module value = sensor.Measurement(trig_pin, echo_pin) # The default sample_size is 11 and sample_wait is 0.1 # Increase speed by lowering the sample_size and sample_wait # The effect of reducing sample_size is larger variance in readings # The effect of lowering sample_wait is higher cpu usage and sensor # instability if you push it with too fast of a value. # These two options have been added to allow you to tweak a # more optimal setting for your application. # e.g. raw_measurement = value.raw_distance(sample_size=5, sample_wait=0.03) # Calculate the distance in centimeters metric_distance = value.distance_metric(raw_measurement) print("The Distance = {} centimeters".format(metric_distance))
[ "def", "main", "(", ")", ":", "trig_pin", "=", "17", "echo_pin", "=", "27", "# Create a distance reading with the hcsr04 sensor module", "value", "=", "sensor", ".", "Measurement", "(", "trig_pin", ",", "echo_pin", ")", "# The default sample_size is 11 and sample_wait is...
Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi. This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at quicker intervals.
[ "Calculate", "the", "distance", "of", "an", "object", "in", "centimeters", "using", "a", "HCSR04", "sensor", "and", "a", "Raspberry", "Pi", ".", "This", "script", "allows", "for", "a", "quicker", "reading", "by", "decreasing", "the", "number", "of", "samples...
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/sample_speed.py#L6-L31
train
31,551
alaudet/hcsr04sensor
bin/hcsr04.py
main
def main(): '''Main function to run the sensor with passed arguments''' trig, echo, speed, samples = get_args() print('trig pin = gpio {}'.format(trig)) print('echo pin = gpio {}'.format(echo)) print('speed = {}'.format(speed)) print('samples = {}'.format(samples)) print('') value = sensor.Measurement(trig, echo) raw_distance = value.raw_distance(sample_size=samples, sample_wait=speed) imperial_distance = value.distance_imperial(raw_distance) metric_distance = value.distance_metric(raw_distance) print('The imperial distance is {} inches.'.format(imperial_distance)) print('The metric distance is {} centimetres.'.format(metric_distance))
python
def main(): '''Main function to run the sensor with passed arguments''' trig, echo, speed, samples = get_args() print('trig pin = gpio {}'.format(trig)) print('echo pin = gpio {}'.format(echo)) print('speed = {}'.format(speed)) print('samples = {}'.format(samples)) print('') value = sensor.Measurement(trig, echo) raw_distance = value.raw_distance(sample_size=samples, sample_wait=speed) imperial_distance = value.distance_imperial(raw_distance) metric_distance = value.distance_metric(raw_distance) print('The imperial distance is {} inches.'.format(imperial_distance)) print('The metric distance is {} centimetres.'.format(metric_distance))
[ "def", "main", "(", ")", ":", "trig", ",", "echo", ",", "speed", ",", "samples", "=", "get_args", "(", ")", "print", "(", "'trig pin = gpio {}'", ".", "format", "(", "trig", ")", ")", "print", "(", "'echo pin = gpio {}'", ".", "format", "(", "echo", ")...
Main function to run the sensor with passed arguments
[ "Main", "function", "to", "run", "the", "sensor", "with", "passed", "arguments" ]
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/bin/hcsr04.py#L59-L75
train
31,552
alaudet/hcsr04sensor
recipes/imperial_depth.py
main
def main(): '''Calculate the depth of a liquid in inches using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 hole_depth = 31.5 # inches # Default values # unit = 'metric' # temperature = 20 # round_to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp, unit and rounding) value = sensor.Measurement(trig_pin, echo_pin, temperature=68, unit='imperial', round_to=2 ) raw_measurement = value.raw_distance() # Calculate the liquid depth, in inches, of a hole filled # with liquid liquid_depth = value.depth_imperial(raw_measurement, hole_depth) print("Depth = {} inches".format(liquid_depth))
python
def main(): '''Calculate the depth of a liquid in inches using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 hole_depth = 31.5 # inches # Default values # unit = 'metric' # temperature = 20 # round_to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp, unit and rounding) value = sensor.Measurement(trig_pin, echo_pin, temperature=68, unit='imperial', round_to=2 ) raw_measurement = value.raw_distance() # Calculate the liquid depth, in inches, of a hole filled # with liquid liquid_depth = value.depth_imperial(raw_measurement, hole_depth) print("Depth = {} inches".format(liquid_depth))
[ "def", "main", "(", ")", ":", "trig_pin", "=", "17", "echo_pin", "=", "27", "hole_depth", "=", "31.5", "# inches", "# Default values", "# unit = 'metric'", "# temperature = 20", "# round_to = 1", "# Create a distance reading with the hcsr04 sensor module", "# and overide the ...
Calculate the depth of a liquid in inches using a HCSR04 sensor and a Raspberry Pi
[ "Calculate", "the", "depth", "of", "a", "liquid", "in", "inches", "using", "a", "HCSR04", "sensor", "and", "a", "Raspberry", "Pi" ]
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/imperial_depth.py#L6-L32
train
31,553
alaudet/hcsr04sensor
recipes/imperial_distance.py
main
def main(): '''Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 # round_to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp, unit and rounding) value = sensor.Measurement(trig_pin, echo_pin, temperature=68, unit='imperial', round_to=2 ) raw_measurement = value.raw_distance() # Calculate the distance in inches imperial_distance = value.distance_imperial(raw_measurement) print("The Distance = {} inches".format(imperial_distance))
python
def main(): '''Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi''' trig_pin = 17 echo_pin = 27 # Default values # unit = 'metric' # temperature = 20 # round_to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp, unit and rounding) value = sensor.Measurement(trig_pin, echo_pin, temperature=68, unit='imperial', round_to=2 ) raw_measurement = value.raw_distance() # Calculate the distance in inches imperial_distance = value.distance_imperial(raw_measurement) print("The Distance = {} inches".format(imperial_distance))
[ "def", "main", "(", ")", ":", "trig_pin", "=", "17", "echo_pin", "=", "27", "# Default values", "# unit = 'metric'", "# temperature = 20", "# round_to = 1", "# Create a distance reading with the hcsr04 sensor module", "# and overide the default values for temp, unit and rounding)", ...
Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi
[ "Calculate", "the", "distance", "of", "an", "object", "in", "inches", "using", "a", "HCSR04", "sensor", "and", "a", "Raspberry", "Pi" ]
74caf5c825e3f700c9daa9985542c061ae04b002
https://github.com/alaudet/hcsr04sensor/blob/74caf5c825e3f700c9daa9985542c061ae04b002/recipes/imperial_distance.py#L6-L31
train
31,554
vsergeev/python-periphery
periphery/led.py
LED.read
def read(self): """Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 8) except OSError as e: raise LEDError(e.errno, "Reading LED brightness: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror) return int(buf)
python
def read(self): """Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 8) except OSError as e: raise LEDError(e.errno, "Reading LED brightness: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror) return int(buf)
[ "def", "read", "(", "self", ")", ":", "# Read value", "try", ":", "buf", "=", "os", ".", "read", "(", "self", ".", "_fd", ",", "8", ")", "except", "OSError", "as", "e", ":", "raise", "LEDError", "(", "e", ".", "errno", ",", "\"Reading LED brightness:...
Read the brightness of the LED. Returns: int: Current brightness. Raises: LEDError: if an I/O or OS error occurs.
[ "Read", "the", "brightness", "of", "the", "LED", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L78-L100
train
31,555
vsergeev/python-periphery
periphery/led.py
LED.write
def write(self, brightness): """Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS error occurs. TypeError: if `brightness` type is not bool or int. """ if not isinstance(brightness, (bool, int)): raise TypeError("Invalid brightness type, should be bool or int.") if isinstance(brightness, bool): brightness = self._max_brightness if brightness else 0 else: if not 0 <= brightness <= self._max_brightness: raise ValueError("Invalid brightness value, should be between 0 and %d." % self._max_brightness) # Write value try: os.write(self._fd, b"%d\n" % brightness) except OSError as e: raise LEDError(e.errno, "Writing LED brightness: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror)
python
def write(self, brightness): """Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS error occurs. TypeError: if `brightness` type is not bool or int. """ if not isinstance(brightness, (bool, int)): raise TypeError("Invalid brightness type, should be bool or int.") if isinstance(brightness, bool): brightness = self._max_brightness if brightness else 0 else: if not 0 <= brightness <= self._max_brightness: raise ValueError("Invalid brightness value, should be between 0 and %d." % self._max_brightness) # Write value try: os.write(self._fd, b"%d\n" % brightness) except OSError as e: raise LEDError(e.errno, "Writing LED brightness: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise LEDError(e.errno, "Rewinding LED brightness: " + e.strerror)
[ "def", "write", "(", "self", ",", "brightness", ")", ":", "if", "not", "isinstance", "(", "brightness", ",", "(", "bool", ",", "int", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid brightness type, should be bool or int.\"", ")", "if", "isinstance", "(",...
Set the brightness of the LED to `brightness`. `brightness` can be a boolean for on/off, or integer value for a specific brightness. Args: brightness (bool, int): Brightness value to set. Raises: LEDError: if an I/O or OS error occurs. TypeError: if `brightness` type is not bool or int.
[ "Set", "the", "brightness", "of", "the", "LED", "to", "brightness", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L102-L135
train
31,556
vsergeev/python-periphery
periphery/led.py
LED.close
def close(self): """Close the sysfs LED. Raises: LEDError: if an I/O or OS error occurs. """ if self._fd is None: return try: os.close(self._fd) except OSError as e: raise LEDError(e.errno, "Closing LED: " + e.strerror) self._fd = None
python
def close(self): """Close the sysfs LED. Raises: LEDError: if an I/O or OS error occurs. """ if self._fd is None: return try: os.close(self._fd) except OSError as e: raise LEDError(e.errno, "Closing LED: " + e.strerror) self._fd = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_fd", "is", "None", ":", "return", "try", ":", "os", ".", "close", "(", "self", ".", "_fd", ")", "except", "OSError", "as", "e", ":", "raise", "LEDError", "(", "e", ".", "errno", ",", "...
Close the sysfs LED. Raises: LEDError: if an I/O or OS error occurs.
[ "Close", "the", "sysfs", "LED", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/led.py#L137-L152
train
31,557
vsergeev/python-periphery
periphery/i2c.py
I2C.transfer
def transfer(self, address, messages): """Transfer `messages` to the specified I2C `address`. Modifies the `messages` array with the results of any read transactions. Args: address (int): I2C address. messages (list): list of I2C.Message messages. Raises: I2CError: if an I/O or OS error occurs. TypeError: if `messages` type is not list. ValueError: if `messages` length is zero, or if message data is not valid bytes. """ if not isinstance(messages, list): raise TypeError("Invalid messages type, should be list of I2C.Message.") elif len(messages) == 0: raise ValueError("Invalid messages data, should be non-zero length.") # Convert I2C.Message messages to _CI2CMessage messages cmessages = (_CI2CMessage * len(messages))() for i in range(len(messages)): # Convert I2C.Message data to bytes if isinstance(messages[i].data, bytes): data = messages[i].data elif isinstance(messages[i].data, bytearray): data = bytes(messages[i].data) elif isinstance(messages[i].data, list): data = bytes(bytearray(messages[i].data)) cmessages[i].addr = address cmessages[i].flags = messages[i].flags | (I2C._I2C_M_RD if messages[i].read else 0) cmessages[i].len = len(data) cmessages[i].buf = ctypes.cast(ctypes.create_string_buffer(data, len(data)), ctypes.POINTER(ctypes.c_ubyte)) # Prepare transfer structure i2c_xfer = _CI2CIocTransfer() i2c_xfer.nmsgs = len(cmessages) i2c_xfer.msgs = cmessages # Transfer try: fcntl.ioctl(self._fd, I2C._I2C_IOC_RDWR, i2c_xfer, False) except IOError as e: raise I2CError(e.errno, "I2C transfer: " + e.strerror) # Update any read I2C.Message messages for i in range(len(messages)): if messages[i].read: data = [cmessages[i].buf[j] for j in range(cmessages[i].len)] # Convert read data to type used in I2C.Message messages if isinstance(messages[i].data, list): messages[i].data = data elif isinstance(messages[i].data, bytearray): messages[i].data = bytearray(data) elif isinstance(messages[i].data, bytes): messages[i].data = bytes(bytearray(data))
python
def transfer(self, address, messages): """Transfer `messages` to the specified I2C `address`. Modifies the `messages` array with the results of any read transactions. Args: address (int): I2C address. messages (list): list of I2C.Message messages. Raises: I2CError: if an I/O or OS error occurs. TypeError: if `messages` type is not list. ValueError: if `messages` length is zero, or if message data is not valid bytes. """ if not isinstance(messages, list): raise TypeError("Invalid messages type, should be list of I2C.Message.") elif len(messages) == 0: raise ValueError("Invalid messages data, should be non-zero length.") # Convert I2C.Message messages to _CI2CMessage messages cmessages = (_CI2CMessage * len(messages))() for i in range(len(messages)): # Convert I2C.Message data to bytes if isinstance(messages[i].data, bytes): data = messages[i].data elif isinstance(messages[i].data, bytearray): data = bytes(messages[i].data) elif isinstance(messages[i].data, list): data = bytes(bytearray(messages[i].data)) cmessages[i].addr = address cmessages[i].flags = messages[i].flags | (I2C._I2C_M_RD if messages[i].read else 0) cmessages[i].len = len(data) cmessages[i].buf = ctypes.cast(ctypes.create_string_buffer(data, len(data)), ctypes.POINTER(ctypes.c_ubyte)) # Prepare transfer structure i2c_xfer = _CI2CIocTransfer() i2c_xfer.nmsgs = len(cmessages) i2c_xfer.msgs = cmessages # Transfer try: fcntl.ioctl(self._fd, I2C._I2C_IOC_RDWR, i2c_xfer, False) except IOError as e: raise I2CError(e.errno, "I2C transfer: " + e.strerror) # Update any read I2C.Message messages for i in range(len(messages)): if messages[i].read: data = [cmessages[i].buf[j] for j in range(cmessages[i].len)] # Convert read data to type used in I2C.Message messages if isinstance(messages[i].data, list): messages[i].data = data elif isinstance(messages[i].data, bytearray): messages[i].data = bytearray(data) elif isinstance(messages[i].data, bytes): messages[i].data = bytes(bytearray(data))
[ "def", "transfer", "(", "self", ",", "address", ",", "messages", ")", ":", "if", "not", "isinstance", "(", "messages", ",", "list", ")", ":", "raise", "TypeError", "(", "\"Invalid messages type, should be list of I2C.Message.\"", ")", "elif", "len", "(", "messag...
Transfer `messages` to the specified I2C `address`. Modifies the `messages` array with the results of any read transactions. Args: address (int): I2C address. messages (list): list of I2C.Message messages. Raises: I2CError: if an I/O or OS error occurs. TypeError: if `messages` type is not list. ValueError: if `messages` length is zero, or if message data is not valid bytes.
[ "Transfer", "messages", "to", "the", "specified", "I2C", "address", ".", "Modifies", "the", "messages", "array", "with", "the", "results", "of", "any", "read", "transactions", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/i2c.py#L93-L149
train
31,558
vsergeev/python-periphery
periphery/serial.py
Serial.read
def read(self, length, timeout=None): """Read up to `length` number of bytes from the serial port with an optional timeout. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking read, or negative or None for a blocking read that will block until `length` number of bytes are read. Default is a blocking read. For a non-blocking or timeout-bound read, read() may return data whose length is less than or equal to the requested length. Args: length (int): length in bytes. timeout (int, float, None): timeout duration in seconds. Returns: bytes: data read. Raises: SerialError: if an I/O or OS error occurs. """ data = b"" # Read length bytes if timeout is None # Read up to length bytes if timeout is not None while True: if timeout is not None: # Select (rlist, _, _) = select.select([self._fd], [], [], timeout) # If timeout if self._fd not in rlist: break try: data += os.read(self._fd, length - len(data)) except OSError as e: raise SerialError(e.errno, "Reading serial port: " + e.strerror) if len(data) == length: break return data
python
def read(self, length, timeout=None): """Read up to `length` number of bytes from the serial port with an optional timeout. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking read, or negative or None for a blocking read that will block until `length` number of bytes are read. Default is a blocking read. For a non-blocking or timeout-bound read, read() may return data whose length is less than or equal to the requested length. Args: length (int): length in bytes. timeout (int, float, None): timeout duration in seconds. Returns: bytes: data read. Raises: SerialError: if an I/O or OS error occurs. """ data = b"" # Read length bytes if timeout is None # Read up to length bytes if timeout is not None while True: if timeout is not None: # Select (rlist, _, _) = select.select([self._fd], [], [], timeout) # If timeout if self._fd not in rlist: break try: data += os.read(self._fd, length - len(data)) except OSError as e: raise SerialError(e.errno, "Reading serial port: " + e.strerror) if len(data) == length: break return data
[ "def", "read", "(", "self", ",", "length", ",", "timeout", "=", "None", ")", ":", "data", "=", "b\"\"", "# Read length bytes if timeout is None", "# Read up to length bytes if timeout is not None", "while", "True", ":", "if", "timeout", "is", "not", "None", ":", "...
Read up to `length` number of bytes from the serial port with an optional timeout. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking read, or negative or None for a blocking read that will block until `length` number of bytes are read. Default is a blocking read. For a non-blocking or timeout-bound read, read() may return data whose length is less than or equal to the requested length. Args: length (int): length in bytes. timeout (int, float, None): timeout duration in seconds. Returns: bytes: data read. Raises: SerialError: if an I/O or OS error occurs.
[ "Read", "up", "to", "length", "number", "of", "bytes", "from", "the", "serial", "port", "with", "an", "optional", "timeout", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L172-L216
train
31,559
vsergeev/python-periphery
periphery/serial.py
Serial.write
def write(self, data): """Write `data` to the serial port and return the number of bytes written. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Returns: int: number of bytes written. Raises: SerialError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes. """ if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, should be bytes, bytearray, or list.") if isinstance(data, list): data = bytearray(data) try: return os.write(self._fd, data) except OSError as e: raise SerialError(e.errno, "Writing serial port: " + e.strerror)
python
def write(self, data): """Write `data` to the serial port and return the number of bytes written. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Returns: int: number of bytes written. Raises: SerialError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes. """ if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, should be bytes, bytearray, or list.") if isinstance(data, list): data = bytearray(data) try: return os.write(self._fd, data) except OSError as e: raise SerialError(e.errno, "Writing serial port: " + e.strerror)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid data type, should be bytes, bytearray, or list.\"", ")", "if", ...
Write `data` to the serial port and return the number of bytes written. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Returns: int: number of bytes written. Raises: SerialError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes.
[ "Write", "data", "to", "the", "serial", "port", "and", "return", "the", "number", "of", "bytes", "written", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L218-L243
train
31,560
vsergeev/python-periphery
periphery/serial.py
Serial.poll
def poll(self, timeout=None): """Poll for data available for reading from the serial port. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Default is a blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if data is available for reading from the serial port, ``False`` if not. """ p = select.poll() p.register(self._fd, select.POLLIN | select.POLLPRI) events = p.poll(int(timeout * 1000)) if len(events) > 0: return True return False
python
def poll(self, timeout=None): """Poll for data available for reading from the serial port. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Default is a blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if data is available for reading from the serial port, ``False`` if not. """ p = select.poll() p.register(self._fd, select.POLLIN | select.POLLPRI) events = p.poll(int(timeout * 1000)) if len(events) > 0: return True return False
[ "def", "poll", "(", "self", ",", "timeout", "=", "None", ")", ":", "p", "=", "select", ".", "poll", "(", ")", "p", ".", "register", "(", "self", ".", "_fd", ",", "select", ".", "POLLIN", "|", "select", ".", "POLLPRI", ")", "events", "=", "p", "...
Poll for data available for reading from the serial port. `timeout` can be positive for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Default is a blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if data is available for reading from the serial port, ``False`` if not.
[ "Poll", "for", "data", "available", "for", "reading", "from", "the", "serial", "port", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L245-L266
train
31,561
vsergeev/python-periphery
periphery/serial.py
Serial.flush
def flush(self): """Flush the write buffer of the serial port, blocking until all bytes are written. Raises: SerialError: if an I/O or OS error occurs. """ try: termios.tcdrain(self._fd) except termios.error as e: raise SerialError(e.errno, "Flushing serial port: " + e.strerror)
python
def flush(self): """Flush the write buffer of the serial port, blocking until all bytes are written. Raises: SerialError: if an I/O or OS error occurs. """ try: termios.tcdrain(self._fd) except termios.error as e: raise SerialError(e.errno, "Flushing serial port: " + e.strerror)
[ "def", "flush", "(", "self", ")", ":", "try", ":", "termios", ".", "tcdrain", "(", "self", ".", "_fd", ")", "except", "termios", ".", "error", "as", "e", ":", "raise", "SerialError", "(", "e", ".", "errno", ",", "\"Flushing serial port: \"", "+", "e", ...
Flush the write buffer of the serial port, blocking until all bytes are written. Raises: SerialError: if an I/O or OS error occurs.
[ "Flush", "the", "write", "buffer", "of", "the", "serial", "port", "blocking", "until", "all", "bytes", "are", "written", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L268-L279
train
31,562
vsergeev/python-periphery
periphery/serial.py
Serial.input_waiting
def input_waiting(self): """Query the number of bytes waiting to be read from the serial port. Returns: int: number of bytes waiting to be read. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCINQ, buf, True) except OSError as e: raise SerialError(e.errno, "Querying input waiting: " + e.strerror) return buf[0]
python
def input_waiting(self): """Query the number of bytes waiting to be read from the serial port. Returns: int: number of bytes waiting to be read. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCINQ, buf, True) except OSError as e: raise SerialError(e.errno, "Querying input waiting: " + e.strerror) return buf[0]
[ "def", "input_waiting", "(", "self", ")", ":", "# Get input waiting", "buf", "=", "array", ".", "array", "(", "'I'", ",", "[", "0", "]", ")", "try", ":", "fcntl", ".", "ioctl", "(", "self", ".", "_fd", ",", "termios", ".", "TIOCINQ", ",", "buf", ",...
Query the number of bytes waiting to be read from the serial port. Returns: int: number of bytes waiting to be read. Raises: SerialError: if an I/O or OS error occurs.
[ "Query", "the", "number", "of", "bytes", "waiting", "to", "be", "read", "from", "the", "serial", "port", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L281-L298
train
31,563
vsergeev/python-periphery
periphery/serial.py
Serial.output_waiting
def output_waiting(self): """Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCOUTQ, buf, True) except OSError as e: raise SerialError(e.errno, "Querying output waiting: " + e.strerror) return buf[0]
python
def output_waiting(self): """Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs. """ # Get input waiting buf = array.array('I', [0]) try: fcntl.ioctl(self._fd, termios.TIOCOUTQ, buf, True) except OSError as e: raise SerialError(e.errno, "Querying output waiting: " + e.strerror) return buf[0]
[ "def", "output_waiting", "(", "self", ")", ":", "# Get input waiting", "buf", "=", "array", ".", "array", "(", "'I'", ",", "[", "0", "]", ")", "try", ":", "fcntl", ".", "ioctl", "(", "self", ".", "_fd", ",", "termios", ".", "TIOCOUTQ", ",", "buf", ...
Query the number of bytes waiting to be written to the serial port. Returns: int: number of bytes waiting to be written. Raises: SerialError: if an I/O or OS error occurs.
[ "Query", "the", "number", "of", "bytes", "waiting", "to", "be", "written", "to", "the", "serial", "port", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/serial.py#L300-L317
train
31,564
vsergeev/python-periphery
periphery/gpio.py
GPIO.read
def read(self): """Read the state of the GPIO. Returns: bool: ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 2) except OSError as e: raise GPIOError(e.errno, "Reading GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) if buf[0] == b"0"[0]: return False elif buf[0] == b"1"[0]: return True raise GPIOError(None, "Unknown GPIO value: \"%s\"" % buf[0])
python
def read(self): """Read the state of the GPIO. Returns: bool: ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. """ # Read value try: buf = os.read(self._fd, 2) except OSError as e: raise GPIOError(e.errno, "Reading GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) if buf[0] == b"0"[0]: return False elif buf[0] == b"1"[0]: return True raise GPIOError(None, "Unknown GPIO value: \"%s\"" % buf[0])
[ "def", "read", "(", "self", ")", ":", "# Read value", "try", ":", "buf", "=", "os", ".", "read", "(", "self", ".", "_fd", ",", "2", ")", "except", "OSError", "as", "e", ":", "raise", "GPIOError", "(", "e", ".", "errno", ",", "\"Reading GPIO: \"", "...
Read the state of the GPIO. Returns: bool: ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs.
[ "Read", "the", "state", "of", "the", "GPIO", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L103-L130
train
31,565
vsergeev/python-periphery
periphery/gpio.py
GPIO.write
def write(self, value): """Set the state of the GPIO to `value`. Args: value (bool): ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `value` type is not bool. """ if not isinstance(value, bool): raise TypeError("Invalid value type, should be bool.") # Write value try: if value: os.write(self._fd, b"1\n") else: os.write(self._fd, b"0\n") except OSError as e: raise GPIOError(e.errno, "Writing GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror)
python
def write(self, value): """Set the state of the GPIO to `value`. Args: value (bool): ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `value` type is not bool. """ if not isinstance(value, bool): raise TypeError("Invalid value type, should be bool.") # Write value try: if value: os.write(self._fd, b"1\n") else: os.write(self._fd, b"0\n") except OSError as e: raise GPIOError(e.errno, "Writing GPIO: " + e.strerror) # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror)
[ "def", "write", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"Invalid value type, should be bool.\"", ")", "# Write value", "try", ":", "if", "value", ":", "os", ".", "wri...
Set the state of the GPIO to `value`. Args: value (bool): ``True`` for high state, ``False`` for low state. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `value` type is not bool.
[ "Set", "the", "state", "of", "the", "GPIO", "to", "value", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L132-L159
train
31,566
vsergeev/python-periphery
periphery/gpio.py
GPIO.poll
def poll(self, timeout=None): """Poll a GPIO for the edge event configured with the .edge property. `timeout` can be a positive number for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Defaults to blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if an edge event occurred, ``False`` on timeout. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `timeout` type is not None or int. """ if not isinstance(timeout, (int, float, type(None))): raise TypeError("Invalid timeout type, should be integer, float, or None.") # Setup epoll p = select.epoll() p.register(self._fd, select.EPOLLIN | select.EPOLLET | select.EPOLLPRI) # Poll twice, as first call returns with current state for _ in range(2): events = p.poll(timeout) # If GPIO edge interrupt occurred if events: # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) return True return False
python
def poll(self, timeout=None): """Poll a GPIO for the edge event configured with the .edge property. `timeout` can be a positive number for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Defaults to blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if an edge event occurred, ``False`` on timeout. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `timeout` type is not None or int. """ if not isinstance(timeout, (int, float, type(None))): raise TypeError("Invalid timeout type, should be integer, float, or None.") # Setup epoll p = select.epoll() p.register(self._fd, select.EPOLLIN | select.EPOLLET | select.EPOLLPRI) # Poll twice, as first call returns with current state for _ in range(2): events = p.poll(timeout) # If GPIO edge interrupt occurred if events: # Rewind try: os.lseek(self._fd, 0, os.SEEK_SET) except OSError as e: raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror) return True return False
[ "def", "poll", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "isinstance", "(", "timeout", ",", "(", "int", ",", "float", ",", "type", "(", "None", ")", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid timeout type, should be integ...
Poll a GPIO for the edge event configured with the .edge property. `timeout` can be a positive number for a timeout in seconds, 0 for a non-blocking poll, or negative or None for a blocking poll. Defaults to blocking poll. Args: timeout (int, float, None): timeout duration in seconds. Returns: bool: ``True`` if an edge event occurred, ``False`` on timeout. Raises: GPIOError: if an I/O or OS error occurs. TypeError: if `timeout` type is not None or int.
[ "Poll", "a", "GPIO", "for", "the", "edge", "event", "configured", "with", "the", ".", "edge", "property", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/gpio.py#L161-L200
train
31,567
vsergeev/python-periphery
periphery/mmio.py
MMIO.read32
def read32(self, offset): """Read 32-bits from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. Returns: int: 32-bit value read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") offset = self._adjust_offset(offset) self._validate_offset(offset, 4) return struct.unpack("=L", self.mapping[offset:offset + 4])[0]
python
def read32(self, offset): """Read 32-bits from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. Returns: int: 32-bit value read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") offset = self._adjust_offset(offset) self._validate_offset(offset, 4) return struct.unpack("=L", self.mapping[offset:offset + 4])[0]
[ "def", "read32", "(", "self", ",", "offset", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid offset type, should be integer.\"", ")", "offset", "=", "self", ".", "_adjus...
Read 32-bits from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. Returns: int: 32-bit value read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds.
[ "Read", "32", "-", "bits", "from", "the", "specified", "offset", "in", "bytes", "relative", "to", "the", "base", "physical", "address", "of", "the", "MMIO", "region", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L84-L104
train
31,568
vsergeev/python-periphery
periphery/mmio.py
MMIO.read
def read(self, offset, length): """Read a string of bytes from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. length (int): number of bytes to read. Returns: bytes: bytes read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") offset = self._adjust_offset(offset) self._validate_offset(offset, length) return bytes(self.mapping[offset:offset + length])
python
def read(self, offset, length): """Read a string of bytes from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. length (int): number of bytes to read. Returns: bytes: bytes read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") offset = self._adjust_offset(offset) self._validate_offset(offset, length) return bytes(self.mapping[offset:offset + length])
[ "def", "read", "(", "self", ",", "offset", ",", "length", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid offset type, should be integer.\"", ")", "offset", "=", "self",...
Read a string of bytes from the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. length (int): number of bytes to read. Returns: bytes: bytes read. Raises: TypeError: if `offset` type is invalid. ValueError: if `offset` is out of bounds.
[ "Read", "a", "string", "of", "bytes", "from", "the", "specified", "offset", "in", "bytes", "relative", "to", "the", "base", "physical", "address", "of", "the", "MMIO", "region", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L150-L171
train
31,569
vsergeev/python-periphery
periphery/mmio.py
MMIO.write8
def write8(self, offset, value): """Write 8-bits to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. value (int, long): 8-bit value to write. Raises: TypeError: if `offset` or `value` type are invalid. ValueError: if `offset` or `value` are out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") if not isinstance(value, (int, long)): raise TypeError("Invalid value type, should be integer.") if value < 0 or value > 0xff: raise ValueError("Value out of bounds.") offset = self._adjust_offset(offset) self._validate_offset(offset, 1) self.mapping[offset:offset + 1] = struct.pack("B", value)
python
def write8(self, offset, value): """Write 8-bits to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. value (int, long): 8-bit value to write. Raises: TypeError: if `offset` or `value` type are invalid. ValueError: if `offset` or `value` are out of bounds. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") if not isinstance(value, (int, long)): raise TypeError("Invalid value type, should be integer.") if value < 0 or value > 0xff: raise ValueError("Value out of bounds.") offset = self._adjust_offset(offset) self._validate_offset(offset, 1) self.mapping[offset:offset + 1] = struct.pack("B", value)
[ "def", "write8", "(", "self", ",", "offset", ",", "value", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid offset type, should be integer.\"", ")", "if", "not", "isinsta...
Write 8-bits to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. value (int, long): 8-bit value to write. Raises: TypeError: if `offset` or `value` type are invalid. ValueError: if `offset` or `value` are out of bounds.
[ "Write", "8", "-", "bits", "to", "the", "specified", "offset", "in", "bytes", "relative", "to", "the", "base", "physical", "address", "of", "the", "MMIO", "region", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L221-L243
train
31,570
vsergeev/python-periphery
periphery/mmio.py
MMIO.write
def write(self, offset, data): """Write a string of bytes to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Raises: TypeError: if `offset` or `data` type are invalid. ValueError: if `offset` is out of bounds, or if data is not valid bytes. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, expected bytes, bytearray, or list.") offset = self._adjust_offset(offset) self._validate_offset(offset, len(data)) data = bytes(bytearray(data)) self.mapping[offset:offset + len(data)] = data
python
def write(self, offset, data): """Write a string of bytes to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Raises: TypeError: if `offset` or `data` type are invalid. ValueError: if `offset` is out of bounds, or if data is not valid bytes. """ if not isinstance(offset, (int, long)): raise TypeError("Invalid offset type, should be integer.") if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, expected bytes, bytearray, or list.") offset = self._adjust_offset(offset) self._validate_offset(offset, len(data)) data = bytes(bytearray(data)) self.mapping[offset:offset + len(data)] = data
[ "def", "write", "(", "self", ",", "offset", ",", "data", ")", ":", "if", "not", "isinstance", "(", "offset", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid offset type, should be integer.\"", ")", "if", "not", "isinstanc...
Write a string of bytes to the specified `offset` in bytes, relative to the base physical address of the MMIO region. Args: offset (int, long): offset from base physical address, in bytes. data (bytes, bytearray, list): a byte array or list of 8-bit integers to write. Raises: TypeError: if `offset` or `data` type are invalid. ValueError: if `offset` is out of bounds, or if data is not valid bytes.
[ "Write", "a", "string", "of", "bytes", "to", "the", "specified", "offset", "in", "bytes", "relative", "to", "the", "base", "physical", "address", "of", "the", "MMIO", "region", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L245-L268
train
31,571
vsergeev/python-periphery
periphery/mmio.py
MMIO.close
def close(self): """Unmap the MMIO object's mapped physical memory.""" if self.mapping is None: return self.mapping.close() self.mapping = None self._fd = None
python
def close(self): """Unmap the MMIO object's mapped physical memory.""" if self.mapping is None: return self.mapping.close() self.mapping = None self._fd = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "mapping", "is", "None", ":", "return", "self", ".", "mapping", ".", "close", "(", ")", "self", ".", "mapping", "=", "None", "self", ".", "_fd", "=", "None" ]
Unmap the MMIO object's mapped physical memory.
[ "Unmap", "the", "MMIO", "object", "s", "mapped", "physical", "memory", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L270-L278
train
31,572
vsergeev/python-periphery
periphery/mmio.py
MMIO.pointer
def pointer(self): """Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p """ return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
python
def pointer(self): """Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p """ return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
[ "def", "pointer", "(", "self", ")", ":", "return", "ctypes", ".", "cast", "(", "ctypes", ".", "pointer", "(", "ctypes", ".", "c_uint8", ".", "from_buffer", "(", "self", ".", "mapping", ",", "0", ")", ")", ",", "ctypes", ".", "c_void_p", ")" ]
Get a ctypes void pointer to the memory mapped region. :type: ctypes.c_void_p
[ "Get", "a", "ctypes", "void", "pointer", "to", "the", "memory", "mapped", "region", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/mmio.py#L299-L304
train
31,573
vsergeev/python-periphery
periphery/spi.py
SPI.transfer
def transfer(self, data): """Shift out `data` and return shifted in data. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out. Returns: bytes, bytearray, list: data shifted in. Raises: SPIError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes. """ if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, should be bytes, bytearray, or list.") # Create mutable array try: buf = array.array('B', data) except OverflowError: raise ValueError("Invalid data bytes.") buf_addr, buf_len = buf.buffer_info() # Prepare transfer structure spi_xfer = _CSpiIocTransfer() spi_xfer.tx_buf = buf_addr spi_xfer.rx_buf = buf_addr spi_xfer.len = buf_len # Transfer try: fcntl.ioctl(self._fd, SPI._SPI_IOC_MESSAGE_1, spi_xfer) except OSError as e: raise SPIError(e.errno, "SPI transfer: " + e.strerror) # Return shifted out data with the same type as shifted in data if isinstance(data, bytes): return bytes(bytearray(buf)) elif isinstance(data, bytearray): return bytearray(buf) elif isinstance(data, list): return buf.tolist()
python
def transfer(self, data): """Shift out `data` and return shifted in data. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out. Returns: bytes, bytearray, list: data shifted in. Raises: SPIError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes. """ if not isinstance(data, (bytes, bytearray, list)): raise TypeError("Invalid data type, should be bytes, bytearray, or list.") # Create mutable array try: buf = array.array('B', data) except OverflowError: raise ValueError("Invalid data bytes.") buf_addr, buf_len = buf.buffer_info() # Prepare transfer structure spi_xfer = _CSpiIocTransfer() spi_xfer.tx_buf = buf_addr spi_xfer.rx_buf = buf_addr spi_xfer.len = buf_len # Transfer try: fcntl.ioctl(self._fd, SPI._SPI_IOC_MESSAGE_1, spi_xfer) except OSError as e: raise SPIError(e.errno, "SPI transfer: " + e.strerror) # Return shifted out data with the same type as shifted in data if isinstance(data, bytes): return bytes(bytearray(buf)) elif isinstance(data, bytearray): return bytearray(buf) elif isinstance(data, list): return buf.tolist()
[ "def", "transfer", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid data type, should be bytes, bytearray, or list.\"", ")", "# Cr...
Shift out `data` and return shifted in data. Args: data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out. Returns: bytes, bytearray, list: data shifted in. Raises: SPIError: if an I/O or OS error occurs. TypeError: if `data` type is invalid. ValueError: if data is not valid bytes.
[ "Shift", "out", "data", "and", "return", "shifted", "in", "data", "." ]
ff4d535691a1747a76962a3d077d96d224308611
https://github.com/vsergeev/python-periphery/blob/ff4d535691a1747a76962a3d077d96d224308611/periphery/spi.py#L131-L175
train
31,574
pinax/pinax-referrals
pinax/referrals/utils.py
ensure_session_key
def ensure_session_key(request): """ Given a request return a session key that will be used. There may already be a session key associated, but if there is not, we force the session to create itself and persist between requests for the client behind the given request. """ key = request.session.session_key if key is None: # @@@ Django forces us to handle session key collision amongst # multiple processes (not handled) request.session.save() # force session to persist for client request.session.modified = True key = request.session.session_key return key
python
def ensure_session_key(request): """ Given a request return a session key that will be used. There may already be a session key associated, but if there is not, we force the session to create itself and persist between requests for the client behind the given request. """ key = request.session.session_key if key is None: # @@@ Django forces us to handle session key collision amongst # multiple processes (not handled) request.session.save() # force session to persist for client request.session.modified = True key = request.session.session_key return key
[ "def", "ensure_session_key", "(", "request", ")", ":", "key", "=", "request", ".", "session", ".", "session_key", "if", "key", "is", "None", ":", "# @@@ Django forces us to handle session key collision amongst", "# multiple processes (not handled)", "request", ".", "sessi...
Given a request return a session key that will be used. There may already be a session key associated, but if there is not, we force the session to create itself and persist between requests for the client behind the given request.
[ "Given", "a", "request", "return", "a", "session", "key", "that", "will", "be", "used", ".", "There", "may", "already", "be", "a", "session", "key", "associated", "but", "if", "there", "is", "not", "we", "force", "the", "session", "to", "create", "itself...
4e192afb31287c6ba426badae513555ff04a945d
https://github.com/pinax/pinax-referrals/blob/4e192afb31287c6ba426badae513555ff04a945d/pinax/referrals/utils.py#L6-L21
train
31,575
carsonyl/pypac
pypac/resolver.py
add_proxy_auth
def add_proxy_auth(possible_proxy_url, proxy_auth): """ Add a username and password to a proxy URL, if the input value is a proxy URL. :param str possible_proxy_url: Proxy URL or ``DIRECT``. :param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info. :returns: Proxy URL with auth info added, or ``DIRECT``. :rtype: str """ if possible_proxy_url == 'DIRECT': return possible_proxy_url parsed = urlparse(possible_proxy_url) return '{0}://{1}:{2}@{3}'.format(parsed.scheme, proxy_auth.username, proxy_auth.password, parsed.netloc)
python
def add_proxy_auth(possible_proxy_url, proxy_auth): """ Add a username and password to a proxy URL, if the input value is a proxy URL. :param str possible_proxy_url: Proxy URL or ``DIRECT``. :param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info. :returns: Proxy URL with auth info added, or ``DIRECT``. :rtype: str """ if possible_proxy_url == 'DIRECT': return possible_proxy_url parsed = urlparse(possible_proxy_url) return '{0}://{1}:{2}@{3}'.format(parsed.scheme, proxy_auth.username, proxy_auth.password, parsed.netloc)
[ "def", "add_proxy_auth", "(", "possible_proxy_url", ",", "proxy_auth", ")", ":", "if", "possible_proxy_url", "==", "'DIRECT'", ":", "return", "possible_proxy_url", "parsed", "=", "urlparse", "(", "possible_proxy_url", ")", "return", "'{0}://{1}:{2}@{3}'", ".", "format...
Add a username and password to a proxy URL, if the input value is a proxy URL. :param str possible_proxy_url: Proxy URL or ``DIRECT``. :param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info. :returns: Proxy URL with auth info added, or ``DIRECT``. :rtype: str
[ "Add", "a", "username", "and", "password", "to", "a", "proxy", "URL", "if", "the", "input", "value", "is", "a", "proxy", "URL", "." ]
9e14a9e84a1ec5513a4fa819573073942fed0980
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L112-L124
train
31,576
carsonyl/pypac
pypac/resolver.py
ProxyResolver.get_proxies
def get_proxies(self, url): """ Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means to abort the request. :rtype: list[str] """ hostname = urlparse(url).hostname if hostname is None: # URL has no hostname, and PAC functions don't expect to receive nulls. hostname = "" value_from_js_func = self.pac.find_proxy_for_url(url, hostname) if value_from_js_func in self._cache: return self._cache[value_from_js_func] config_values = parse_pac_value(self.pac.find_proxy_for_url(url, hostname), self.socks_scheme) if self._proxy_auth: config_values = [add_proxy_auth(value, self._proxy_auth) for value in config_values] self._cache[value_from_js_func] = config_values return config_values
python
def get_proxies(self, url): """ Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means to abort the request. :rtype: list[str] """ hostname = urlparse(url).hostname if hostname is None: # URL has no hostname, and PAC functions don't expect to receive nulls. hostname = "" value_from_js_func = self.pac.find_proxy_for_url(url, hostname) if value_from_js_func in self._cache: return self._cache[value_from_js_func] config_values = parse_pac_value(self.pac.find_proxy_for_url(url, hostname), self.socks_scheme) if self._proxy_auth: config_values = [add_proxy_auth(value, self._proxy_auth) for value in config_values] self._cache[value_from_js_func] = config_values return config_values
[ "def", "get_proxies", "(", "self", ",", "url", ")", ":", "hostname", "=", "urlparse", "(", "url", ")", ".", "hostname", "if", "hostname", "is", "None", ":", "# URL has no hostname, and PAC functions don't expect to receive nulls.", "hostname", "=", "\"\"", "value_fr...
Get the proxies that are applicable to a given URL, according to the PAC file. :param str url: The URL for which to find appropriate proxies. :return: All the proxies that apply to the given URL. Can be empty, which means to abort the request. :rtype: list[str]
[ "Get", "the", "proxies", "that", "are", "applicable", "to", "a", "given", "URL", "according", "to", "the", "PAC", "file", "." ]
9e14a9e84a1ec5513a4fa819573073942fed0980
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L42-L66
train
31,577
carsonyl/pypac
pypac/resolver.py
ProxyResolver.get_proxy
def get_proxy(self, url): """ Get a proxy to use for a given URL, excluding any banned ones. :param str url: The URL for which to find an appropriate proxy. :return: A proxy to use for the URL, or the string 'DIRECT', which means a proxy is not to be used. Can be ``None``, which means to not attempt the request. :rtype: str|None """ proxies = self.get_proxies(url) for proxy in proxies: if proxy == 'DIRECT' or proxy not in self._offline_proxies: return proxy
python
def get_proxy(self, url): """ Get a proxy to use for a given URL, excluding any banned ones. :param str url: The URL for which to find an appropriate proxy. :return: A proxy to use for the URL, or the string 'DIRECT', which means a proxy is not to be used. Can be ``None``, which means to not attempt the request. :rtype: str|None """ proxies = self.get_proxies(url) for proxy in proxies: if proxy == 'DIRECT' or proxy not in self._offline_proxies: return proxy
[ "def", "get_proxy", "(", "self", ",", "url", ")", ":", "proxies", "=", "self", ".", "get_proxies", "(", "url", ")", "for", "proxy", "in", "proxies", ":", "if", "proxy", "==", "'DIRECT'", "or", "proxy", "not", "in", "self", ".", "_offline_proxies", ":",...
Get a proxy to use for a given URL, excluding any banned ones. :param str url: The URL for which to find an appropriate proxy. :return: A proxy to use for the URL, or the string 'DIRECT', which means a proxy is not to be used. Can be ``None``, which means to not attempt the request. :rtype: str|None
[ "Get", "a", "proxy", "to", "use", "for", "a", "given", "URL", "excluding", "any", "banned", "ones", "." ]
9e14a9e84a1ec5513a4fa819573073942fed0980
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L68-L81
train
31,578
carsonyl/pypac
pypac/resolver.py
ProxyResolver.get_proxy_for_requests
def get_proxy_for_requests(self, url): """ Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter. :rtype: dict :raises ProxyConfigExhaustedError: If no proxy is configured or available, and 'DIRECT' is not configured as a fallback. """ proxy = self.get_proxy(url) if not proxy: raise ProxyConfigExhaustedError(url) return proxy_parameter_for_requests(proxy)
python
def get_proxy_for_requests(self, url): """ Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter. :rtype: dict :raises ProxyConfigExhaustedError: If no proxy is configured or available, and 'DIRECT' is not configured as a fallback. """ proxy = self.get_proxy(url) if not proxy: raise ProxyConfigExhaustedError(url) return proxy_parameter_for_requests(proxy)
[ "def", "get_proxy_for_requests", "(", "self", ",", "url", ")", ":", "proxy", "=", "self", ".", "get_proxy", "(", "url", ")", "if", "not", "proxy", ":", "raise", "ProxyConfigExhaustedError", "(", "url", ")", "return", "proxy_parameter_for_requests", "(", "proxy...
Get proxy configuration for a given URL, in a form ready to use with the Requests library. :param str url: The URL for which to obtain proxy configuration. :returns: Proxy configuration in a form recognized by Requests, for use with the ``proxies`` parameter. :rtype: dict :raises ProxyConfigExhaustedError: If no proxy is configured or available, and 'DIRECT' is not configured as a fallback.
[ "Get", "proxy", "configuration", "for", "a", "given", "URL", "in", "a", "form", "ready", "to", "use", "with", "the", "Requests", "library", "." ]
9e14a9e84a1ec5513a4fa819573073942fed0980
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/resolver.py#L83-L96
train
31,579
carsonyl/pypac
pypac/parser_functions.py
isInNet
def isInNet(host, pattern, mask): """ Pattern and mask specification is done the same way as for SOCKS configuration. :param str host: a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. :param str pattern: an IP address pattern in the dot-separated format :param str mask: mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. :returns: True iff the IP address of the host matches the specified IP address pattern. :rtype: bool """ host_ip = host if is_ipv4_address(host) else dnsResolve(host) if not host_ip or not is_ipv4_address(pattern) or not is_ipv4_address(mask): return False return _address_in_network(host_ip, pattern, mask)
python
def isInNet(host, pattern, mask): """ Pattern and mask specification is done the same way as for SOCKS configuration. :param str host: a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. :param str pattern: an IP address pattern in the dot-separated format :param str mask: mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. :returns: True iff the IP address of the host matches the specified IP address pattern. :rtype: bool """ host_ip = host if is_ipv4_address(host) else dnsResolve(host) if not host_ip or not is_ipv4_address(pattern) or not is_ipv4_address(mask): return False return _address_in_network(host_ip, pattern, mask)
[ "def", "isInNet", "(", "host", ",", "pattern", ",", "mask", ")", ":", "host_ip", "=", "host", "if", "is_ipv4_address", "(", "host", ")", "else", "dnsResolve", "(", "host", ")", "if", "not", "host_ip", "or", "not", "is_ipv4_address", "(", "pattern", ")", ...
Pattern and mask specification is done the same way as for SOCKS configuration. :param str host: a DNS hostname, or IP address. If a hostname is passed, it will be resolved into an IP address by this function. :param str pattern: an IP address pattern in the dot-separated format :param str mask: mask for the IP address pattern informing which parts of the IP address should be matched against. 0 means ignore, 255 means match. :returns: True iff the IP address of the host matches the specified IP address pattern. :rtype: bool
[ "Pattern", "and", "mask", "specification", "is", "done", "the", "same", "way", "as", "for", "SOCKS", "configuration", "." ]
9e14a9e84a1ec5513a4fa819573073942fed0980
https://github.com/carsonyl/pypac/blob/9e14a9e84a1ec5513a4fa819573073942fed0980/pypac/parser_functions.py#L51-L66
train
31,580
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS._get_ssh_config
def _get_ssh_config(config_path='~/.ssh/config'): """Extract the configuration located at ``config_path``. Returns: paramiko.SSHConfig: the configuration instance. """ ssh_config = paramiko.SSHConfig() try: with open(os.path.realpath(os.path.expanduser(config_path))) as f: ssh_config.parse(f) except IOError: pass return ssh_config
python
def _get_ssh_config(config_path='~/.ssh/config'): """Extract the configuration located at ``config_path``. Returns: paramiko.SSHConfig: the configuration instance. """ ssh_config = paramiko.SSHConfig() try: with open(os.path.realpath(os.path.expanduser(config_path))) as f: ssh_config.parse(f) except IOError: pass return ssh_config
[ "def", "_get_ssh_config", "(", "config_path", "=", "'~/.ssh/config'", ")", ":", "ssh_config", "=", "paramiko", ".", "SSHConfig", "(", ")", "try", ":", "with", "open", "(", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "("...
Extract the configuration located at ``config_path``. Returns: paramiko.SSHConfig: the configuration instance.
[ "Extract", "the", "configuration", "located", "at", "config_path", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L67-L79
train
31,581
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS.openbin
def openbin(self, path, mode='r', buffering=-1, **options): # noqa: D102 """Open a binary file-like object. Arguments: path (str): A path on the filesystem. mode (str): Mode to open the file (must be a valid, non-text mode). Since this method only opens binary files, the ``b`` in the mode is implied. buffering (int): the buffering policy (-1 to use default buffering, 0 to disable completely, 1 to enable line based buffering, or any larger positive integer for a custom buffer size). Keyword Arguments: pipelined (bool): Set the transfer in pipelined mode (should improve transfer speed). Defaults to ``True``. Raises: fs.errors.FileExpected: if the path if not a file. fs.errors.FileExists: if the file already exists and *exclusive mode* is specified (``x`` in the mode). fs.errors.ResourceNotFound: if the path does not exist. Returns: io.IOBase: a file handle. """ self.check() _path = self.validatepath(path) _mode = Mode(mode) _mode.validate_bin() with self._lock: if _mode.exclusive: if self.exists(_path): raise errors.FileExists(path) else: _mode = Mode(''.join(set(mode.replace('x', 'w')))) elif _mode.reading and not _mode.create and not self.exists(_path): raise errors.ResourceNotFound(path) elif self.isdir(_path): raise errors.FileExpected(path) with convert_sshfs_errors('openbin', path): _sftp = self._client.open_sftp() handle = _sftp.open( _path, mode=_mode.to_platform_bin(), bufsize=buffering ) handle.set_pipelined(options.get("pipelined", True)) return SSHFile(handle)
python
def openbin(self, path, mode='r', buffering=-1, **options): # noqa: D102 """Open a binary file-like object. Arguments: path (str): A path on the filesystem. mode (str): Mode to open the file (must be a valid, non-text mode). Since this method only opens binary files, the ``b`` in the mode is implied. buffering (int): the buffering policy (-1 to use default buffering, 0 to disable completely, 1 to enable line based buffering, or any larger positive integer for a custom buffer size). Keyword Arguments: pipelined (bool): Set the transfer in pipelined mode (should improve transfer speed). Defaults to ``True``. Raises: fs.errors.FileExpected: if the path if not a file. fs.errors.FileExists: if the file already exists and *exclusive mode* is specified (``x`` in the mode). fs.errors.ResourceNotFound: if the path does not exist. Returns: io.IOBase: a file handle. """ self.check() _path = self.validatepath(path) _mode = Mode(mode) _mode.validate_bin() with self._lock: if _mode.exclusive: if self.exists(_path): raise errors.FileExists(path) else: _mode = Mode(''.join(set(mode.replace('x', 'w')))) elif _mode.reading and not _mode.create and not self.exists(_path): raise errors.ResourceNotFound(path) elif self.isdir(_path): raise errors.FileExpected(path) with convert_sshfs_errors('openbin', path): _sftp = self._client.open_sftp() handle = _sftp.open( _path, mode=_mode.to_platform_bin(), bufsize=buffering ) handle.set_pipelined(options.get("pipelined", True)) return SSHFile(handle)
[ "def", "openbin", "(", "self", ",", "path", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ",", "*", "*", "options", ")", ":", "# noqa: D102", "self", ".", "check", "(", ")", "_path", "=", "self", ".", "validatepath", "(", "path", ")", ...
Open a binary file-like object. Arguments: path (str): A path on the filesystem. mode (str): Mode to open the file (must be a valid, non-text mode). Since this method only opens binary files, the ``b`` in the mode is implied. buffering (int): the buffering policy (-1 to use default buffering, 0 to disable completely, 1 to enable line based buffering, or any larger positive integer for a custom buffer size). Keyword Arguments: pipelined (bool): Set the transfer in pipelined mode (should improve transfer speed). Defaults to ``True``. Raises: fs.errors.FileExpected: if the path if not a file. fs.errors.FileExists: if the file already exists and *exclusive mode* is specified (``x`` in the mode). fs.errors.ResourceNotFound: if the path does not exist. Returns: io.IOBase: a file handle.
[ "Open", "a", "binary", "file", "-", "like", "object", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L177-L225
train
31,582
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS.platform
def platform(self): """The platform the server is running on. Returns: str: the platform of the remote server, as in `sys.platform`. """ uname_sys = self._exec_command("uname -s") sysinfo = self._exec_command("sysinfo") if uname_sys is not None: if uname_sys == b"FreeBSD": return "freebsd" elif uname_sys == b"Darwin": return "darwin" elif uname_sys == b"Linux": return "linux" elif uname_sys.startswith(b"CYGWIN"): return "cygwin" elif sysinfo is not None and sysinfo: return "win32" return "unknown"
python
def platform(self): """The platform the server is running on. Returns: str: the platform of the remote server, as in `sys.platform`. """ uname_sys = self._exec_command("uname -s") sysinfo = self._exec_command("sysinfo") if uname_sys is not None: if uname_sys == b"FreeBSD": return "freebsd" elif uname_sys == b"Darwin": return "darwin" elif uname_sys == b"Linux": return "linux" elif uname_sys.startswith(b"CYGWIN"): return "cygwin" elif sysinfo is not None and sysinfo: return "win32" return "unknown"
[ "def", "platform", "(", "self", ")", ":", "uname_sys", "=", "self", ".", "_exec_command", "(", "\"uname -s\"", ")", "sysinfo", "=", "self", ".", "_exec_command", "(", "\"sysinfo\"", ")", "if", "uname_sys", "is", "not", "None", ":", "if", "uname_sys", "==",...
The platform the server is running on. Returns: str: the platform of the remote server, as in `sys.platform`.
[ "The", "platform", "the", "server", "is", "running", "on", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L277-L296
train
31,583
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS.locale
def locale(self): """The locale the server is running on. Returns: str: the locale of the remote server if detected, or `None`. """ if self.platform in ("linux", "darwin", "freebsd"): locale = self._exec_command('echo $LANG') if locale is not None: return locale.split(b'.')[-1].decode('ascii').lower() return None
python
def locale(self): """The locale the server is running on. Returns: str: the locale of the remote server if detected, or `None`. """ if self.platform in ("linux", "darwin", "freebsd"): locale = self._exec_command('echo $LANG') if locale is not None: return locale.split(b'.')[-1].decode('ascii').lower() return None
[ "def", "locale", "(", "self", ")", ":", "if", "self", ".", "platform", "in", "(", "\"linux\"", ",", "\"darwin\"", ",", "\"freebsd\"", ")", ":", "locale", "=", "self", ".", "_exec_command", "(", "'echo $LANG'", ")", "if", "locale", "is", "not", "None", ...
The locale the server is running on. Returns: str: the locale of the remote server if detected, or `None`.
[ "The", "locale", "the", "server", "is", "running", "on", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L299-L309
train
31,584
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS._exec_command
def _exec_command(self, cmd): """Run a command on the remote SSH server. Returns: bytes: the output of the command, if it didn't fail None: if the error pipe of the command was not empty """ _, out, err = self._client.exec_command(cmd, timeout=self._timeout) return out.read().strip() if not err.read().strip() else None
python
def _exec_command(self, cmd): """Run a command on the remote SSH server. Returns: bytes: the output of the command, if it didn't fail None: if the error pipe of the command was not empty """ _, out, err = self._client.exec_command(cmd, timeout=self._timeout) return out.read().strip() if not err.read().strip() else None
[ "def", "_exec_command", "(", "self", ",", "cmd", ")", ":", "_", ",", "out", ",", "err", "=", "self", ".", "_client", ".", "exec_command", "(", "cmd", ",", "timeout", "=", "self", ".", "_timeout", ")", "return", "out", ".", "read", "(", ")", ".", ...
Run a command on the remote SSH server. Returns: bytes: the output of the command, if it didn't fail None: if the error pipe of the command was not empty
[ "Run", "a", "command", "on", "the", "remote", "SSH", "server", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L311-L319
train
31,585
althonos/fs.sshfs
fs/sshfs/sshfs.py
SSHFS._make_info
def _make_info(self, name, stat_result, namespaces): """Create an `Info` object from a stat result. """ info = { 'basic': { 'name': name, 'is_dir': stat.S_ISDIR(stat_result.st_mode) } } if 'details' in namespaces: info['details'] = self._make_details_from_stat(stat_result) if 'stat' in namespaces: info['stat'] = { k: getattr(stat_result, k) for k in dir(stat_result) if k.startswith('st_') } if 'access' in namespaces: info['access'] = self._make_access_from_stat(stat_result) return Info(info)
python
def _make_info(self, name, stat_result, namespaces): """Create an `Info` object from a stat result. """ info = { 'basic': { 'name': name, 'is_dir': stat.S_ISDIR(stat_result.st_mode) } } if 'details' in namespaces: info['details'] = self._make_details_from_stat(stat_result) if 'stat' in namespaces: info['stat'] = { k: getattr(stat_result, k) for k in dir(stat_result) if k.startswith('st_') } if 'access' in namespaces: info['access'] = self._make_access_from_stat(stat_result) return Info(info)
[ "def", "_make_info", "(", "self", ",", "name", ",", "stat_result", ",", "namespaces", ")", ":", "info", "=", "{", "'basic'", ":", "{", "'name'", ":", "name", ",", "'is_dir'", ":", "stat", ".", "S_ISDIR", "(", "stat_result", ".", "st_mode", ")", "}", ...
Create an `Info` object from a stat result.
[ "Create", "an", "Info", "object", "from", "a", "stat", "result", "." ]
773cbdb6bceac5e00cf5785b6ffad6dc4574d29c
https://github.com/althonos/fs.sshfs/blob/773cbdb6bceac5e00cf5785b6ffad6dc4574d29c/fs/sshfs/sshfs.py#L321-L339
train
31,586
rroemhild/flask-ldapconn
flask_ldapconn/attribute.py
LDAPAttribute.value
def value(self): '''Return single value or list of values from the attribute. If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a list with values. ''' if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False: return self.__dict__['values'][0] else: return self.__dict__['values']
python
def value(self): '''Return single value or list of values from the attribute. If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a list with values. ''' if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False: return self.__dict__['values'][0] else: return self.__dict__['values']
[ "def", "value", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__dict__", "[", "'values'", "]", ")", "==", "1", "and", "current_app", ".", "config", "[", "'FORCE_ATTRIBUTE_VALUE_AS_LIST'", "]", "is", "False", ":", "return", "self", ".", "__dict__...
Return single value or list of values from the attribute. If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a list with values.
[ "Return", "single", "value", "or", "list", "of", "values", "from", "the", "attribute", ".", "If", "FORCE_ATTRIBUTE_VALUE_AS_LIST", "is", "True", "always", "return", "a", "list", "with", "values", "." ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/attribute.py#L68-L76
train
31,587
rroemhild/flask-ldapconn
flask_ldapconn/attribute.py
LDAPAttribute.append
def append(self, value): '''Add another value to the attribute''' if self.__dict__['values']: self.__dict__['changetype'] = MODIFY_REPLACE self.__dict__['values'].append(value)
python
def append(self, value): '''Add another value to the attribute''' if self.__dict__['values']: self.__dict__['changetype'] = MODIFY_REPLACE self.__dict__['values'].append(value)
[ "def", "append", "(", "self", ",", "value", ")", ":", "if", "self", ".", "__dict__", "[", "'values'", "]", ":", "self", ".", "__dict__", "[", "'changetype'", "]", "=", "MODIFY_REPLACE", "self", ".", "__dict__", "[", "'values'", "]", ".", "append", "(",...
Add another value to the attribute
[ "Add", "another", "value", "to", "the", "attribute" ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/attribute.py#L86-L91
train
31,588
rroemhild/flask-ldapconn
flask_ldapconn/__init__.py
LDAPConn.authenticate
def authenticate(self, username, password, attribute=None, base_dn=None, search_filter=None, search_scope=SUBTREE): '''Attempts to bind a user to the LDAP server. Args: username (str): DN or the username to attempt to bind with. password (str): The password of the username. attribute (str): The LDAP attribute for the username. base_dn (str): The LDAP basedn to search on. search_filter (str): LDAP searchfilter to attempt the user search with. Returns: bool: ``True`` if successful or ``False`` if the credentials are invalid. ''' # If the username is no valid DN we can bind with, we need to find # the user first. valid_dn = False try: parse_dn(username) valid_dn = True except LDAPInvalidDnError: pass if valid_dn is False: user_filter = '({0}={1})'.format(attribute, username) if search_filter is not None: user_filter = '(&{0}{1})'.format(user_filter, search_filter) try: self.connection.search(base_dn, user_filter, search_scope, attributes=[attribute]) response = self.connection.response username = response[0]['dn'] except (LDAPInvalidDnError, LDAPInvalidFilterError, IndexError): return False try: conn = self.connect(username, password) conn.unbind() return True except LDAPBindError: return False
python
def authenticate(self, username, password, attribute=None, base_dn=None, search_filter=None, search_scope=SUBTREE): '''Attempts to bind a user to the LDAP server. Args: username (str): DN or the username to attempt to bind with. password (str): The password of the username. attribute (str): The LDAP attribute for the username. base_dn (str): The LDAP basedn to search on. search_filter (str): LDAP searchfilter to attempt the user search with. Returns: bool: ``True`` if successful or ``False`` if the credentials are invalid. ''' # If the username is no valid DN we can bind with, we need to find # the user first. valid_dn = False try: parse_dn(username) valid_dn = True except LDAPInvalidDnError: pass if valid_dn is False: user_filter = '({0}={1})'.format(attribute, username) if search_filter is not None: user_filter = '(&{0}{1})'.format(user_filter, search_filter) try: self.connection.search(base_dn, user_filter, search_scope, attributes=[attribute]) response = self.connection.response username = response[0]['dn'] except (LDAPInvalidDnError, LDAPInvalidFilterError, IndexError): return False try: conn = self.connect(username, password) conn.unbind() return True except LDAPBindError: return False
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ",", "attribute", "=", "None", ",", "base_dn", "=", "None", ",", "search_filter", "=", "None", ",", "search_scope", "=", "SUBTREE", ")", ":", "# If the username is no valid DN we can bind with, ...
Attempts to bind a user to the LDAP server. Args: username (str): DN or the username to attempt to bind with. password (str): The password of the username. attribute (str): The LDAP attribute for the username. base_dn (str): The LDAP basedn to search on. search_filter (str): LDAP searchfilter to attempt the user search with. Returns: bool: ``True`` if successful or ``False`` if the credentials are invalid.
[ "Attempts", "to", "bind", "a", "user", "to", "the", "LDAP", "server", "." ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/__init__.py#L122-L171
train
31,589
rroemhild/flask-ldapconn
flask_ldapconn/query.py
BaseQuery.get
def get(self, ldap_dn): '''Return an LDAP entry by DN Args: ldap_dn (str): LDAP DN ''' self.base_dn = ldap_dn self.sub_tree = BASE return self.first()
python
def get(self, ldap_dn): '''Return an LDAP entry by DN Args: ldap_dn (str): LDAP DN ''' self.base_dn = ldap_dn self.sub_tree = BASE return self.first()
[ "def", "get", "(", "self", ",", "ldap_dn", ")", ":", "self", ".", "base_dn", "=", "ldap_dn", "self", ".", "sub_tree", "=", "BASE", "return", "self", ".", "first", "(", ")" ]
Return an LDAP entry by DN Args: ldap_dn (str): LDAP DN
[ "Return", "an", "LDAP", "entry", "by", "DN" ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L50-L58
train
31,590
rroemhild/flask-ldapconn
flask_ldapconn/query.py
BaseQuery.filter
def filter(self, *query_filter): '''Set the query filter to perform the query with Args: *query_filter: Simplified Query Language filter ''' for query in query_filter: self.query.append(query) return self
python
def filter(self, *query_filter): '''Set the query filter to perform the query with Args: *query_filter: Simplified Query Language filter ''' for query in query_filter: self.query.append(query) return self
[ "def", "filter", "(", "self", ",", "*", "query_filter", ")", ":", "for", "query", "in", "query_filter", ":", "self", ".", "query", ".", "append", "(", "query", ")", "return", "self" ]
Set the query filter to perform the query with Args: *query_filter: Simplified Query Language filter
[ "Set", "the", "query", "filter", "to", "perform", "the", "query", "with" ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L60-L68
train
31,591
rroemhild/flask-ldapconn
flask_ldapconn/query.py
BaseQuery.all
def all(self, components_in_and=True): '''Return all of the results of a query in a list''' self.components_in_and = components_in_and return [obj for obj in iter(self)]
python
def all(self, components_in_and=True): '''Return all of the results of a query in a list''' self.components_in_and = components_in_and return [obj for obj in iter(self)]
[ "def", "all", "(", "self", ",", "components_in_and", "=", "True", ")", ":", "self", ".", "components_in_and", "=", "components_in_and", "return", "[", "obj", "for", "obj", "in", "iter", "(", "self", ")", "]" ]
Return all of the results of a query in a list
[ "Return", "all", "of", "the", "results", "of", "a", "query", "in", "a", "list" ]
5295596c14538e2d874672c6b108b4b1b85dcd7e
https://github.com/rroemhild/flask-ldapconn/blob/5295596c14538e2d874672c6b108b4b1b85dcd7e/flask_ldapconn/query.py#L79-L82
train
31,592
teffland/pytorch-monitor
build/lib/pytorch_monitor/monitor.py
set_monitor
def set_monitor(module): """ Defines the monitor method on the module. """ def monitor(name, tensor, track_data=True, track_grad=True): """ Register the tensor under the name given (now a string) and track it based on the track_data and track_grad arguments. """ module.monitored_vars[name] = { 'tensor':tensor, 'track_data':track_data, 'track_grad':track_grad, } module.monitor = monitor
python
def set_monitor(module): """ Defines the monitor method on the module. """ def monitor(name, tensor, track_data=True, track_grad=True): """ Register the tensor under the name given (now a string) and track it based on the track_data and track_grad arguments. """ module.monitored_vars[name] = { 'tensor':tensor, 'track_data':track_data, 'track_grad':track_grad, } module.monitor = monitor
[ "def", "set_monitor", "(", "module", ")", ":", "def", "monitor", "(", "name", ",", "tensor", ",", "track_data", "=", "True", ",", "track_grad", "=", "True", ")", ":", "\"\"\"\n Register the tensor under the name given (now a string)\n and track it based on t...
Defines the monitor method on the module.
[ "Defines", "the", "monitor", "method", "on", "the", "module", "." ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L3-L17
train
31,593
teffland/pytorch-monitor
build/lib/pytorch_monitor/monitor.py
set_monitoring
def set_monitoring(module): """ Defines the monitoring method on the module. """ def monitoring(is_monitoring, track_data=None, track_grad=None, track_update=None, track_update_ratio=None): """ Turn monitoring on or off. If any of the keyword arguments are not None, they will be overwritten. """ module.is_monitoring = is_monitoring module.track_data = track_data if track_data is not None else module.track_data module.track_grad = track_grad if track_grad is not None else module.track_grad module.track_update = track_update if track_update is not None else module.track_update module.track_update_ratio = track_update_ratio if track_update_ratio is not None else module.track_update_ratio module.monitoring = monitoring
python
def set_monitoring(module): """ Defines the monitoring method on the module. """ def monitoring(is_monitoring, track_data=None, track_grad=None, track_update=None, track_update_ratio=None): """ Turn monitoring on or off. If any of the keyword arguments are not None, they will be overwritten. """ module.is_monitoring = is_monitoring module.track_data = track_data if track_data is not None else module.track_data module.track_grad = track_grad if track_grad is not None else module.track_grad module.track_update = track_update if track_update is not None else module.track_update module.track_update_ratio = track_update_ratio if track_update_ratio is not None else module.track_update_ratio module.monitoring = monitoring
[ "def", "set_monitoring", "(", "module", ")", ":", "def", "monitoring", "(", "is_monitoring", ",", "track_data", "=", "None", ",", "track_grad", "=", "None", ",", "track_update", "=", "None", ",", "track_update_ratio", "=", "None", ")", ":", "\"\"\"\n Tu...
Defines the monitoring method on the module.
[ "Defines", "the", "monitoring", "method", "on", "the", "module", "." ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L19-L35
train
31,594
teffland/pytorch-monitor
build/lib/pytorch_monitor/monitor.py
grad_hook
def grad_hook(module, name, writer, bins): """ Factory for grad_hook closures """ def hook(grad): writer.add_histogram('{}/grad'.format(name.replace('.','/')), grad.detach().cpu().numpy(), module.global_step-1, bins=bins) return hook
python
def grad_hook(module, name, writer, bins): """ Factory for grad_hook closures """ def hook(grad): writer.add_histogram('{}/grad'.format(name.replace('.','/')), grad.detach().cpu().numpy(), module.global_step-1, bins=bins) return hook
[ "def", "grad_hook", "(", "module", ",", "name", ",", "writer", ",", "bins", ")", ":", "def", "hook", "(", "grad", ")", ":", "writer", ".", "add_histogram", "(", "'{}/grad'", ".", "format", "(", "name", ".", "replace", "(", "'.'", ",", "'/'", ")", "...
Factory for grad_hook closures
[ "Factory", "for", "grad_hook", "closures" ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L37-L44
train
31,595
teffland/pytorch-monitor
build/lib/pytorch_monitor/monitor.py
remove_grad_hooks
def remove_grad_hooks(module, input): """ Remove gradient hooks to all of the parameters and monitored vars """ for hook in list(module.param_hooks.keys()): module.param_hooks[hook].remove() module.param_hooks.pop(hook) for hook in list(module.var_hooks.keys()): module.var_hooks[hook].remove() module.var_hooks.pop(hook)
python
def remove_grad_hooks(module, input): """ Remove gradient hooks to all of the parameters and monitored vars """ for hook in list(module.param_hooks.keys()): module.param_hooks[hook].remove() module.param_hooks.pop(hook) for hook in list(module.var_hooks.keys()): module.var_hooks[hook].remove() module.var_hooks.pop(hook)
[ "def", "remove_grad_hooks", "(", "module", ",", "input", ")", ":", "for", "hook", "in", "list", "(", "module", ".", "param_hooks", ".", "keys", "(", ")", ")", ":", "module", ".", "param_hooks", "[", "hook", "]", ".", "remove", "(", ")", "module", "."...
Remove gradient hooks to all of the parameters and monitored vars
[ "Remove", "gradient", "hooks", "to", "all", "of", "the", "parameters", "and", "monitored", "vars" ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L46-L53
train
31,596
teffland/pytorch-monitor
build/lib/pytorch_monitor/monitor.py
get_monitor_forward_and_backward
def get_monitor_forward_and_backward(summary_writer, bins): """ Get the method for monitoring the forward values of the network """ def monitor_forward_and_backward(module, input, output): """ Iterate over the module parameters and monitor their forward values. Then iterate over all of the monitored_vars, monitor their forward values and set their grad_hooks """ # Parameters if module.is_monitoring: param_names = [ name for name, _ in module.named_parameters()] for name, param in zip(param_names, module.parameters()): if module.track_grad and param.requires_grad: hook = grad_hook(module, name, summary_writer, bins) module.param_hooks[name] = param.register_hook(hook) if module.track_data: summary_writer.add_histogram('{}/data'.format(name.replace('.','/')), param.detach().cpu().numpy(), module.global_step, bins=bins) if name in module.last_state_dict: if module.track_update: update = param - module.last_state_dict[name] summary_writer.add_histogram('{}/update-val'.format(name.replace('.','/')), update.detach().cpu().numpy(), module.global_step-1, bins=bins) if module.track_update and module.track_update_ratio: update_ratio = update / (module.last_state_dict[name]+1e-15) summary_writer.add_histogram('{}/update-ratio'.format(name.replace('.','/')), update_ratio.detach().cpu().numpy(), module.global_step-1, bins=bins) if module.track_update: module.last_state_dict[name] = param.clone() # Intermediate Vars for prefix, mod in module.named_modules(): for tensor_name, entry in mod.monitored_vars.items(): name = '{}/{}'.format(prefix, tensor_name) if prefix else tensor_name tensor = entry['tensor'] if entry['track_grad'] and tensor.requires_grad: hook = grad_hook(module, name, summary_writer, bins) module.var_hooks[name] = tensor.register_hook(hook) if entry['track_data']: summary_writer.add_histogram('{}/data'.format(name.replace('.','/')), tensor.detach().cpu().numpy(), module.global_step, bins=bins) # Update step module.global_step += 1 return monitor_forward_and_backward
python
def get_monitor_forward_and_backward(summary_writer, bins): """ Get the method for monitoring the forward values of the network """ def monitor_forward_and_backward(module, input, output): """ Iterate over the module parameters and monitor their forward values. Then iterate over all of the monitored_vars, monitor their forward values and set their grad_hooks """ # Parameters if module.is_monitoring: param_names = [ name for name, _ in module.named_parameters()] for name, param in zip(param_names, module.parameters()): if module.track_grad and param.requires_grad: hook = grad_hook(module, name, summary_writer, bins) module.param_hooks[name] = param.register_hook(hook) if module.track_data: summary_writer.add_histogram('{}/data'.format(name.replace('.','/')), param.detach().cpu().numpy(), module.global_step, bins=bins) if name in module.last_state_dict: if module.track_update: update = param - module.last_state_dict[name] summary_writer.add_histogram('{}/update-val'.format(name.replace('.','/')), update.detach().cpu().numpy(), module.global_step-1, bins=bins) if module.track_update and module.track_update_ratio: update_ratio = update / (module.last_state_dict[name]+1e-15) summary_writer.add_histogram('{}/update-ratio'.format(name.replace('.','/')), update_ratio.detach().cpu().numpy(), module.global_step-1, bins=bins) if module.track_update: module.last_state_dict[name] = param.clone() # Intermediate Vars for prefix, mod in module.named_modules(): for tensor_name, entry in mod.monitored_vars.items(): name = '{}/{}'.format(prefix, tensor_name) if prefix else tensor_name tensor = entry['tensor'] if entry['track_grad'] and tensor.requires_grad: hook = grad_hook(module, name, summary_writer, bins) module.var_hooks[name] = tensor.register_hook(hook) if entry['track_data']: summary_writer.add_histogram('{}/data'.format(name.replace('.','/')), tensor.detach().cpu().numpy(), module.global_step, bins=bins) # Update step module.global_step += 1 return monitor_forward_and_backward
[ "def", "get_monitor_forward_and_backward", "(", "summary_writer", ",", "bins", ")", ":", "def", "monitor_forward_and_backward", "(", "module", ",", "input", ",", "output", ")", ":", "\"\"\"\n Iterate over the module parameters and monitor their forward values.\n The...
Get the method for monitoring the forward values of the network
[ "Get", "the", "method", "for", "monitoring", "the", "forward", "values", "of", "the", "network" ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/monitor.py#L55-L107
train
31,597
teffland/pytorch-monitor
build/lib/pytorch_monitor/init_experiment.py
commit
def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time), allow_empty=True ) commit_hash = sh.git('rev-parse', 'HEAD').strip() return commit_hash except: return '<Unable to commit>'
python
def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time), allow_empty=True ) commit_hash = sh.git('rev-parse', 'HEAD').strip() return commit_hash except: return '<Unable to commit>'
[ "def", "commit", "(", "experiment_name", ",", "time", ")", ":", "try", ":", "sh", ".", "git", ".", "commit", "(", "'-a'", ",", "m", "=", "'\"auto commit tracked files for new experiment: {} on {}\"'", ".", "format", "(", "experiment_name", ",", "time", ")", ",...
Try to commit repo exactly as it is when starting the experiment for reproducibility.
[ "Try", "to", "commit", "repo", "exactly", "as", "it", "is", "when", "starting", "the", "experiment", "for", "reproducibility", "." ]
56dce63ba85c0f9faf9df11df78161ee60f5fae9
https://github.com/teffland/pytorch-monitor/blob/56dce63ba85c0f9faf9df11df78161ee60f5fae9/build/lib/pytorch_monitor/init_experiment.py#L13-L25
train
31,598
percolate/ec2-security-groups-dumper
ec2_security_groups_dumper/main.py
Firewall.json
def json(self): """ Output the security rules as a json string. Return: str """ return json.dumps(self.dict_rules, sort_keys=True, indent=2, separators=(',', ': '))
python
def json(self): """ Output the security rules as a json string. Return: str """ return json.dumps(self.dict_rules, sort_keys=True, indent=2, separators=(',', ': '))
[ "def", "json", "(", "self", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "dict_rules", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
Output the security rules as a json string. Return: str
[ "Output", "the", "security", "rules", "as", "a", "json", "string", "." ]
f2a40d1b3802211c85767fe74281617e4dbae543
https://github.com/percolate/ec2-security-groups-dumper/blob/f2a40d1b3802211c85767fe74281617e4dbae543/ec2_security_groups_dumper/main.py#L135-L145
train
31,599