rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print "Status string: %s, players: %s" % (status_string, self.players)
def update_players_list(self): try: self.connection.request("GET", "/status?game_id=%s" % self.game_id) status_string = self.connection.getresponse().read() # TODO: Parse status report and put it into a GameStatus object status, players, size = status_string.split('|')[:3] self.players = players.split(",") print "Statu...
self.title_fnt = self.loader.load_font("KLEPTOMA.TTF", 60)
self.title_fnt = self.loader.load_font("KLEPTOMA.TTF", 50)
def __init__(self): self.loader = Loader() self.desk = self.loader.load_image("back.png") self.back = self.desk.copy()
t = ["Empate!","Ganaste!","Perdiste!"]
t = ["Empate!","Jugador Uno!","Jugador Dos!"] if t[result] != t[0]: self._title('Bien',y - 80,x)
def render_gameover(self,result): self.back.blit(self.desk,(0,0)) y = 275 x = 300 t = ["Empate!","Ganaste!","Perdiste!"] self._title(t[result],y,x); y+=50 self._text("Pulsa el raton para volver a jugar!",y,x)
elif event.key == K_F11: pygame.display.toggle_fullscreen()
def main_loop(self): clock = pygame.time.Clock()
self.mixer_internal = PREFS["mixer_internal"]
self.mixer_internal = bool(int(PREFS["mixer_internal"]))
def __init__(self): """ Constructor """ gtk.StatusIcon.__init__(self)
self.last_id = self.notify.Notify('audiovolume', self.last_id, icon, '', body, [], hints, duration * 1000)
self.last_id = self.notify.Notify('volume', self.last_id, icon, self.title, body, [], hints, duration * 1000)
def show(self, icon, message, duration, volume): """ Show the notification """ body = self.format(message, volume) hints = {"urgency": dbus.Byte(0), "desktop-entry": dbus.String("volti")} if self.main.notify_position and self.server_capable: hints["x"], hints["y"] = self.get_position() self.last_id = self.notify.Notify...
if term == "linux":
if term == "linux" or "":
def find_term(self): term = os.getenv("TERM") if term == "linux": if which("gconftool-2"): term = Popen(["gconftool-2", "-g", "/desktop/gnome/applications/terminal/exec"], stdout=PIPE).communicate()[0].strip() else: term = 'xterm' else: if term == "rxvt" and not which(term): term = "urxvt" return term
x1,y1 = apply_context_transforms(x1,y1) x2,y2 = apply_context_transforms(x2,y2)
x1,y1 = self.apply_context_transforms(x1,y1) x2,y2 = self.apply_context_transforms(x2,y2)
def line_message(self, x1,y1,x2,y2): x1+=random()*self.MaxNoise-self.MaxNoise/2 y1+=random()*self.MaxNoise-self.MaxNoise/2 x2+=random()*self.MaxNoise-self.MaxNoise/2 y2+=random()*self.MaxNoise-self.MaxNoise/2 x1,y1 = apply_context_transforms(x1,y1) x2,y2 = apply_context_transforms(x2,y2)
self.ReplayInitLog()
def __init__(self, config=None): self.localDevice = True self.remoteDevice = None if config: if "server" in config: if not "port" in config: config["port"]=50000
buf = ""
buf2 = ""
def ReplayInitLog(self): # find our device self.usbdev=None for bus in usb.busses(): for dev in bus.devices: if dev.idVendor == 0x3333: self.usbdev = dev # was it found? if self.usbdev is None: raise ValueError('Device (3333:5555) not found')
buf+=chr(int(byte,16)) handle.controlMsg(reqType,req,buf,value,index)
buf2+=chr(int(byte,16)) handle.controlMsg(reqType,req,buf2,value,index)
def ReplayInitLog(self): # find our device self.usbdev=None for bus in usb.busses(): for dev in bus.devices: if dev.idVendor == 0x3333: self.usbdev = dev # was it found? if self.usbdev is None: raise ValueError('Device (3333:5555) not found')
content = serialize('json', object)
content = serialize('json', data)
def __init__(self, data, *args, **kwargs): content = None; if isinstance(data, QuerySet): content = serialize('json', object) else: content = json.dumps(data, indent=2, cls=json.DjangoJSONEdncoder, ensure_ascii=False) super(JsonResponse, self).__init__(content, *args, content_type='application/json', **kwargs)
content = json.dumps(data, indent=2, cls=json.DjangoJSONEdncoder,
content = simplejson.dumps(data, indent=2, cls=json.DjangoJSONEncoder,
def __init__(self, data, *args, **kwargs): content = None; if isinstance(data, QuerySet): content = serialize('json', data) else: content = json.dumps(data, indent=2, cls=json.DjangoJSONEdncoder, ensure_ascii=False) kwargs['content_type'] = 'application/json' super(JsonResponse, self).__init__(content, *args, **kwargs)
url = "%s/?all
url = "%s?all
def edit_transaction(request, transaction=None): load_from_database = True if transaction == None: transaction = Transaction(date=datetime.date.today(), auto_generated=False) load_from_database = False else: transaction = get_object_or_404(Transaction, id=int(transaction)) splits = [] commit = True # Is...
url = "%s/
url = "%s
def edit_transaction(request, transaction=None): load_from_database = True if transaction == None: transaction = Transaction(date=datetime.date.today(), auto_generated=False) load_from_database = False else: transaction = get_object_or_404(Transaction, id=int(transaction)) splits = [] commit = True # Is...
if account is None and not request.GET.has_key('all'): include_auto = False
if account is None: include_auto = False if request.GET.has_key('all'): if request.GET['all'] != '0': include_auto = True else: include_auto = False
def ledger(request, account=None): if account: account = Account.objects.get(id=account) title = account.name else: title = "General Ledger" transactions = [] transaction_filter = {} include_auto = True if account is None and not request.GET.has_key('all'): include_auto = False if not include_auto: transaction_filt...
return HttpResponseRedirect('/finance/accounts/')
return HttpResponseRedirect(reverse('chezbob.finance.views.account_list'))
def redirect(request): return HttpResponseRedirect('/finance/accounts/')
url = "/finance/ledger/?all
url = "%s/?all
def edit_transaction(request, transaction=None): load_from_database = True if transaction == None: transaction = Transaction(date=datetime.date.today(), auto_generated=False) load_from_database = False else: transaction = get_object_or_404(Transaction, id=int(transaction)) splits = [] commit = True # Is...
url = "/finance/ledger/
url = "%s/
def edit_transaction(request, transaction=None): load_from_database = True if transaction == None: transaction = Transaction(date=datetime.date.today(), auto_generated=False) load_from_database = False else: transaction = get_object_or_404(Transaction, id=int(transaction)) splits = [] commit = True # Is...
_errors = [] _warnings = [] _notes = []
def __init__(self, data, *args, **kwargs): content = None; if isinstance(data, QuerySet): content = serialize('json', object) else: content = json.dumps(data, indent=2, cls=json.DjangoJSONEdncoder, ensure_ascii=False) super(JsonResponse, self).__init__(content, *args, content_type='application/json', **kwargs)
return render_to_response('chezbob/bob_message.html', m)
return render_to_response('chezbob/base.html', m)
def error(m): return render_to_response('chezbob/bob_message.html', m)
inventory = inventory_summary[item.bulkid]
if item.bulkid in inventory_summary: inventory = inventory_summary[item.bulkid] else: inventory = {'activity': False, 'date': None, 'old_count': 0, 'purchases': 0, 'sales': 0}
def take_inventory(request, date): date = parse_date(date) show_all= request.GET.has_key('all') # If a POST request was submitted, apply any updates to the inventory data # in the database before rendering the response. if request.method == 'POST': if request.POST.get('session_key') != get_session_key(request): raise...
tags.update({'source':'lukr', 'source:date':'2010-09-18'})
tags.update({'source':'lukr', 'source:date':'2010-09-17'})
def translateAttributes(attrs): if not attrs: return tags = {} #tags on all paths tags.update({'source':'lukr', 'source:date':'2010-09-18'}) tags.update({'lukr:raw':str(attrs).replace("&apos", "")}) #all lukr original tags, including the unique ObjectId. tags.update({'lukr:highway':'footway'}) #remove the lukr: prefi...
tags = {'width':attrs['BREIDD'].lstrip()}
tags.update({'width':attrs['BREIDD'].lstrip()})
def translateAttributes(attrs): if not attrs: return tags = {} #tags on all paths tags.update({'source':'lukr', 'source:date':'2010-09-18'}) tags.update({'lukr:raw':str(attrs).replace("&apos", "")}) #all lukr original tags, including the unique ObjectId. tags.update({'lukr:highway':'footway'}) #remove the lukr: prefi...
None)
inverted_index[i])
def train_aux_classifiers(self, ds, auxtasks, classifier_trainer, inverted_index=None): dim = ds.dim w_data = [] row = [] col = [] original_instances = ds.instances[ds._idx] print "Run joblib.Parallel" res = Parallel(n_jobs=-1, verbose=1)( delayed(_train_aux_classifier)(i, auxtask, original_instances, dim, classifier_t...
classifier_trainer, inverted_index=None):
classifier_trainer, occurances=None):
def _train_aux_classifier(i, auxtask, original_instances, dim, classifier_trainer, inverted_index=None): """Trains a single auxiliary classifier. Parameters ---------- i : int The index of the auxiliary task. auxtask : tuple of ints The auxiliary task. original_instances : array, dtype=bolt.sparsedtype The unlabeled i...
if inverted_index is None:
if occurances is None:
def _train_aux_classifier(i, auxtask, original_instances, dim, classifier_trainer, inverted_index=None): """Trains a single auxiliary classifier. Parameters ---------- i : int The index of the auxiliary task. auxtask : tuple of ints The auxiliary task. original_instances : array, dtype=bolt.sparsedtype The unlabeled i...
occurances = inverted_index[j]
def _train_aux_classifier(i, auxtask, original_instances, dim, classifier_trainer, inverted_index=None): """Trains a single auxiliary classifier. Parameters ---------- i : int The index of the auxiliary task. auxtask : tuple of ints The auxiliary task. original_instances : array, dtype=bolt.sparsedtype The unlabeled i...
trainer = structlearn.ElasticNetTrainer(0.00001, 0.85, 10**6.0), strategy = structlearn.HadoopTrainingStrategy()
trainer = auxtrainer.ElasticNetTrainer(0.00001, 0.85, 10**6.0), strategy = auxstrategy.HadoopTrainingStrategy()
def train(): maxlines = 50000 argv = sys.argv[1:] slang = argv[0] tlang = argv[1] fname_s_train = argv[2] fname_s_unlabeled = argv[3] fname_t_unlabeled = argv[4] fname_dict = argv[5] s_voc = vocabulary(fname_s_train, fname_s_unlabeled, mindf = 2, maxlines = maxlines) t_voc = vocabulary(fname_t_unlabeled, mindf = 2, ...
terms = [(self.s_ivoc[ws],self.t_ivoc[wt]) for ws,wt in pivots] for term in terms[:50]: print term
def select_pivots(self, m, phi):
trainer = auxtrainer.ElasticNetTrainer(0.00001, 0.85, 10**6.0),
trainer = auxtrainer.ElasticNetTrainer(0.00001, 0.85, 10**6.0)
def train(): maxlines = 50000 argv = sys.argv[1:] slang = argv[0] tlang = argv[1] fname_s_train = argv[2] fname_s_unlabeled = argv[3] fname_t_unlabeled = argv[4] fname_dict = argv[5] s_voc = vocabulary(fname_s_train, fname_s_unlabeled, mindf = 2, maxlines = maxlines) t_voc = vocabulary(fname_t_unlabeled, mindf = 2, ...
t = unichr(n)
t = chr(n)
def test_bmp(self): for n in range(0,0x10000): # Just check that it doesn't throw an exception t = unichr(n) unidecode(t)
''),
'A'), ('\U0001d5c4\U0001d5c6/\U0001d5c1', 'km/h'),
def test_specific(self):
for input, output in TESTS: self.failUnlessEqual(unidecode(input), output)
for instr, output in TESTS: self.failUnlessEqual(unidecode(instr), output)
def test_specific(self):
scipy.optimize.fmin_l_bfgs_b(self.error_func,
scipy.optimize.fmin_l_bfgs_b(error_func,
def _solve(self, error_func, job_server=None): """ Optimize the parameters of the function. """
if polished_error < self.population_errors[best_ind]:
if polished_error < self.best_error:
def _solve(self, error_func, job_server=None): """ Optimize the parameters of the function. """
tmp = {row.index: { 'query': getCurrentUsername(context),
mt = getToolByName(context, 'portal_membership') user = mt.getAuthenticatedMember() username = 'Anonymous User' if user: username = user.getUserName() return {row.index: { 'query': username,
def _currentUser(context, row): tmp = {row.index: { 'query': getCurrentUsername(context), }, } return tmp
return tmp
def _currentUser(context, row): tmp = {row.index: { 'query': getCurrentUsername(context), }, } return tmp
row.values = my_date
row = Row(index=row.index, operator=row.operator, values=my_date)
def _lessThanRelativeDate(context, row): values = int(row.values) now = DateTime() my_date = now + values my_date = my_date.earliestTime() row.values = my_date return _lessThan(context, row)
row.values = my_date
row = Row(index=row.index, operator=row.operator, values=my_date)
def _moreThanRelativeDate(context, row): values = int(row.values) now = DateTime() my_date = now + values my_date = my_date.latestTime() row.values = my_date return _largerThan(context, row)
if obj and hasattr(obj, 'getPhysicalPath'): row.values = '/'.join(obj.getPhysicalPath()) return _path(context, row)
row = Row(index=row.index, operator=row.operator, values='/'.join(obj.getPhysicalPath()))
def _relativePath(context, row): t = len([x for x in row.values.split('/') if x]) obj = context for x in xrange(t): obj = aq_parent(obj) if obj and hasattr(obj, 'getPhysicalPath'): row.values = '/'.join(obj.getPhysicalPath()) return _path(context, row) row.values = '/'.join(obj.getPhysicalPath()) return _path(contex...
row.values = '/'.join(obj.getPhysicalPath())
def _relativePath(context, row): t = len([x for x in row.values.split('/') if x]) obj = context for x in xrange(t): obj = aq_parent(obj) if obj and hasattr(obj, 'getPhysicalPath'): row.values = '/'.join(obj.getPhysicalPath()) return _path(context, row) row.values = '/'.join(obj.getPhysicalPath()) return _path(contex...
def getCurrentUsername(context): mt = getToolByName(context, 'portal_membership') user = mt.getAuthenticatedMember() if user: return user.getUserName() return ''
def _relativePath(context, row): t = len([x for x in row.values.split('/') if x]) obj = context for x in xrange(t): obj = aq_parent(obj) if obj and hasattr(obj, 'getPhysicalPath'): row.values = '/'.join(obj.getPhysicalPath()) return _path(context, row) row.values = '/'.join(obj.getPhysicalPath()) return _path(contex...
if 'form.button.addcriteria' or 'removecriteria' in form:
if 'form.button.addcriteria' in form or 'removecriteria' in form:
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """A custom implementation for the widget form processing.""" value = form.get(field.getName()) # check if form.button.addcriteria is in request, # this only happends when javascript is disabled if 'form.button...
data = { 'index': 'modified', 'values': ['2009/08/12', '2009/08/14'], }
data = Row(index='modified', operator='_between', values=['2009/08/12', '2009/08/14'])
def test__between(self): data = { 'index': 'modified', 'values': ['2009/08/12', '2009/08/14'], } parsed = queryparser._between(None, data) expected = {'modified': {'query': ['2009/08/12', '2009/08/14'], 'range': 'minmax'}} self.assertEqual(parsed, expected)
import pdb; pdb.set_trace( )
def test_string_equality(self): registry = self.portal.portal_registry prefix = "plone.app.collection.operation.string.is" import pdb; pdb.set_trace( ) assert prefix+'.title' in registry self.assertEqual(registry[prefix+".title"], "equals") self.assertEqual(registry[prefix+".description"], 'Tip: you can use * to autoc...
sortables = result.get('plone.app.collection.field')
sortables = result['sortable']
def test_sortable_indexes(self): registry = self.createRegistry(td.minimal_missing_operator_xml) reader = ICollectionRegistryReader(registry) result = reader.parseRegistry() result = reader.mapOperations(result) result = reader.mapSortableIndexes(result) sortables = result.get('plone.app.collection.field')
assert len(sortables)
assert len(sortables) > 0
def test_sortable_indexes(self): registry = self.createRegistry(td.minimal_missing_operator_xml) reader = ICollectionRegistryReader(registry) result = reader.parseRegistry() result = reader.mapOperations(result) result = reader.mapSortableIndexes(result) sortables = result.get('plone.app.collection.field')
assert not field['sortable']
assert field['sortable'] == True
def test_sortable_indexes(self): registry = self.createRegistry(td.minimal_missing_operator_xml) reader = ICollectionRegistryReader(registry) result = reader.parseRegistry() result = reader.mapOperations(result) result = reader.mapSortableIndexes(result) sortables = result.get('plone.app.collection.field')
self.parser = queryparser.QueryParser(None, None)
self.parser = queryparser.QueryParser(MockSite(), None)
def setUp(self): super(TestQueryParserBase, self).setUp()
print 'value = %s' % value
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """A custom implementation for the widget form processing.""" value = form.get(field.getName()) print 'value = %s' % value self.value = value #if 'form.button.addcriteria' in form: if value: return value, {}
return np.exp(-1.0/sigma2 * projection_frobenius_norm_matrix)
return np.exp(-1.0/sigma2 * projection_frobenius_norm_matrix*projection_frobenius_norm_matrix)
def compute_tensorial_kernel(X, Y=None, sigma2=1.0): """Compute tensorial RBF kernel between two datasets. """ if Y is None: projection_frobenius_norm_matrix = compute_projection_frobenius_norm_train(X) else: projection_frobenius_norm_matrix = compute_projection_frobenius_norm_test(X, Y) return np.exp(-1.0/sigma2 * pro...
W_Y = Vh_X.T W_X = Vh_Y.T
W_X = Vh_X.T W_Y = Vh_Y.T
def compute_projection_frobenius_norm(U_s_Vh_list_X, U_s_Vh_list_Y): """Compute the projection Frobenius norm between two tensors. """ projection_frobenius_norm = 0.0 for i in range(len(U_s_Vh_list_X)): U_X, s_X, Vh_X = U_s_Vh_list_X[i] U_Y, s_Y, Vh_Y = U_s_Vh_list_Y[i] if U_X.shape[0] > Vh_X.shape[1]: W_X = U_X W_Y = ...
def ndim_meshgrid(*arrs): """n-dimensional analogue to numpy.meshgrid""" arrs = tuple(reversed(arrs)) lens = map(len, arrs) dim = len(arrs) sz = 1 for s in lens: sz*=s ans = [] for i, arr in enumerate(arrs): slc = [1]*dim slc[i] = lens[i] arr2 = asarray(arr).reshape(slc) for j, sz in enumerate(lens): if j!=i: arr2 = ...
def ndim_meshgrid(*arrs): """n-dimensional analogue to numpy.meshgrid""" arrs = tuple(reversed(arrs)) #edit lens = map(len, arrs) dim = len(arrs) sz = 1 for s in lens: sz*=s ans = [] for i, arr in enumerate(arrs): slc = [1]*dim slc[i] = lens[i] arr2 = asarray(arr).reshape(slc) for j, sz in enumerate(lens): if j!=i: ...
takes a list of lists of equal length q = [[1,2],[3,4]]
takes a list of lists of arbitrary length q = [[1,2],[3,4]]
def gridpts(q): """
q = list(reversed(q)) w = ndim_meshgrid(*q) for i in range(len(q)): q[i] = list( w[i].reshape(w[i].size) ) q = zip(*q) return [list(i) for i in q]
w = [[] for i in range(len(q[-1]))] for j in range(len(q)-1,-1,-1): for k in range(len(q[j])): for l in range(k*len(w)/len(q[j]), (k+1)*len(w)/len(q[j])): w[l].append(q[j][k]) if j: w += [i[:] for i in w[:]*(len(q[j-1])-1)] return [list(reversed(w[i])) for i in range(len(w))]
def gridpts(q): """
if len(cand)%2: return cand[len(cand)/2], cand[len(cand)/2] return cand[len(cand)/2], cand[len(cand)/2 - 1]
best = [cand[len(cand)/2], n/cand[len(cand)/2]] best.sort(reverse=True) return tuple(best)
def best_dimensions(n): "get the 'best' dimensions (n x m) for arranging plots" allfactors = list(factor(n)) from numpy import product cand = [1] + [product(allfactors[:i+1]) for i in range(len(allfactors))] if len(cand)%2: return cand[len(cand)/2], cand[len(cand)/2] return cand[len(cand)/2], cand[len(cand)/2 - 1]
def derivative(self,coeffs): """evaluates n-dimensional Rosenbrock derivative for a list of coeffs minimum is f'(x)=[0.0]*n at x=[1.0]*n; x must have len >= 2""" l = len(coeffs) x = [0]*l x[:l]=coeffs x = asarray(x) xm = x[1:-1] xm_m1 = x[:-2] xm_p1 = x[2:] der = zeros_like(x) der[1:-1] = 200*(xm-xm_m1**2) - 400*(xm_...
# def forward(self,pts):
reload(south.signals)
def load_post_syncdb_signals(): """ This is a duplicate from Django syncdb management command. This code imports any module named 'management' in INSTALLED_APPS. The 'management' module is the preferred way of listening to post_syncdb signals. """ unload_post_syncdb_signals() # If south is available, we should reload...
padded = "\x02%s\x00%s" % ("\xFF" * (128 - (len(toEncrypt)) -2), toEncrypt)
padded = "\x00\x02%s\x00%s" % ("\xFF" * (128 - (len(toEncrypt)) -3), toEncrypt)
def usage(): print "Usage:", sys.argv[0], print "[-p pin][--pin=pin]", print "[-c lib][--lib=lib]", print "[-S][--sign]", print "[-d][--decrypt]", print "[-h][--help]",
def initToken(self, pin, label): """ C_InitToken """ rv = self.lib.C_InitToken(self.session, pin, label) if rv != CKR_OK: raise PyKCS11Error(rv)
def logout(self): """ C_Logout """ rv = self.lib.C_Logout(self.session) if rv != CKR_OK: raise PyKCS11Error(rv)
waml.append_waml(blip.insert_inline_blip(match.end()-2),
waml.append_waml(blip.insert_inline_blip(match.end()),
def OnBlipSubmitted(event, wavelet): game = WaveGame.all().filter('waveid =', wavelet.wave_id).get() if not game: return blip = event.blip com = Commander(game, blip.creator) for match in COMMAND_RE.finditer(blip.text): result = com.command(match.group('commands')) if result is not False: # Swap brackets for parens and...
self.xorg_conf.makeSection('Device', identifier='Configured Video Device') self.xorg_conf.addOption('Device', 'Driver', 'vboxvideo', position=0)
def customiseConfig(self): # set DefaultDepth to 24; X.org does not work otherwise self.xorg_conf.makeSection('Screen', identifier='Default Screen') self.xorg_conf.addOption('Screen', 'DefaultDepth', '24', position=0, prefix='')
self.xorg_conf.addOption('Screen', 'DefaultDepth', '24', position=0, prefix='')
self.xorg_conf.addOption('Screen', 'Device', 'Configured Video Device', position=0)
def customiseConfig(self): # set DefaultDepth to 24; X.org does not work otherwise self.xorg_conf.makeSection('Screen', identifier='Default Screen') self.xorg_conf.addOption('Screen', 'DefaultDepth', '24', position=0, prefix='')
self.xorg_conf.makeSubSection('Screen', 'Display', position=0) self.xorg_conf.addSubOption('Screen', 'Display', 'Depth', value='24', position=0) self.xorg_conf.addSubOption('Screen', 'Display', 'Modes', value='"1024x600"', position=0)
self.xorg_conf.makeSection('ServerLayout', identifier='Default Layout') self.xorg_conf.addOption('ServerLayout', 'Screen', 'Default Screen', position=0)
def customiseConfig(self): # set DefaultDepth to 24; X.org does not work otherwise self.xorg_conf.makeSection('Screen', identifier='Default Screen') self.xorg_conf.addOption('Screen', 'DefaultDepth', '24', position=0, prefix='')
r".*\.js", r".*\.py", r".*\.json", r".*\.sh", r".*\.rb",
r".*\.js", r".*\.py", r".*\.sh", r".*\.rb", r".*\.pl", r".*\.pm",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
r".*\.java", r".*\.mk", r".*\.am", r".*\.txt",
r".*\.java", r".*\.mk", r".*\.am",
def __init__(self, *args, **kwargs): raise NotImplementedException() # TODO(joi) Implement.
return RunShellWithReturnCode(['svn', 'diff'] + files + args, print_output=True)[1]
root = GetRepositoryRoot() cmd = ['svn', 'diff'] cmd.extend([os.path.join(root, x) for x in files]) cmd.extend(args) return RunShellWithReturnCode(cmd, print_output=True)[1]
def CMDdiff(args): """Diffs all files in the changelist or all files that aren't in a CL.""" files = None if args: change_info = ChangeInfo.Load(args.pop(0), GetRepositoryRoot(), True, True) files = change_info.GetFileNames() else: files = GetFilesNotInCL() return RunShellWithReturnCode(['svn', 'diff'] + files + args, ...
try: def WebKitRevision(options, opt, value, parser): if not hasattr(options, 'sub_rep'): options.sub_rep = [] if parser.rargs and not parser.rargs[0].startswith('-'): options.sub_rep.append('third_party/WebKit@%s' % parser.rargs.pop(0)) else: options.sub_rep.append('third_party/WebKit') group.add_option("-W", "--webk...
def TryChange(argv, file_list, swallow_exception, prog=None, extra_epilog=None): """ Args: argv: Arguments and options. file_list: Default value to pass to --file. swallow_exception: Whether we raise or swallow exceptions. """ # Parse argv parser = optparse.OptionParser(usage=USAGE, version=__version__, prog=prog) epil...
assert re.match(r'^[a-z]+://[a-z0-9\.-_]+[a-z](|:[0-9]+)$', self.host), (
assert re.match(r'^[a-z]+://[a-z0-9\.-_]+(|:[0-9]+)$', self.host), (
def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False, account_type=AUTH_ACCOUNT_TYPE): """Creates a new HttpRpcServer.
try: import simplejson except ImportError: parser.error('simplejson library is missing, please install.')
if json is None: parser.error('json or simplejson library is missing, please install.')
def WebKitRevision(options, opt, value, parser): if not hasattr(options, 'sub_rep'): options.sub_rep = [] if parser.rargs and not parser.rargs[0].startswith('-'): options.sub_rep.append('third_party/WebKit@%s' % parser.rargs.pop(0)) else: options.sub_rep.append('third_party/WebKit')
contents = simplejson.loads(urllib.urlopen(api_url).read())
contents = json.loads(urllib.urlopen(api_url).read())
def WebKitRevision(options, opt, value, parser): if not hasattr(options, 'sub_rep'): options.sub_rep = [] if parser.rargs and not parser.rargs[0].startswith('-'): options.sub_rep.append('third_party/WebKit@%s' % parser.rargs.pop(0)) else: options.sub_rep.append('third_party/WebKit')
return subprocess.Popen(args, **kwargs)
try: return subprocess.Popen(args, **kwargs) except OSError, e: if e.errno == errno.EAGAIN and sys.platform == 'cygwin': raise Error( 'Visit ' 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure to ' 'learn how to fix this error; you need to rebase your cygwin dlls') raise
def Popen(args, **kwargs): """Calls subprocess.Popen() with hacks to work around certain behaviors. Ensure English outpout for svn and make it work reliably on Windows. """ logging.debug(u'%s, cwd=%s' % (u' '.join(args), kwargs.get('cwd', ''))) if not 'env' in kwargs: # It's easier to parse the stdout if it is always ...
file_list = None
file_list = []
def TryChange(change_info, args, swallow_exception): """Create a diff file of change_info and send it to the try server.""" try: import trychange except ImportError: if swallow_exception: return 1 ErrorExit("You need to install trychange.py to use the try server.") trychange_args = [] if change_info: trychange_args.ex...
content = ""
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same...
svn_path = url_path + "/" + filename content, rc = RunShellWithReturnCode(["svn", "cat", svn_path]) if not rc:
for _ in range(5): content = "" try: content_array = [] svn_path = url_path + "/" + filename SVN.RunAndFilterOutput(['cat', svn_path, '--non-interactive'], '.', False, False, content_array.append) content = '\n'.join(content_array) break except gclient_utils.Error, e: if content_array[0].startswith( 'svn: Can\'t ge...
def GetCachedFile(filename, max_age=60*60*24*3, use_root=False): """Retrieves a file from the repository and caches it in GetCacheDir() for max_age seconds. use_root: If False, look up the arborescence for the first match, otherwise go directory to the root repository. Note: The cache will be inconsistent if the same...
stderr=subprocess.STDOUT, shell=use_shell,
stderr=subprocess.STDOUT, shell=use_shell, env=env,
def RunShellWithReturnCode(command, print_output=False): """Executes a command and returns the output and the return code.""" # Use a shell for subcommands on Windows to get a PATH search, and because svn # may be a batch file. use_shell = sys.platform.startswith("win") p = subprocess.Popen(command, stdout=subprocess.P...
execfile("drover.properties")
f = open("drover.properties") exec(f) f.close()
def drover(options, args): revision = options.revert or options.merge # Initialize some variables used below. They can be overwritten by # the drover.properties file. BASE_URL = "svn://svn.chromium.org/chrome" TRUNK_URL = BASE_URL + "/trunk/src" BRANCH_URL = BASE_URL + "/branches/$branch/src" SKIP_CHECK_WORKING = True...
allows the capture of a overall "revision" for the source tree that can
allows the capture of an overall "revision" for the source tree that can
def PrintRevInfo(self): """Output revision info mapping for the client and its dependencies. This allows the capture of a overall "revision" for the source tree that can be used to reproduce the same tree in the future. The actual output contains enough information (source paths, svn server urls and revisions) that it ...
NOTE: Unlike RunOnDeps this does not require a local checkout and is run on the Pulse master. It MUST NOT execute hooks.
def PrintRevInfo(self): """Output revision info mapping for the client and its dependencies. This allows the capture of a overall "revision" for the source tree that can be used to reproduce the same tree in the future. The actual output contains enough information (source paths, svn server urls and revisions) that it ...
entries_deps_content[name] = gclient_scm.scm.SVN.Capture( ["cat", "%s/%s@%s" % (url, self._options.deps_file, rev)], os.getcwd())
deps_file = solution.get("deps_file", self._options.deps_file) if '/' in deps_file or '\\' in deps_file: raise gclient_utils.Error('deps_file name must not be a path, just a ' 'filename.') try: deps_content = gclient_utils.FileRead( os.path.join(self._root_dir, name, deps_file)) except IOError, e: if e.errno != errno.E...
def GetURLAndRev(name, original_url): url, revision = gclient_utils.SplitUrlRevision(original_url) if not revision: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: scm = gclient_scm.CreateSCM(solution["url"], self._root_dir, name) return (url, scm.revinfo(self._options, [], None)) else...
print(";\n\n".join(["%s: %s" % (x, entries[x])
print(";\n".join(["%s: %s" % (x, entries[x])
def GetURLAndRev(name, original_url): url, revision = gclient_utils.SplitUrlRevision(original_url) if not revision: if revision_overrides.has_key(name): return (url, revision_overrides[name]) else: scm = gclient_scm.CreateSCM(solution["url"], self._root_dir, name) return (url, scm.revinfo(self._options, [], None)) else...
'breakpad', 'datetime', 'gclient_utils', 'getpass', 'logging',
'breakpad', 'datetime', 'errno', 'gclient_utils', 'getpass', 'logging',
def testMembersChanged(self): members = [ 'EscapeDot', 'GIT', 'GuessVCS', 'HELP_STRING', 'InvalidScript', 'NoTryServerAccess', 'PrintSuccess', 'SCM', 'SVN', 'TryChange', 'USAGE', 'breakpad', 'datetime', 'gclient_utils', 'getpass', 'logging', 'optparse', 'os', 'posixpath', 'scm', 'shutil', 'sys', 'tempfile', 'urllib', ]...
'GenerateDiff', 'GetFileNames', 'GetLocalRoot',
'GenerateDiff', 'GetFileNames',
def testMembersChanged(self): members = [ 'AutomagicalSettings', 'GclStyleSettings', 'GclientStyleSettings', 'GetCodeReviewSetting', 'ReadRootFile', 'GenerateDiff', 'GetFileNames', 'GetLocalRoot', ] # If this test fails, you should add the relevant test. self.compareMembers(trychange.SVN, members)
self.assertEqual(svn.GetLocalRoot(), self.fake_root)
self.assertEqual(svn.checkout_root, self.fake_root)
def testBasic(self): trychange.scm.SVN.GetCheckoutRoot(self.fake_root).AndReturn(self.fake_root) trychange.scm.SVN.GenerateDiff(['foo.txt', 'bar.txt'], self.fake_root, full_move=True, revision=None).AndReturn('A diff') trychange.scm.SVN.GetEmail(self.fake_root).AndReturn('georges@example.com') self.mox.ReplayAll() svn ...
'GenerateDiff', 'GetFileNames', 'GetLocalRoot',
'GenerateDiff', 'GetFileNames',
def testMembersChanged(self): members = [ 'AutomagicalSettings', 'GclStyleSettings', 'GclientStyleSettings', 'GetCodeReviewSetting', 'ReadRootFile', 'GenerateDiff', 'GetFileNames', 'GetLocalRoot', ] # If this test fails, you should add the relevant test. self.compareMembers(trychange.GIT, members)
self.assertEqual(git.GetLocalRoot(), self.fake_root)
self.assertEqual(git.checkout_root, self.fake_root)
def testBasic(self): trychange.scm.GIT.GetCheckoutRoot(self.fake_root).AndReturn(self.fake_root) trychange.scm.GIT.GenerateDiff(self.fake_root, full_move=True, branch=None).AndReturn('A diff') trychange.scm.GIT.GetPatchName(self.fake_root).AndReturn('bleh-1233') trychange.scm.GIT.GetEmail(self.fake_root).AndReturn('geo...
if sys.stdout.isatty():
if 'CHROME_HEADLESS' not in os.environ:
def Main(argv): """Doesn't parse the arguments here, just find the right subcommand to execute.""" try: # Do it late so all commands are listed. CMDhelp.usage = ('\n\nCommands are:\n' + '\n'.join([ ' %-10s %s' % (fn[3:], Command(fn[3:]).__doc__.split('\n')[0].strip()) for fn in dir(sys.modules[__name__]) if fn.startsw...
if last_tb:
if last_tb and sys.last_type is not KeyboardInterrupt:
def CheckForException(): last_tb = getattr(sys, 'last_traceback', None) if last_tb: SendStack(''.join(traceback.format_tb(last_tb)))
logging.warning(str(e))
logging.info(str(e))
def _SendChangeHTTP(options): """Send a change to the try server using the HTTP protocol.""" if not options.host: raise NoTryServerAccess('Please use the --host option to specify the try ' 'server host to connect to.') if not options.port: raise NoTryServerAccess('Please use the --port option to specify the try ' 'serv...
logging.warn('Unexpected error code: %s' % e.returncode)
logging.warning('Unexpected error code: %s' % e.returncode)
def GuessVCS(options, path): """Helper to guess the version control system. NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't support it yet. This examines the path directory, guesses which SCM we're using, and returns an instance of the appropriate class. Exit with an error if we can't figur...
for x in failure: if ('502 Bad Gateway' in x or 'svn: REPORT of \'/svn/!svn/vcc/default\': 200 OK' in x): if os.path.isdir(args[2]): gclient_utils.RemoveDirectory(args[2]) break else:
if not IsKnownFailure():
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): failure.append(line)
if len(file_list) == previous_list_len: for x in failure: if ('502 Bad Gateway' in x or 'svn: REPORT of \'/svn/!svn/vcc/default\': 200 OK' in x): break else: raise else: pass
if len(file_list) == previous_list_len and not IsKnownFailure(): raise
def CaptureMatchingLines(line): match = compiled_pattern.search(line) if match: file_list.append(match.group(1)) if line.startswith('svn: '): failure.append(line)
if len(argv) > 2:
if argv and len(argv) > 2:
def CMDhelp(argv=None): """Prints this help or help for the given command.""" if len(argv) > 2: if argv[2] == 'try': TryChange(None, ['--help'], swallow_exception=False) return 0 if argv[2] == 'upload': upload.RealMain(['upload.py', '--help']) return 0 print (
log = Backquote(['git', 'show', '--name-only', '--pretty=format:%H%n%s%n%n%b']) m = re.match(r'^(\w+)\n(.*)$', log, re.MULTILINE|re.DOTALL) if not m: raise Exception("Could not parse log message: %s" % log) name = m.group(1)
name = Backquote(['git', 'rev-parse', 'HEAD'])
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
description = m.group(2)
description = Backquote(['git', 'log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)])
def __init__(self, commit=None, upstream_branch=None): self.commit = commit self.verbose = None self.default_presubmit = None self.may_prompt = None
for s in self.dependencies: if not s.safesync_url: continue handle = urllib.urlopen(s.safesync_url) rev = handle.read().strip() handle.close() if len(rev): self._options.revisions.append('%s@%s' % (s.name, rev))
if not self._options.revisions: for s in self.dependencies: if not s.safesync_url: continue handle = urllib.urlopen(s.safesync_url) rev = handle.read().strip() handle.close() if len(rev): self._options.revisions.append('%s@%s' % (s.name, rev))
def _EnforceRevisions(self): """Checks for revision overrides.""" revision_overrides = {} if self._options.head: return revision_overrides for s in self.dependencies: if not s.safesync_url: continue handle = urllib.urlopen(s.safesync_url) rev = handle.read().strip() handle.close() if len(rev): self._options.revisions.a...
'if the src@ part is skipped.')
'if the src@ part is skipped. Note that specifying ' '--revision means your safesync_url gets ignored.')
def CMDsync(parser, args): """Checkout/update all modules.""" parser.add_option('-f', '--force', action='store_true', help='force update even for unchanged modules') parser.add_option('-n', '--nohooks', action='store_true', help='don\'t run hooks after the update is complete') parser.add_option('-r', '--revision', acti...
('running', self.root_dir + '/src/file/other'),
('running', os.path.join(self.root_dir, 'src', 'file', 'other')),
def testSync(self): # TODO(maruel): safesync. if not self.enabled: return self.gclient(['config', self.svn_base + 'trunk/src/']) # Test unversioned checkout. self.parseGclient(['sync', '--deps', 'mac', '--jobs', '1'], ['running', 'running', # This is due to the way svn update is called for a # single file when File() i...
('running', self.root_dir + '/src/file/other'),
('running', os.path.join(self.root_dir, 'src', 'file', 'other')),
def testSyncIgnoredSolutionName(self): """TODO(maruel): This will become an error soon.""" if not self.enabled: return self.gclient(['config', self.svn_base + 'trunk/src/']) results = self.gclient( ['sync', '--deps', 'mac', '-r', 'invalid@1', '--jobs', '1']) self.checkBlock(results[0], [ 'running', 'running', # This is...