Search is not available for this dataset
text stringlengths 75 104k |
|---|
def load_mnist():
'''Load the MNIST digits dataset.'''
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
train_images = arr('train_images', np.float32) / 128 - 1
... |
def build(algo, loss, params=None, inputs=None, updates=(), monitors=(),
monitor_gradients=False):
'''Construct an optimizer by name.
Parameters
----------
algo : str
The name of the optimization algorithm to build.
loss : Theano expression
Loss function to minimize. This ... |
def _compile(self, **kwargs):
'''Compile the Theano functions for evaluating and updating our model.
'''
util.log('compiling evaluation function')
self.f_eval = theano.function(self._inputs,
self._monitor_exprs,
... |
def get_updates(self, **kwargs):
'''Get parameter update expressions for performing optimization.
Keyword arguments can be applied here to set any of the global
optimizer attributes.
Yields
------
updates : (parameter, expression) tuples
A sequence of parame... |
def _differentiate(self, params=None):
'''Return a sequence of gradients for our parameters.
If this optimizer has been configured with a gradient norm limit, or
with elementwise gradient clipping, this method applies the appropriate
rescaling and clipping operations before returning th... |
def set_params(self, targets=None):
'''Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters ... |
def _log(self, monitors, iteration, label='', suffix=''):
'''Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
itera... |
def evaluate(self, dataset):
'''Evaluate the current model parameters on a dataset.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A set of data to use for evaluating the model.
Returns
-------
monitors : OrderedDict
... |
def _prepare(self, **kwargs):
'''Set up properties for optimization.
This method can be overridden by base classes to provide parameters that
are specific to a particular optimization technique (e.g., setting up a
learning rate value).
'''
self.learning_rate = util.as_fl... |
def iterate(self, train=None, valid=None, max_updates=None, **kwargs):
r'''Optimize a loss iteratively using a training and validation dataset.
This method yields a series of monitor values to the caller. After every
optimization epoch, a pair of monitor dictionaries is generated: one
e... |
def minimize(self, *args, **kwargs):
'''Optimize our loss exhaustively.
This method is a thin wrapper over the :func:`iterate` method. It simply
exhausts the iterative optimization process and returns the final
monitor values.
Returns
-------
train_monitors : di... |
def _step(self, dataset):
'''Advance the state of the optimizer by one step.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A dataset for optimizing the model.
Returns
-------
train_monitors : dict
A dictionar... |
def accept_arguments(method, number_of_arguments=1):
"""Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments
"""
if 'method' in method.__class__.__name__:
number_of_argume... |
def emit(self, signal, value=None, gather=False):
"""Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value)
signal: the name of the signal to emit, must be defined in the classes 'signals' list.
value: the value to pass to all connect... |
def connect(self, signal, slot, transform=None, condition=None):
"""Defines a connection between this objects signal and another objects slot
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be called
... |
def disconnect(self, signal=None, slot=None, transform=None, condition=None):
"""Removes connection(s) between this objects signal and connected slot(s)
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be cal... |
def get(self, key):
""" Returns context data for a given app, can be an ID or a case insensitive name """
keystr = str(key)
res = None
try:
res = self.ctx[keystr]
except KeyError:
for k, v in self.ctx.items():
if "name" in v and v["name"].... |
def hash_name(self):
""" The URL-friendly identifier for the item. Generates its own approximation if one isn't available """
name = self._item.get("market_hash_name")
if not name:
name = "{0.appid}-{0.name}".format(self)
return name |
def quality(self):
""" Can't really trust presence of a schema here, but there is an ID sometimes """
try:
qid = int((self.tool_metadata or {}).get("quality", 0))
except:
qid = 0
# We might be able to get the quality strings from the item's tags
internal_... |
def get(cls):
"""Get the current API key.
if one has not been given via 'set' the env var STEAMODD_API_KEY will
be checked instead.
"""
apikey = cls.__api_key or cls.__api_key_env_var
if apikey:
return apikey
else:
raise APIKeyMissingError... |
def call(self):
""" Make the API call again and fetch fresh data. """
data = self._downloader.download()
# Only try to pass errors arg if supported
if sys.version >= "2.7":
data = data.decode("utf-8", errors="ignore")
else:
data = data.decode("utf-8")
... |
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID """
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
ex... |
def _quality_definition(self, qid):
""" Returns the ID and localized name of the given quality, can be either ID type """
qualities = self._schema["qualities"]
try:
return qualities[qid]
except KeyError:
qid = self._schema["quality_names"].get(str(qid).lower(), 0... |
def attributes(self):
""" Returns all attributes in the schema """
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] |
def origin_id_to_name(self, origin):
""" Returns a localized origin name for a given ID """
try:
oid = int(origin)
except (ValueError, TypeError):
return None
return self.origins.get(oid) |
def attributes(self):
""" Returns a list of attributes """
overridden_attrs = self._attributes
sortmap = {"neutral": 1, "positive": 2,
"negative": 3}
sortedattrs = list(overridden_attrs.values())
sortedattrs.sort(key=operator.itemgetter("defindex"))
s... |
def equipped(self):
""" Returns a dict of classes that have the item equipped and in what slot """
equipped = self._item.get("equipped", [])
# WORKAROUND: 0 is probably an off-by-one error
# WORKAROUND: 65535 actually serves a purpose (according to Valve)
return dict([(eq["class... |
def equipable_classes(self):
""" Returns a list of classes that _can_ use the item. """
sitem = self._schema_item
return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c] |
def contents(self):
""" Returns the item in the container, if there is one.
This will be a standard item object. """
rawitem = self._item.get("contained_item")
if rawitem:
return self.__class__(rawitem, self._schema) |
def full_name(self):
"""
The full name of the item, generated depending
on things such as its quality, rank, the schema language,
and so on.
"""
qid, quality_str, pretty_quality_str = self.quality
custom_name = self.custom_name
item_name = self.name
... |
def kill_eaters(self):
"""
Returns a list of tuples containing the proper localized kill eater type strings and their values
according to set/type/value "order"
"""
eaters = {}
ranktypes = self._kill_types
for attr in self:
aname = attr.name.strip()
... |
def rank(self):
"""
Returns the item's rank (if it has one)
as a dict that includes required score, name, and level.
"""
if self._rank != {}:
# Don't bother doing attribute lookups again
return self._rank
try:
# The eater determining ... |
def available_styles(self):
""" Returns a list of all styles defined for the item """
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) |
def formatted_value(self):
""" Returns a formatted value as a string"""
# TODO: Cleanup all of this, it's just weird and unnatural maths
val = self.value
pval = val
ftype = self.value_type
if ftype == "percentage":
pval = int(round(val * 100))
if... |
def formatted_description(self):
""" Returns a formatted description string (%s* tokens replaced) or None if unavailable """
desc = self.description
if desc:
return desc.replace("%s1", self.formatted_value)
else:
return None |
def value_type(self):
""" The attribute's type, note that this is the type of the attribute's
value and not its affect on the item (i.e. negative or positive). See
'type' for that. """
redundantprefix = "value_is_"
vtype = self._attribute.get("description_format")
if vty... |
def account_info(self):
""" Certain attributes have a user's account information
associated with it such as a gifted or crafted item.
A dict with two keys: 'persona' and 'id64'.
None if the attribute has no account information attached to it. """
account_info = self._attribute.g... |
def tags(self):
""" Returns a dict containing tags and their localized labels as values """
return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])]) |
def vanity(self):
""" Returns the user's vanity url if it exists, None otherwise """
purl = self.profile_url.strip('/')
if purl.find("/id/") != -1:
return os.path.basename(purl) |
def creation_date(self):
""" Returns the account creation date as a localtime time.struct_time
struct if public"""
timestamp = self._prof.get("timecreated")
if timestamp:
return time.localtime(timestamp) |
def current_game(self):
"""
Returns a tuple of 3 elements (each of which may be None if not available):
Current game app ID, server ip:port, misc. extra info (eg. game title)
"""
obj = self._prof
gameid = obj.get("gameid")
gameserverip = obj.get("gameserverip")
... |
def level(self):
"""
Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this o... |
def from_def(cls, obj):
""" Builds a profile object from a raw player summary object """
prof = cls(obj["steamid"])
prof._cache = obj
return prof |
def on_status_withheld(self, status_id, user_id, countries):
"""Called when a status is withheld"""
logger.info('Status %s withheld for user %s', status_id, user_id)
return True |
def on_disconnect(self, code, stream_name, reason):
"""Called when a disconnect is received"""
logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
return True |
def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
logger.error('Twitter returned error code %s', status_code)
self.error = status_code
return False |
def on_exception(self, exception):
"""An exception occurred in the streaming thread"""
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception |
def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... |
def update_tracking_terms(self):
"""
Terms must be one-per-line.
Blank lines will be skipped.
"""
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set... |
def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... |
def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal"""
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode... |
def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) |
def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... |
def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) |
def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... |
def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... |
def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate |
def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... |
def start_polling(self, interval):
"""
Start polling for term updates and streaming.
"""
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for... |
def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... |
def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... |
def stop_stream(self):
"""
Stops the current stream. Blocks until this is done.
"""
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
... |
def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %... |
def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... |
def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key |
def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
"""
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %... |
def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... |
def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b |
def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... |
def zero_width_split(pattern, string):
"""
Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array
"""
splits = list((m.start(), m.end()) for m in regex.finditer(patt... |
def roll_group(group):
"""
Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results
"""
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2... |
def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... |
def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... |
def eval(self, expr):
"""
Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression
"""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.pa... |
def _eval(self, node):
"""
Evaluate a node
:param node: Node to eval
:return: Result of node
"""
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na... |
def _eval_num(self, node):
"""
Evaluate a numerical node
:param node: Node to eval
:return: Result of node
"""
if self.floats:
return node.n
else:
return int(node.n) |
def _eval_unaryop(self, node):
"""
Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.operand)) |
def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) |
def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... |
def roll_dice(self): # Roll dice with current roll
"""
Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results.
"""
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._las... |
def roll(self, value):
"""
Setter for roll, verifies the roll is valid
:param value: Roll
:return: None
"""
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dic... |
def run(files, temp_folder, arg=''):
"Look for pdb.set_trace() commands in python files."
parser = get_parser()
args = parser.parse_args(arg.split())
py_files = filter_python_files(files)
if args.ignore:
orig_file_list = original_files(py_files, temp_folder)
py_files = set(orig_file... |
def checks():
"""
An iterator of valid checks that are in the installed checkers package.
yields check name, check module
"""
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = impo... |
def files_to_check(commit_only):
"""
Validate the commit diff.
Make copies of the staged changes for analysis.
"""
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
... |
def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... |
def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash... |
def create_fake_copies(files, destination):
"""
Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files.
"""
dest_files = []
for filename in files:
leaf_d... |
def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... |
def configuration(self, plugin):
"""
Get plugin configuration.
Return a tuple of (on|off|default, args)
"""
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) |
def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() |
def run(files, temp_folder):
"""Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
"""
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_... |
def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in arg... |
def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
... |
def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py... |
def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy... |
def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... |
def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f |
def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
... |
def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) |
def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.