rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
charset=email_charset, debug=False, From=source) | charset=email_charset, debug=False) | def __call__(self): localrole = self.element.localrole.strip() mailhost = getToolByName(aq_inner(self.context), "MailHost") |
The comparision is based on the nummerical name of the device, which is the bus address for the device. """ if (long(self.data[0]["name"])) < other: | The comparision is based on the name of the device, which is the bus address for the device. """ if self.data[0]["name"] < other: | def __cmp__(self, other): """Compare device data widgets to other widgets (or anything). |
elif (long(self.data[0]["name"])) > other: | elif self.data[0]["name"] > other: | def __cmp__(self, other): """Compare device data widgets to other widgets (or anything). |
165: '& 164: '& | 209: '& 241: '& | def Format(line_in, replace = True): global cur_file; char_map = { 10: '', # newline 13: '\n', # newline 160: '', # non-printable char 38: '&', # ampersand 60: '<', # less than 62: '>', # greater than 145: '‘', # left single quote 146: '’', # right single quote 34: ... |
(hours, minutes), ampm = start_time[:-2].split(':'), start_time[-2:] | hours, minutes = start_time[:-2].split(':') ampm = start_time[-2:] | def format_class_sortkey_time(self, value): """Returns the 24-hour time value of the given class's start time.""" start_time = self.input.get('session', {}).get('start-time') try: (hours, minutes), ampm = start_time[:-2].split(':'), start_time[-2:] nhours = int(hours) if ampm == 'PM' and nhours != 12: hours = nhours + ... |
assert key in self.input, 'Invalid key in profile.skip_cross_listings: %s (%s)' % (key, repr(profile.skip_cross_listings)) | assert key in self.input,\ 'Invalid key in profile.skip_cross_listings: %s (%s)' % ( key, repr(profile.skip_cross_listings)) | def format_cross_listings(self, value): """Returns a list of cross-listings for the current class. In some cases, returns an empty list, even if the class is cross-listed in Colleague.""" # If the current profile wants us to skip the cross-listings for this # class, return an empty list. for key, patterns in profile.... |
if name.strip() and self.input.get('start-time','').strip() == '' and self.input.get('end-time','').strip() == '': | if name.strip() and self.input.get('start-time','').strip() == ''\ and self.input.get('end-time','').strip() == '': | def __get_faculty_names(self, name): """Utility function to split the given name, in "Last Name, First Initial" format, into its constituent parts. Will always return a two-tuple, which will contain the last name and first initial or two empty strings.""" |
return time.lstrip('0').replace('AM',' a.m.').replace('PM',' p.m.').replace(':00','') | return time\ .lstrip('0')\ .replace('AM',' a.m.')\ .replace('PM',' p.m.')\ .replace(':00','') | def format_time(time): return time.lstrip('0').replace('AM',' a.m.').replace('PM',' p.m.').replace(':00','') |
if session_data.get('start-time') in ('TBA',) or session_data.get('end-time') in ('TBA',): | if session_data.get('start-time') in ('TBA',) or \ session_data.get('end-time') in ('TBA',): | def add_defaults(self, session_data): """Adds default values to the given session_data dict. Has special-case logic for certain fields that the normal SessionFormatter formatting functions cannot implement. Always returns a dict.""" assert isinstance(session_data, dict) |
if session_data.get('start-time') in default_times and session_data.get('end-time') in default_times: | if session_data.get('start-time') in default_times and \ session_data.get('end-time') in default_times: | def add_default(session, session_key, defaults_key=None): """Intelligently adds a value from the profile.defaults dict to the given session dict if that value is not already present.""" defaults_key = defaults_key or session_key if not session.get(session_key): session[session_key] = profile.defaults[defaults_key] |
print 'Inavlid key in skip_minimesters: %s' % repr(key) | print 'Inavlid key in skip_minimesters: %r' % key | def is_minimester(self, classdata): """A course counts as a "minimester" course if either of the following conditions are met: - The class is a "Flex Day" or "Flex Night" class OR - The class lasts less than profile.minimester_threshold weeks AND the class does not match any of the patterns in profile.skip_minimesters"... |
print 'Class start date %s is not in any of the terms in this profile.' % class_start | print ('Class start date %s is not in any of the terms in ' 'this profile.') % class_start | def get_term(self, term_id, class_start): """Determines the term for a class that starts on the given start date. This method is in FormatUtils because it needs to be used in multiple formatters and thus should have its results cached. |
raise AssertionError('Target date %s not found in the current profile\'s terms.' % target_date) | raise AssertionError( ("Target date %s not found in the current profile's " "terms.") % target_date) | def find_term(start_or_end, target_date): """Search through the profile's terms to find one that contains the given target date as either its start or end date. Parameter start_or_end must be either 0 or 1.""" for term, dates in profile.terms.items(): if dates[start_or_end] == target_date: return term raise AssertionE... |
'Class starting on %s falls between the earliest ' + 'and latest term dates but is not contained in any ' + 'the current profile\'s terms. This is probably a ' + 'problem in the current profile\'s term dates.' ) | 'Class starting on %s falls between the earliest ' 'and latest term dates but is not contained in any ' 'the current profile\'s terms. This is probably a ' 'problem in the current profile\'s term dates.') | def find_term(start_or_end, target_date): """Search through the profile's terms to find one that contains the given target date as either its start or end date. Parameter start_or_end must be either 0 or 1.""" for term, dates in profile.terms.items(): if dates[start_or_end] == target_date: return term raise AssertionE... |
profile's terms dict. If the given term is not a key in the terms dict, the term name is looked up in the term_names dict first.""" assert term in profile.terms, \ 'Term %s not found in current profile\'s term dict. Valid term names: %s' % (term, ', '.join(profile.terms.keys())) | profile's terms dict. If the given term is not a key in the terms dict, the term name is looked up in the term_names dict first.""" assert term in profile.terms, ( "Term %s not found in current profile's term dict. Valid term " "names: %s") % (term, ', '.join(profile.terms.keys())) | def get_term_dates(self, term): """Gets the start and end dates for the given term from the current profile's terms dict. If the given term is not a key in the terms dict, the term name is looked up in the term_names dict first.""" assert term in profile.terms, \ 'Term %s not found in current profile\'s term dict. Va... |
if re.search(pattern, value) and not xmlutils.is_xml_fragment(value) and not already_escaped: | if re.search(pattern, value) and \ not xmlutils.is_xml_fragment(value) and \ not already_escaped: | def post_process_comments(self, value): """Runs a set of regular expression patterns and replacements over the input value to, e.g., wrap every URL in a <url> tag.""" |
os.kill(os.getpid(), 15) | py.process.kill(os.getpid()) | def test_crash(): os.kill(os.getpid(), 15) |
assert "Not properly terminated" in str(kwargs['error']) | assert isinstance(kwargs['error'], execnet.RemoteError) | def test_crash_invalid_item(self, mysetup): node = mysetup.makenode() node.send(123) # invalid item kwargs = mysetup.geteventargs("pytest_testnodedown") assert kwargs['node'] is node assert "Not properly terminated" in str(kwargs['error']) |
data = self.events.get(timeout=2) | data = self.events.get(timeout=WAIT_TIMEOUT) | def popevent(self, name=None): while 1: if self.use_callback: data = self.events.get(timeout=2) else: data = self.slp.channel.receive(timeout=2) ev = EventCall(data) if name is None or ev.name == name: return ev print("skipping %s" % (ev,)) |
data = self.slp.channel.receive(timeout=2) | data = self.slp.channel.receive(timeout=WAIT_TIMEOUT) | def popevent(self, name=None): while 1: if self.use_callback: data = self.events.get(timeout=2) else: data = self.slp.channel.receive(timeout=2) ev = EventCall(data) if name is None or ev.name == name: return ev print("skipping %s" % (ev,)) |
print ev.kwargs | def test_remote_collect_skip(self, slave): p = slave.testdir.makepyfile(""" import py py.test.skip("hello") """) slave.setup() ev = slave.popevent("collectionstart") assert not ev.kwargs ev = slave.popevent() assert ev.name == "collectreport" rep = unserialize_report(ev.name, ev.kwargs['data']) assert rep.skipped ev = ... | |
print "s2call-finished" | print ("s2call-finished") | def pytest_testnodedown(node, error): assert node.slaveoutput['s2'] == 42 print "s2call-finished" |
directivelyProvides(ob, directlyProvidedBy(ob), I1) | directlyProvides(ob, directlyProvidedBy(ob), I1) | def alsoProvides(object, *interfaces): """Declare additional interfaces directly for an object:: |
try: for non_name_text in self.NON_NAME: if self.__full_name.upper().find(non_name_text) > -1: return True except AttributeError: pass | for part in self.__split_name: if part.upper() in self.NON_NAME: return True | def get_has_non_name_values(self): try: for non_name_text in self.NON_NAME: if self.__full_name.upper().find(non_name_text) > -1: return True except AttributeError: pass return False |
if self.__processed: | if self.__processed or self.looks_corporate or self.has_non_name_values: | def process_name(self): if self.__processed: return self.__clean() name_parts = self.__split_name # Find salutation, save it, remove it if self.has_salutation: self.__salutation = name_parts[0] del name_parts[0] |
self.__suffix = name_parts[-1] del name_parts[-1] | suffixes = [] suffix_present = True while suffix_present: if name_parts[-1].upper() in self.SUFFIXES: suffixes.append(name_parts[-1]) del name_parts[-1] else: suffix_present = False self.__suffix = ", ".join(suffixes) | def process_name(self): if self.__processed: return self.__clean() name_parts = self.__split_name # Find salutation, save it, remove it if self.has_salutation: self.__salutation = name_parts[0] del name_parts[0] |
def get_has_generation(self): for part in self.__split_name: if part.upper() in self.GENERATIONS: return True return False has_generation = property(get_has_generation) | def get_has_suffix(self): if self.__split_name[-1].upper() in self.SUFFIXES: return True return False | |
for supplemental_text in self.SUPPLEMENTAL_INFO: supplemental_index = self.__full_name.upper().find(supplemental_text) if supplemental_index > -1: self.__full_name = self.__full_name[0:supplemental_index] | def __clean(self): unwanted = ['.',',','/'] for char in unwanted: self.__full_name = self.__full_name.replace(char,'') for supplemental_text in self.SUPPLEMENTAL_INFO: supplemental_index = self.__full_name.upper().find(supplemental_text) if supplemental_index > -1: self.__full_name = self.__full_name[0:supplemental_ind... | |
suffixes.append(name_parts[-1]) | suffixes.insert(0,name_parts[-1]) | def process_name(self): if self.__processed or self.looks_corporate or self.has_non_name_values: return self.__clean() |
if nick in self.greets: util.say(bot, channel, self.greets[nick]) | greet = self.greets.get(nick) if greet: util.say(bot, channel, greet) | def join(self, bot, channel, user): ''' Called when user joins a channel. ''' # Retrieve the nick nick = util.get_nick(user) if nick == bot.nickname: return # Only interested in others joining # Check if we have greeting and serve it if nick in self.greets: util.say(bot, channel, self.greets[nick]) |
log.writelines(msgs) | log.writelines(m + "\n" for m in msgs) | def message(self, bot, channel, user, message, type): ''' Called when bot "hears" a message. ''' if not channel: return # Only interested in channel messages nick = util.get_nick(user) # Collect messages pertaining to this user messages = [] ; files = [] for recp in self._list_recipients(): if fnmatch.fnmatch... |
for func in ['__import__', 'eval', 'dir', 'open', 'exit']: del g['__builtins__'][func] | for func in FORBIDDEN_BUILTINS: if func in g['__builtins__']: del g['__builtins__'][func] for func in FORBIDDEN_GLOBALS: if func in g: del g[func] | def _eval_worker(pipe): ''' Pops the incoming expressions from given Pipe, evaluates them and sends the back. Continues indefinetaly. ''' # Construct a (relatively) safe dictionary of globals # to be used by evaluated expressions g = math.__dict__.copy() g['__builtins__'] = __builtins__.copy() for func in ['__import__'... |
except SyntaxError: res = "Syntax error." except ValueError: res = "Evaluation error." except NameError: res = "Unknown or forbidden function." except MemoryError: res = "Out of memory." except Exception: res = "Error." | except SyntaxError: res = "Syntax error." except ValueError: res = "Evaluation error." except TypeError: res = "Type mismatch." except OverflowError: res = "Overflow." except FloatingPointError: res = "Floating point exception." except ZeroDivisionError: res = "Division by zero." exc... | def _eval_worker(pipe): ''' Pops the incoming expressions from given Pipe, evaluates them and sends the back. Continues indefinetaly. ''' # Construct a (relatively) safe dictionary of globals # to be used by evaluated expressions g = math.__dict__.copy() g['__builtins__'] = __builtins__.copy() for func in ['__import__'... |
if res and len(res) > 1000: | if res and len(res) > 1024: | def _eval_worker(pipe): ''' Pops the incoming expressions from given Pipe, evaluates them and sends the back. Continues indefinetaly. ''' # Construct a (relatively) safe dictionary of globals # to be used by evaluated expressions g = math.__dict__.copy() g['__builtins__'] = __builtins__.copy() for func in ['__import__'... |
@command('c') | EVAL_TIMEOUT = 5 | def hello(arg, **kwargs): return "Hello." |
def _imp(name, globals={}, locals={}, from_list=[], level=-1): raise ImportError | def _imp(name, globals={}, locals={}, from_list=[], level=-1): raise ImportError | |
g['__builtins__']['__import__'] = _imp | del g['__builtins__']['__import__'] del g['__builtins__']['eval'] del g['__builtins__']['dir'] | def _imp(name, globals={}, locals={}, from_list=[], level=-1): raise ImportError |
except ImportError: return "Sorry, only math allowed." | def _imp(name, globals={}, locals={}, from_list=[], level=-1): raise ImportError | |
return T.nnet.sigmoid(T.dot(v, self.W) + self.hbias) | return T.nnet.sigmoid(T.dot(vis, self.W) + self.hbias) | def propup(self, vis): ''' This function propagates the visible units activation upwards to the hidden units ''' return T.nnet.sigmoid(T.dot(v, self.W) + self.hbias) |
to_exec[3]=False to_exec=[False]*len(algo) to_exec[3]=True | def speed(): """ This fonction modify the configuration theano and don't restore it! I want it to be compatible with python2.4 so using try: finaly: is not an option. """ import theano algo=['logistic_sgd','logistic_cg','mlp','convolutional_mlp','dA','SdA','DBN','rbm'] to_exec=[True]*len(algo) | |
expected_times_64=numpy.asarray([ 12.42313051 28.09523582 106.35365391 153.62705898 153.12310314 425.09175086 642.72824597 652.52828193]) | expected_times_64=numpy.asarray([ 12.42313051, 28.09523582, 106.35365391, 153.62705898, 153.12310314, 425.09175086, 642.72824597, 652.52828193]) | def speed(): """ This fonction modify the configuration theano and don't restore it! I want it to be compatible with python2.4 so using try: finaly: is not an option. """ import theano algo=['logistic_sgd','logistic_cg','mlp','convolutional_mlp','dA','SdA','DBN','rbm'] to_exec=[True]*len(algo) |
while (epoch < n_epoch) and (not done_looping): | while (epoch < n_epochs) and (not done_looping): | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
(epoch, minibatch_index+1, n_minibatches, \ | (epoch, minibatch_index+1, n_train_batches, \ | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
(epoch, minibatch_index+1, n_minibatches, | (epoch, minibatch_index+1, n_train_batches, | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
low = low = -numpy.sqrt(6/(n_in+n_hidden)), high = numpy.sqrt(6/(n_in+n_hidden)), \ | low = -numpy.sqrt(6/(n_in+n_hidden)), high = numpy.sqrt(6/(n_in+n_hidden)), \ | def __init__(self, input, n_in, n_hidden, n_out): """Initialize the parameters for the multilayer perceptron |
self.output = pooled_out + self.b.dimshuffle('x', 0, 'x', 'x') | self.output = T.tanh(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x')) | def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2,2)): """ Allocate a LeNetConvPoolLayer with shared variable internal parameters. :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type input: theano.tensor.dtensor4 :param input: symbolic image ten... |
def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate | def evaluate_lenet5(learning_rate=0.01, n_iter=200, dataset='mnist.pkl.gz'): | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
filter_shape=(6,1,5,5), poolsize=(2,2)) | filter_shape=(20,1,5,5), poolsize=(2,2)) | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
image_shape=(batch_size,6,12,12), filter_shape=(32,6,5,5), poolsize=(2,2)) | image_shape=(batch_size,20,12,12), filter_shape=(50,20,5,5), poolsize=(2,2)) | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
n_in=32*4*4, n_out=500) | n_in=50*4*4, n_out=500) | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
learning_rate = numpy.asarray(learning_rate, dtype=theano.config.floatX) | grads = T.grad(cost, params) | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
train_model = theano.function([x, y], cost, updates=[(p, p - learning_rate*gp) for p,gp in zip(params, T.grad(cost, params))]) | updates = {} for param_i, grad_i in zip(params, grads): updates[param_i] = param_i - learning_rate * grad_i train_model = theano.function([x, y], cost, updates=updates) | def evaluate_lenet5(learning_rate=0.0001, n_iter=1000, dataset='mnist.pkl.gz'): print 'learning_rate = ', learning_rate rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the min... |
x = theano.floatX.xmatrix(theano.config.floatX) | x = T.matrix(theano.config.floatX) | def evaluate_lenet5(learning_rate=0.1, n_iter=200, dataset='mnist.pkl.gz'): rng = numpy.random.RandomState(23455) train_batches, valid_batches, test_batches = load_dataset(dataset) ishape = (28,28) # this is the size of MNIST images batch_size = 20 # sized of the minibatch # allocate symbolic variables for th... |
batch_size = 5 | batch_size = 20 | def cg_optimization_mnist( n_iter=50 ): """Demonstrate conjugate gradient optimization of a log-linear model This is demonstrated on MNIST. :param n_iter: number of iterations ot run the optimizer """ #TODO: Tzanetakis # Load the dataset ; note that the dataset is already divided in # minibatches of size 10; f = gz... |
initial_b = numpy.zeros(n_hidden) | initial_b = numpy.zeros(n_hidden, dtype = theano.config.floatX) | def __init__(self, n_visible= 784, n_hidden= 500, corruption_level = 0.1,\ input = None, shared_W = None, shared_b = None): """ Initialize the dA class by specifying the number of visible units (the dimension d of the input ), the number of hidden units ( the dimension d' of the latent or hidden space ) and the corrupt... |
theano.Param(learning_rate, default = 0.1), theano.Param(k, default = 1)], | theano.Param(learning_rate, default = 0.1)], | def pretraining_functions(self, train_set_x, batch_size,k): ''' Generates a list of functions, for performing one step of gradient descent at a given layer. The function will require as input the minibatch index, and to train an RBM you just need to iterate, calling the corresponding function on all minibatch indexes. |
Note that we return also the pre_sigmoid_activation of the layer. As it will turn out later, due to how Theano deals with optimization and stability this symbolic variable will be needed to write down a more stable graph (see details in the reconstruction cost function) | Note that we return also the pre-sigmoid activation of the layer. As it will turn out later, due to how Theano deals with optimizations, this symbolic variable will be needed to write down a more stable computational graph (see details in the reconstruction cost function) | def propup(self, vis): ''' This function propagates the visible units activation upwards to the hidden units Note that we return also the pre_sigmoid_activation of the layer. As it will turn out later, due to how Theano deals with optimization and stability this symbolic variable will be needed to write down a more st... |
Note that we return also the pre_sigmoid_activation of the layer. As it will turn out later, due to how Theano deals with optimization and stability this symbolic variable will be needed to write down a more stable graph (see details in the reconstruction cost function) | Note that we return also the pre_sigmoid_activation of the layer. As it will turn out later, due to how Theano deals with optimizations, this symbolic variable will be needed to write down a more stable computational graph (see details in the reconstruction cost function) | def propdown(self, hid): '''This function propagates the hidden units activation downwards to the visible units Note that we return also the pre_sigmoid_activation of the layer. As it will turn out later, due to how Theano deals with optimization and stability this symbolic variable will be needed to write down a more... |
Note that this function requires the pre-sigmoid activation. To understand why this is so you need to understand a bit about how Theano works. Once you express a computational graph in Theano, it will apply to it several optimizations which will lead to a faster and more stable computational graph. One of these optimiz... | Note that this function requires the pre-sigmoid activation as input. To understand why this is so you need to understand a bit about how Theano works. Whenever you compile a Theano function, the computational graph that you pass as input gets optimized for speed and stability. This is done by changing several parts of... | def get_reconstruction_cost(self, updates, pre_sigmoid_nv): """Approximation to the reconstruction error Note that this function requires the pre-sigmoid activation. To understand why this is so you need to understand a bit about how Theano works. Once you express a computational graph in Theano, it will apply to it s... |
numbers larger than 30. ( or even less) turn to 1. and numbers | numbers larger than 30. (or even less then that) turn to 1. and numbers | def get_reconstruction_cost(self, updates, pre_sigmoid_nv): """Approximation to the reconstruction error Note that this function requires the pre-sigmoid activation. To understand why this is so you need to understand a bit about how Theano works. Once you express a computational graph in Theano, it will apply to it s... |
and apply bot the log and sigmoid outside scan such that Theano | and apply both the log and sigmoid outside scan such that Theano | def get_reconstruction_cost(self, updates, pre_sigmoid_nv): """Approximation to the reconstruction error Note that this function requires the pre-sigmoid activation. To understand why this is so you need to understand a bit about how Theano works. Once you express a computational graph in Theano, it will apply to it s... |
T.sum(self.input*T.log(T.sigmoid(pre_sigmoid_nv)) + (1 - self.input)*T.log(1-T.sigmoid(pre_sigmoid_nv)), axis = 1)) | T.sum(self.input*T.log(T.nnet.sigmoid(pre_sigmoid_nv)) + (1 - self.input)*T.log(1-T.nnet.sigmoid(pre_sigmoid_nv)), axis = 1)) | def get_reconstruction_cost(self, updates, pre_sigmoid_nv): """Approximation to the reconstruction error Note that this function requires the pre-sigmoid activation as input. To understand why this is so you need to understand a bit about how Theano works. Whenever you compile a Theano function, the computational grap... |
def propdown(self.hid): | def propdown(self, hid): | def propdown(self.hid): '''This function propagates the hidden units activation downwards to the visible units''' return T.nnet.sigmoid(T.dot(hid,self.W.T) + self.vbias) |
DBN.test_DBN(pretraining_epochs = 1, training_epochs = 2, batch_size =300, output_folder = 'tmp_DBN_plots') | DBN.test_DBN(pretraining_epochs = 1, training_epochs = 2, batch_size =300) | def test_dbn(): t0=time.time() DBN.test_DBN(pretraining_epochs = 1, training_epochs = 2, batch_size =300, output_folder = 'tmp_DBN_plots') print >> sys.stderr, "test_mlp took %.3fs expected ??s in our buildbot"%(time.time()-t0) |
def gibbs_1(v0_sample, t): | def gibbs_1(v0_sample): | def gibbs_1(v0_sample, t): ''' This function implements one Gibbs step ''' |
outputs_taps = { 0 : [-1], 1 : [-1] } | outputs_taps = { 0 : [-1], 1 : [] } | def gibbs_1(v0_sample, t): ''' This function implements one Gibbs step ''' |
def test_RBM_option2(learning_rate=0.1, training_epochs = 20, | def test_RBM(learning_rate=0.1, training_epochs = 20, | def test_RBM_option2(learning_rate=0.1, training_epochs = 20, dataset='mnist.pkl.gz'): # Load the dataset f = gzip.open(dataset,'rb') train_set, valid_set, test_set = cPickle.load(f) f.close() def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.flo... |
rbm = RBM_option2(input = x, n_visible=28*28, n_hidden=500, numpy_rng= | rbm = RBM(input = x, n_visible=28*28, n_hidden=500, numpy_rng= | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
test_RBM_option2() | test_RBM() | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
class DeepNetwork() def pretrain( dataset ) def finetune() class SdA(): | class SdA(object): | def __init__(self, n_visible= 784, n_hidden= 500, corruption_level = 0.1,\ input = None, shared_W = None, shared_b = None): """ Initialize the dA class by specifying the number of visible units (the dimension d of the input ), the number of hidden units ( the dimension d' of the latent or hidden space ) and the corrupt... |
theano_rng = RandomStreams(rng.randint(2**30)) | theano_rng = RandomStreams(numpy_rng.randint(2**30)) | def __init__(self, numpy_rng, theano_rng = None, input = None, n_visible= 784, n_hidden= 500, W = None, bhid = None, bvis = None): """ Initialize the dA class by specifying the number of visible units (the dimension d of the input ), the number of hidden units ( the dimension d' of the latent or hidden space ) and the ... |
low = -numpy.sqrt(1./(n_visible)), \ high = numpy.sqrt(1./(n_visible)), \ | low = -numpy.sqrt(6./(n_hidden+n_visible)), \ high = numpy.sqrt(6./(n_hidden+n_visible)), \ | def __init__(self, n_visible= 784, n_hidden= 500, input= None): """ Initialize the dA class by specifying the number of visible units (the dimension d of the input ), the number of hidden units ( the dimension d' of the latent or hidden space ) and by giving a symbolic variable for the input. Such a symbolic variable i... |
def sgd_optimization_mnist( learning_rate=0.1, pretraining_epochs = 5, \ | def sgd_optimization_mnist( learning_rate=0.1, pretraining_epochs = 10, \ | def sgd_optimization_mnist( learning_rate=0.1, pretraining_epochs = 5, \ pretraining_lr = 0.1, training_epochs = 1000, dataset='mnist.pkl.gz'): """ Demonstrate stochastic gradient descent optimization for a multilayer perceptron This is demonstrated on MNIST. :param learning_rate: learning rate used (factor for the s... |
hidden_layers_sizes = [500, 500, 500], n_outs=10) | hidden_layers_sizes = [700, 700, 700], n_outs=10) | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
gW = T.grad(classifier.layers[i].cost, classifier.layers[i].W) gb = T.grad(classifier.layers[i].cost, classifier.layers[i].b) gb_prime = T.grad(classifier.layers[i].cost, \ classifier.layers[i].b_prime) | gW = T.grad(cost, classifier.layers[i].W) gb = T.grad(cost, classifier.layers[i].b) gb_prime = T.grad(cost, classifier.layers[i].b_prime) | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
cost = classifier.layers[i].cost print '---------------------------------------------------' print ' Layer : ',i print ' x : ', theano.pp(classifier.layers[i].x) print ' ' print ' tilde_x: ', theano.pp(classifier.layers[i].tilde_x) print ' ' print 'y :', theano.pp(classifier.layers[i].y) print ' ' print 'z: ', theano.p... | layer_update = theano.function([index], [cost], \ | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
x :train_set_x[index*batch_size:(index+1)*batch_size]}) | x :train_set_x[index*batch_size:(index+1)*batch_size-1]}) | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
print 'Pre-training layer %i, epoch %d'%(i,epoch),c, batch_index | print 'Pre-training layer %i, epoch %d'%(i,epoch),c | def shared_dataset(data_xy): data_x, data_y = data_xy shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX)) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX)) return shared_x, T.cast(shared_y, 'int32') |
low = numpy.sqrt(6./(n_hidden+n_out)), \ | low = -numpy.sqrt(6./(n_hidden+n_out)), \ | def __init__(self, input, n_in, n_hidden, n_out): """Initialize the parameters for the multilayer perceptron |
if (bus.dirname == pattern[0] and dev.filename == pattern[1]): | if (bus.contents.dirname == pattern[0] and dev.contents.filename == pattern[1]): | def list_devices(self, patterns=[{ 'idVendor': VID_SILABS, 'idProduct': PID_CP210x }]): """Yields a list of devices matching certain patterns. param patterns: This must be a list of dictionaries or pairs of string. Each device in the usb tree is matched against all pattern in the list. When an item is a dictionary al... |
class GamesHandler(UserHandler): | class GamesHandler(MainHandler): | def change_password(self, new_password): user = self.current_user() user.password = new_password user.authcode = None user.put() |
class TodayHandler(UserHandler): | class TodayHandler(MainHandler): | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() self.template_values['games'] = GroupGame.get(filter).widewalk() MainHandler.get(self,'games') |
class PoolHandler(UserHandler): | class PoolHandler(MainHandler): | def get(self, filter=''): self.get_template_values() self.submenu('alltips') if filter == '': filter = self.template_values['filtergames'][0].key() |
class ReferralHandler(UserHandler): | class ReferralHandler(MainHandler): | def get(self, filter = ''): self.get_template_values() self.submenu('scoreboard') if filter == '': filter = Fifa2010().tournament.key() groupgame = GroupGame.get(filter) self.template_values['groupgame'] = groupgame self.template_values['scoreboard'] = pool.scoreboard(LocalUser.all().fetch(100), Fifa2010().result, grou... |
if len(game.singlegames()) > 0: | if not game.upgroup() is None and str(game.upgroup().key()) == str(Fifa2010().groupstage.key()): | def submenu(self, page): subgames = GroupGame.everything().values() subgames.sort(key=GroupGame.groupstart) groupgames = [] for game in subgames: if len(game.singlegames()) > 0: groupgames.append(game) |
if filter == '': filter = Fifa2010().tournament.key() | if filter == '': filter = Fifa2010().groupstage.key() | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() self.template_values['games'] = GroupGame.get(filter).widewalk() MainHandler.get(self,'games') |
game_stored = SingleGame.all().filter('fifaId =',game['id']).get() | game_stored = SingleGame.all().filter('fifaId =',int(game['id'])).get() | def init_fifa_group_game(self, game): """Create game if not exists.""" group = self.init_fifa_group(game['group']) game_stored = SingleGame.all().filter('fifaId =',game['id']).get() if game_stored is None: game_stored = SingleGame(fifaId=int(game['id']),group=self.fifa_groupstage()) game_stored.time = game['time'] ga... |
@need_login | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() | |
tips = {} | tips = [] results = singlegame.results() | def singlegame_tips(self, singlegame, users): tips = {} for user in users: results = singlegame.results() for result in results: if results[result].user.key() == user.key(): tips[user.key()] = results[result] else: tips[user.key()] = {} return tips |
results = singlegame.results() for result in results: if results[result].user.key() == user.key(): tips[user.key()] = results[result] else: tips[user.key()] = {} | hastip = False if str(user.key()) in results: tips.append(results[str(user.key())]) else: tips.append({}) | def singlegame_tips(self, singlegame, users): tips = {} for user in users: results = singlegame.results() for result in results: if results[result].user.key() == user.key(): tips[user.key()] = results[result] else: tips[user.key()] = {} return tips |
'result':Fifa2010().result.singlegame_result(singlegame), | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() | |
print "XVZG" print self.template_values | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() | |
if not result.locked: return 0 | if not result.locked or not bet.locked: return 0 | def groupgame_result_point(bet, result): point = 0 if not result.locked: return 0 def count_orders(xs,ys): x_order_set = set((x,y) for x in xs for y in xs if xs.index(x) < xs.index(y)) y_order_set = set((x,y) for x in ys for y in ys if ys.index(x) < ys.index(y)) return len(x_order_set.intersection(y_order_set)) retur... |
teams = {} for team in self.all().fetch(MAX_ITEMS): teams[str(team.key())] = team return teams | games = {} for game in self.all().fetch(MAX_ITEMS): games[str(game.key())] = game return games | def everything(self): teams = {} for team in self.all().fetch(MAX_ITEMS): teams[str(team.key())] = team return teams |
return GroupGame.everything()[self.group_key()] | return GroupGame.everything()[str(self.group_key())] | def group(self): try: return GroupGame.everything()[self.group_key()] except KeyError: return None |
print "everything" | def everything(self): print "everything" teams = {} for team in self.all().fetch(MAX_ITEMS): teams[str(team.key())] = team return teams | |
def save_current(): | def save_current(self): | def save_current(): return self.save(self.current_user()) |
self.redirect('/') | self.redirect(self.request.uri) | def login_local(self, email, password): self.loggedin_user = LocalUser.all().filter('email = ',email).filter('password = ',password).get() if self.loggedin_user is None or password == '': self.set_session_message(_('Failed to log you in, try it again!')) self.redirect('/') else: self.set_session_email(self.loggedin_use... |
@need_login | def get(self, filter=''): self.get_template_values() if filter == '': filter = Fifa2010().tournament.key() self.template_values['games'] = GroupGame.get(filter).widewalk() MainHandler.get(self,'games') | |
self.save(self.current_user()) | self.save_current() | def post(self, *args): if GamesHandler.post(self): return action = self.request.get('action') if 'mytips/save' == action: self.save(self.current_user()) self.redirect(self.request.uri) else: return False return True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.