rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
set_trace()
def getthetaterms(k, q, theta, dp1, dp1dot): """Return array of integrated values for specified theta function and dphi function. Parameters ---------- integrand_elements: tuple Contains integrand arrays in order (k, q, theta) dp1: array_like Array of values for dphi1 dp1dot: array_like Array of values for dphi1dot ...
srceqns = SourceEquations(k)
fx = {"kmin":k[0], "deltak":k[1]-k[0], "numsoks":k.shape[-1], "fullkmax":run_config.kend, "nthetas":integrand_elements[2].shape[-1]} srceqns = SourceEquations(fx)
def slowrollsrcterm(bgvars, a, potentials, integrand_elements, dp1, dp1dot, theta_terms): """Return unintegrated slow roll source term. The source term before integration is calculated here using the slow roll approximation. This function follows the revised version of Eq (5.8) in Malik 06 (astro-ph/0610864v5). Param...
def __init__(self, k): self.k = k
def __init__(self, fixture): self.fixture = fixture self.fullk = N.arange(fixture["kmin"], fixture["fullkmax"], fixture["deltak"]) self.k = self.fullk[:fixture["numsoks"]]
def __init__(self, k): self.k = k
METAVAR="FILE", help="file to store results")
metavar="FILE", help="file to store results")
def main(argv=None): """Main function: deal with command line arguments and start calculation as reqd.""" if not argv: argv = sys.argv #Parse command line options parser = optparse.OptionParser() parser.add_option("-f", "--filename", action="store", dest="foresults", default=run_config.foresults, type="string", META...
"ystart": ystart, "cq": cq, "solver": "rkdriver_tsix"}
"pot_params": pot_params, "ystart": ystart, "cq": cq, "solver": "rkdriver_tsix"}
def getkend(kinit, deltak, numsoks): """Correct kend value given the values of kinit, deltak and numsoks. """ #Change from numsoks-1 to numsoks to include extra point when deltak!=kinit return 2*((numsoks)*deltak + kinit)
results = self.J_terms[0](k, Cterms, **kwargs)
results = np.complex256(self.J_terms[0](k, Cterms, **kwargs))
def full_source_from_model(self, m, nix, **kwargs): """Use the data from a model at a timestep nix to calculate the full source term S.""" #Get background values bgvars = m.yresult[nix, 0:3, 0] a = m.ainit*np.exp(m.tresult[nix]) if np.any(np.isnan(bgvars[0])): raise AttributeError("Background values not available for ...
data = conn.recv(1024)
try: data = conn.recv(1024) except socket.error: print "Connection close." break
def __output(conn): while True: data = conn.recv(1024) if not data:break sys.stdout.write(data) sys.stdout.flush()
while True:
try:
def __output(conn): while True: data = conn.recv(1024) if not data:break sys.stdout.write(data) sys.stdout.flush()
print "connect from %s" % str(addr)
except KeyboardInterrupt: sys.exit(0)
def __output(conn): while True: data = conn.recv(1024) if not data:break sys.stdout.write(data) sys.stdout.flush()
threading.Thread(target = __output, args = (conn,)).start() try: while 1: i = sys.stdin.readline() conn.sendall(i) except socket.error: print "Connect close." finally: conn.close()
print "Connect from %s\n" % str(addr) threading.Thread(target = __output, args = (conn,)).start() try: while 1: i = sys.stdin.readline() conn.sendall(i) except socket.error: print "Connection close." finally: conn.close()
def __output(conn): while True: data = conn.recv(1024) if not data:break sys.stdout.write(data) sys.stdout.flush()
movPath = movPicker.get_filename()
self.movPath = movPicker.get_filename()
def movPick(movFileButton): movPicker = gtk.FileChooserDialog(title="Choose a save location", parent=movDia, action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(("Save Here", -6)), backend=None) movRes = movPicker.run() if movRes == -6: movPath = movPicker.get_filename() movPicker.destroy()
filmFilesink.set_property("location", movPath)
filmFilesink.set_property("location", self.movPath)
def movGen(movButton):
setPic(todayPicName)
setPic(todayDate)
def capture(takeBut): pipeline.set_state(gst.STATE_NULL) stillPipe = gst.Pipeline("stillPipe") stillCam = gst.element_factory_make("v4l2src", "stillPipe") stillFilt = gst.element_factory_make("capsfilter", "stillFilt") stillCap = gst.Caps("video/x-raw-yuv,width=640,height=480") stillFilt.set_property("caps", stillCap) ...
takeBut.set_label("Picture taken this day.") takeBut.set_sensitive(False)
def capture(takeBut): pipeline.set_state(gst.STATE_NULL) stillPipe = gst.Pipeline("stillPipe") stillCam = gst.element_factory_make("v4l2src", "stillPipe") stillFilt = gst.element_factory_make("capsfilter", "stillFilt") stillCap = gst.Caps("video/x-raw-yuv,width=640,height=480") stillFilt.set_property("caps", stillCap) ...
takeBut.set_label("Picture taken for this day.") takeBut.set_sensitive(False)
if date == todayDate: takeBut.set_label("Picture taken for this day.") takeBut.set_sensitive(False)
def setPic(date): if self.pic != None: vbox1.remove(self.pic) vbox1.remove(hbox2) if date in self.db: self.pic = gtk.Image() self.pic.set_from_file(self.db[date]) takeBut.set_label("Picture taken for this day.") takeBut.set_sensitive(False) else: self.pic = gtk.Label() self.pic.set_justify(gtk.JUSTIFY_CENTER) self.pic....
takeBut.set_label("Picture taken for this day.")
takeBut.set_label("Take today's picture") takeBut.set_sensitive(True) else: takeBut.set_label("Take today's picture")
def setPic(date): if self.pic != None: vbox1.remove(self.pic) vbox1.remove(hbox2) if date in self.db: self.pic = gtk.Image() self.pic.set_from_file(self.db[date]) if date == todayDate: takeBut.set_label("Picture taken for this day.") takeBut.set_sensitive(False) else: self.pic = gtk.Label() self.pic.set_justify(gtk.JUS...
else:
def setPic(date): if self.pic != None: vbox1.remove(self.pic) vbox1.remove(hbox2) if date in self.db: self.pic = gtk.Image() self.pic.set_from_file(self.db[date]) if date == todayDate: takeBut.set_label("Picture taken for this day.") takeBut.set_sensitive(False) else: self.pic = gtk.Label() self.pic.set_justify(gtk.JUS...
dtext = f(r"[%(noWsCtl)s\x21-\x5A\x5E-\x7E]")
dtext = f(r"[%(noWsCtl)s%(somePrintableUSAscii)s]")
def f(s): d = inspect.currentframe().f_back.f_locals return "(?:" + (s % d) + ")"
flow_length = math.sqrt(abs(x1*x2+y1*y2))
flow_length = math.sqrt((x2-x1)**2+(y2-y1)**2)
def _plot_sample(self): if not optimised.a_count: return (x1, y1, x2, y2) = self.parameters['density_rectangle'] density_c = 0 density = 0.0 density_area = (y2-y1)*(x2-x1) velocities = list() for i in xrange(optimised.a_count): (x,y) = optimised.a_property(i, "position") r = optimised.a_property(i, "radius") velocities...
if x > self.width or x < -self.width or y > self.height or y < -self.height:
max_x = self.width/2.0 max_y = self.height/2.0 if x > max_x or x < -max_x or y > max_y or y < -max_y:
def _draw_circle(self, x, y, r, c): if x > self.width or x < -self.width or y > self.height or y < -self.height: return self.output.append("\\draw[color=%s] (%.2f,%.2f) circle (%.2f);" % (c,x,y,r))
def create_image(self):
def create_image(self, frames):
def create_image(self): pygame.image.save(self.screen, "%s%05d.png" % (pm.image_prefix, frames))
if self.options.show_simulation: return getattr(self.show_canvas, method)(*args) elif self.options.create_images: return getattr(self.image_canvas, method)(*args)
if self.options.create_images: retval = getattr(self.image_canvas, method)(*args) if self.options.show_simulation and self.options.tikz: return getattr(self.show_canvas, method)(*args) and retval return retval
def _canvas(self, method, *args): if self.options.show_simulation: return getattr(self.show_canvas, method)(*args) elif self.options.create_images: return getattr(self.image_canvas, method)(*args)
canvas.create_image()
canvas.create_image(frames)
def tick(): return True
for (x,y,r) in actors[:3]:
for a in actors: (x,y,r) = a[:3]
def draw_actors(self, actors): for (x,y,r) in actors[:3]: (x,y) = Helper.screen_coords(x,y) gfxdraw.aacircle(self.screen, x,y, Helper.screen_radius(r), DRAW_COLOUR)
"""The distance from the wall to point p
def distance_to(self, p): """The distance from the wall to point p
From http://www.codeguru.com/forum/showthread.php?t=194400: Let the point be C (Cx,Cy) and the line be AB (Ax,Ay) to (Bx,By). Let P be the point of perpendicular projection of C on AB. The parameter r, which indicates P's position along AB, is computed by the dot product of AC and AB divided by the square of the leng...
def distance_to(self, p): """The distance from the wall to point p
(1) AC dot AB r = --------- ||AB||^2
def distance_to(self, p): """The distance from the wall to point p
r has the following meaning: r=0 P = A r=1 P = B r<0 P is on the backward extension of AB r>1 P is on the forward extension of AB 0<r<1 P is interior to AB
def distance_to(self, p): """The distance from the wall to point p
The point P can then be found:
def distance_to(self, p): """The distance from the wall to point p
Px = Ax + r(Bx-Ax) Py = Ay + r(By-Ay)
def distance_to(self, p): """The distance from the wall to point p
And the distance from A to P = r*L."""
def distance_to(self, p): """The distance from the wall to point p
p = Vector(0,0)
p = Vector(12,-2)
def length(self): return self.start.distance_to(self.end)
field_names = numpy.array(map(addressof, field_name_strings))
field_names = (c_void_p * len(field_name_strings))() field_names[:] = map(addressof, field_name_strings)
def __init__(self, record_type, fields): '''Uses the EPICS static database to discover the offset in the record type and the size of each of the specified fields.''' length = len(fields) field_name_strings = map(create_string_buffer, fields) field_names = numpy.array(map(addressof, field_name_strings)) field_offsets ...
record_type, field_names.ctypes.data_as(c_void_p), length,
record_type, field_names, length,
def __init__(self, record_type, fields): '''Uses the EPICS static database to discover the offset in the record type and the size of each of the specified fields.''' length = len(fields) field_name_strings = map(create_string_buffer, fields) field_names = numpy.array(map(addressof, field_name_strings)) field_offsets ...
datatype, length, array = value_to_dbr(value)
datatype, length, data, array = value_to_dbr(value, None)
def set(self, value): '''Special routine to set the value directly.''' dbaddr = dbAddr() imports.dbNameToAddr(self._record.NAME, byref(dbaddr)) datatype, length, array = value_to_dbr(value) imports.dbPutField( byref(dbaddr), DbrToDbfCode[datatype], array.ctypes.data, length)
byref(dbaddr), DbrToDbfCode[datatype], array.ctypes.data, length)
byref(dbaddr), DbrToDbfCode[datatype], data, length)
def set(self, value): '''Special routine to set the value directly.''' dbaddr = dbAddr() imports.dbNameToAddr(self._record.NAME, byref(dbaddr)) datatype, length, array = value_to_dbr(value) imports.dbPutField( byref(dbaddr), DbrToDbfCode[datatype], array.ctypes.data, length)
'content': content.Title().decode("utf-8")}))
'content': safe_unicode(content.Title())}))
def Title(self): """The title of the comment. """ if not self.creator: creator = translate(Message(_(u"label_anonymous", default=u"Anonymous"))) else: creator = self.creator creator = creator
raise WrongCaptchaCode
if settings.captcha == 'norobots': raise WrongNorobotsAnswer else: raise WrongCaptchaCode
def validate(self, value): super(CaptchaValidator, self).validate(value)
msg = self.mailhost.messages[0]
msg = str(self.mailhost.messages[0])
def test_notify_user(self): # Add a comment with user notification enabled. Add another comment # and make sure an email is send to the user of the first comment. comment = createObject('plone.Comment') comment.title = 'Comment 1' comment.text = 'Comment text' comment.user_notification = True comment.author_email = "jo...
from plone.theme.interfaces import IDefaultPloneLayer class IDiscussionLayer(IDefaultPloneLayer):
class IDiscussionLayer(Interface):
def searchResults(REQUEST=None, **kw): """Perform a search over all indexed comments. """
crit.setValue('Discussion Item')
crit.setValue('Comment')
def test_collection(self): self.typetool.constructContent('Topic', self.portal, 'topic') topic = self.portal.topic crit = topic.addCriterion('Type', 'ATSimpleStringCriterion') crit.setValue('Discussion Item') query = topic.buildQuery()
self.assertEquals(query['Type'], 'Discussion Item')
self.assertEquals(query['Type'], 'Comment')
def test_collection(self): self.typetool.constructContent('Topic', self.portal, 'topic') topic = self.portal.topic crit = topic.addCriterion('Type', 'ATSimpleStringCriterion') crit.setValue('Discussion Item') query = topic.buildQuery()
def notify_workflow(obj):
def notify_workflow(obj, event):
def notify_workflow(obj): """Tell the workflow tool when a comment is added """ tool = getToolByName(obj, 'portal_workflow', None) if tool is not None: tool.notifyCreated(obj)
def notify_content_object(obj):
def notify_content_object(obj, event):
def notify_content_object(obj): """Tell the content object when a comment is added """ content_obj = aq_parent(aq_parent(obj)) content_obj.reindexObject(idxs=('total_comments', 'last_comment_date', 'commentators',))
def notify_content_object_deleted(obj):
def notify_content_object_deleted(obj, event):
def notify_content_object_deleted(obj): """Remove all comments of a content object when the content object has been deleted. """ if IAnnotatable.providedBy(obj): conversation = IConversation(obj) for comment in conversation.getComments(): del conversation[comment.id]
def notify_user(obj):
def notify_user(obj, event):
def notify_user(obj): """Tell users when a comment has been added. This method composes and sends emails to all users that have added a comment to this conversation and enabled user notification. This requires the user_notification setting to be enabled in the discussion control panel. """ # Check if user notificati...
message = USER_NOTIFICATION_MESSAGE % (obj.title, content_object.absolute_url(),)
message = MAIL_NOTIFICATION_MESSAGE.substitute( title=obj.title, link=content_object.absolute_url())
def notify_user(obj): """Tell users when a comment has been added. This method composes and sends emails to all users that have added a comment to this conversation and enabled user notification. This requires the user_notification setting to be enabled in the discussion control panel. """ # Check if user notificati...
self.assertEquals(sum(1 for w in conversation.getThreads()), 1)
def test_add_comment(self): # Create a conversation. In this case we doesn't assign it to an # object, as we just want to check the Conversation object API. conversation = IConversation(self.portal.doc1)
self.assertEquals(sum(1 for w in conversation.getThreads()), 1)
def test_delete_comment(self): # Create a conversation. In this case we doesn't assign it to an # object, as we just want to check the Conversation object API. conversation = IConversation(self.portal.doc1)
self.assertEquals(sum(1 for w in conversation.getThreads()), 0)
def test_delete_comment(self): # Create a conversation. In this case we doesn't assign it to an # object, as we just want to check the Conversation object API. conversation = IConversation(self.portal.doc1)
self.failUnless('Lorem ipsum' in contents)
self.failUnless('Lorem ipsum' in browser.contents)
def post(poster=None, password=None, url=urldoc1): if poster: browser.open(portal_url + '/logout') browser.open(portal_url + '/login_form') browser.getControl(name='__ac_name').value = poster browser.getControl(name='__ac_password').value = password browser.getControl(name='submit').click() browser.open(url) browser.ge...
self.assertRaises(Exception, test_view('calendar_todo'))
test_view('calendar_todo')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('calendar_todo'))
return filter(None, [formatOutput(unicode(line, 'utf-8'), skipList) for line in results])
return filter(None, [formatOutput(result, line, skipList) for result in results])
def checkLine(self, line, skipList=None): """Check one (and only one!) line of text, ignore words in skipList, return a list of tuples, each with the mispelled word, position in the line, and a list of suggestions""" if not skipList: skipList = [] self.stdIn.write('^%s\n' % line.encode('utf-8')) self.stdIn.flush() resu...
def formatOutput(line, skipList=[]):
def formatOutput(result, line, skipList=[]):
def formatOutput(line, skipList=[]): """Return tuple of word, position and guess list""" line = line.strip() guessMatch = guessRe.match(line) if guessMatch: word = guessMatch.group(1) if word not in skipList: return (word, int(guessMatch.group(2)) - 1, guessMatch.group(3).split(', ')) else: return None noGuessMatch = n...
line = line.strip() guessMatch = guessRe.match(line) if guessMatch: word = guessMatch.group(1) if word not in skipList: return (word, int(guessMatch.group(2)) - 1, guessMatch.group(3).split(', ')) else:
result = unicode(result, 'utf-8').strip() match = guessRe.match(result) if match: guesses = match.group(3).split(', ') else: match = noGuessRe.match(result) if not match:
def formatOutput(line, skipList=[]): """Return tuple of word, position and guess list""" line = line.strip() guessMatch = guessRe.match(line) if guessMatch: word = guessMatch.group(1) if word not in skipList: return (word, int(guessMatch.group(2)) - 1, guessMatch.group(3).split(', ')) else: return None noGuessMatch = n...
noGuessMatch = noGuessRe.match(line) if noGuessMatch: word = noGuessMatch.group(1) if word not in skipList: return (word, int(noGuessMatch.group(2)) - 1, []) return None
guesses = [] word = match.group(1) if word in skipList: return None wordPos = int(match.group(2)) - 1 while line[wordPos:wordPos + len(word)] != word and wordPos > 0: wordPos -= 1 return (word, wordPos, guesses)
def formatOutput(line, skipList=[]): """Return tuple of word, position and guess list""" line = line.strip() guessMatch = guessRe.match(line) if guessMatch: word = guessMatch.group(1) if word not in skipList: return (word, int(guessMatch.group(2)) - 1, guessMatch.group(3).split(', ')) else: return None noGuessMatch = n...
while results[-1] != '\n':
while results[-1].strip():
def checkLine(self, line, skipList=None): """Check one (and only one!) line of text, ignore words in skipList, return a list of tuples, each with the mispelled word, position in the line, and a list of suggestions""" if not skipList: skipList = [] self.stdIn.write('^%s\n' % line.encode('utf-8')) self.stdIn.flush() resu...
self.fileSave()
win.fileSave()
def savePrompt(self, closing=False): """Ask for save if doc modified, return false on cancel""" win = globalref.mainWin if not self.duplicateWindows(): if win.doc.modified and (closing or not globalref.options. boolData('OpenNewWindow')): text = win.fileImported and _('Save changes?') or \ _('Save changes to "%s"?') % ...
if child.formatName not in formatName])
if child.formatName not in formatNames])
def sortTypeChildren(self, formatNames): """Sort item children of the given formats""" childOfTypeList = [child for child in self.childList if child.formatName in formatNames] if childOfTypeList: childOfTypeList.sort(self.cmpItems) if len(childOfTypeList) < len(self.childList): childOfTypeList.extend([child for child i...
self.resize(globalref.options.intData('WindowXSize', 10, 10000), globalref.options.intData('WindowYSize', 10, 10000))
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setAcceptDrops(True) self.setStatusBar(QtGui.QStatusBar()) self.showStatusBar = globalref.options.boolData('ShowStatusBar') self.viewStatusBar(self.showStatusBar) globalref.mainWin = self self.resize(globalref.options.intData('WindowXSize', ...
x = globalref.options.intData('WindowXPos', -1000, 10000) y = globalref.options.intData('WindowYPos', -1000, 10000) if x != -1000 or y != -1000: shift = TreeMainWin.winCascade * \ globalref.treeControl.windowCount() self.move(x + shift, y + shift)
if globalref.treeControl.windowCount(): rect = globalref.treeControl.windowList[-1].geometry() rect.adjust(TreeMainWin.winCascade, TreeMainWin.winCascade, TreeMainWin.winCascade, TreeMainWin.winCascade) else: rect = QtCore.QRect(globalref.options.intData('WindowXPos', -1000, 10000), globalref.options.intData('WindowYPo...
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.setAcceptDrops(True) self.setStatusBar(QtGui.QStatusBar()) self.showStatusBar = globalref.options.boolData('ShowStatusBar') self.viewStatusBar(self.showStatusBar) globalref.mainWin = self self.resize(globalref.options.intData('WindowXSize', ...
globalref.options.changeData('WindowXPos', self.x(), True) globalref.options.changeData('WindowYPos', self.y(), True)
globalref.options.changeData('WindowXPos', self.geometry().x(), True) globalref.options.changeData('WindowYPos', self.geometry().y(), True)
def closeEvent(self, event): """Ask for save if doc modified""" if globalref.treeControl.savePrompt(True): globalref.treeControl.recentFiles.writeList() toolbarPos = base64.b64encode(self.saveState().data()) globalref.options.changeData('ToolbarPosition', toolbarPos, True) if globalref.options.boolData('SaveWindowGeom'...
except AttibuteError:
except AttributeError:
def firstWindow(self, fileNames): """Open first main window""" try: # check for existing TreeLine session socket = QtNetwork.QLocalSocket() socket.connectToServer('treeline-session', QtCore.QIODevice.WriteOnly) # if found, send files to open and exit TreeLine if socket.waitForConnected(1000): socket.write(repr(fileName...
scores[data[0]] = float(data[1])/num_lines_total
person = data[0] num_lines = data[1] if scores.has_key(person): scores[data[0]] += float(data[1]) else: scores[data[0]] = float(data[1]) for k, v in scores.items(): scores[k] = v/num_lines_total
def score_last_commit(self, block): """ Implementation of Score_last_commit(author, block).
return self._score_author_contributions_(contributions, num_lines_total)
return self._score_author_contributions(contributions, num_lines_total)
def score_all_commits(self, block): """ Returns a hash of author to the contribution [0, 1] of the author for this particular block, using all commits of this block.
Implementation of Score_last_commit(author, block).
Implementation of Score_{LastCommit}(author, block).
def score_last_commit(self, block): """ Implementation of Score_last_commit(author, block).
return self._score_author_contributions_(contributions, num_lines_total) def _score_author_contributions_(self, contributions, num_lines_total, *args):
return self._score_author_contributions(contributions, num_lines_total) def _score_author_contributions(self, contributions, num_lines_total, aging=None):
def score_last_commit(self, block): """ Implementation of Score_last_commit(author, block).
if scores.has_key(person): scores[data[0]] += float(data[1])
cont = float(data[1]) if aging == 'exp': cont *= self.aging_exp(self.days_since(sha)) elif aging == 'linear': cont *= 1 if person in scores: scores[data[0]] += cont
def _score_author_contributions_(self, contributions, num_lines_total, *args): scores = {} for sha, data in contributions.items(): person = data[0] num_lines = data[1] if scores.has_key(person): scores[data[0]] += float(data[1]) else: scores[data[0]] = float(data[1])
scores[data[0]] = float(data[1])
scores[data[0]] = cont
def _score_author_contributions_(self, contributions, num_lines_total, *args): scores = {} for sha, data in contributions.items(): person = data[0] num_lines = data[1] if scores.has_key(person): scores[data[0]] += float(data[1]) else: scores[data[0]] = float(data[1])
rev_contributions, num_lines_total = self.lines_contributed(block, rev)
rev_contributions, num_lines_rev = self.lines_contributed(block, rev)
def lines_contributed_for_revs(self, block, revs): """ Given a block, return a dict {SHA => [Person, num lines]}.
contributions[rev] = [person, num_lines]
if rev in contributions: contributions[rev][1] += num_lines else: contributions[rev] = [person, num_lines]
def lines_contributed_for_revs(self, block, revs): """ Given a block, return a dict {SHA => [Person, num lines]}.
if contributions.has_key(sha):
if sha in contributions:
def lines_contributed(self, block, rev="HEAD"): """ Given a block, return a dict {SHA => [Person, num lines]}.
self.authors.push(Person(name, email))
person = Person(name, email) self.authors.append(person) return person
def find_author(self, name=None, email=None, add_author=False): """ Find author with given name and/or email. If author does not exist, add the author if add_author is True. """
contributions = {}
contributions = {} shas = set()
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
blamestr = self.repo.git.blame(block, porcelain=True)
blamestr = self.repo.git.blame(block, incremental=True)
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
author_name = None author_email = None while not author_name: i += 1 components = lines[i].split(" ") print "Finding authors: " + lines[i] if components[0] == 'author': author_name = " ".join(components[1:]) elif components[0] == 'author-mail': author_email = " ".join(components[1:]).strip("<").strip(">")
if not shas.issuperset((sha,)): shas.add(sha) author_name, author_email = None, None while not (author_name and author_email): i += 1 components = lines[i].split(" ") if components[0] == 'author': author_name = " ".join(components[1:]) elif components[0] == 'author-mail': author_email = " ".join(components[1:]).s...
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
person = self.find_author(name=author_name, email=author_email) if contributions.has_key(person):
person = self.find_author(name=author_name, email=author_email, add_author=True) if contributions.has_key(person): contributions[person] += ln_group else: contributions[person] = ln_group spin = True while spin: i += 1 components = lines[i].split(" ") if components[0] == 'filename': i += 1 spin = False else:
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
else: contributions[person] = 0 spin = True while spin: i += 1 components = lines[i].split(" ") print "Spinning: " + lines[i] if (Search.header_titles.count(components[0]) == 0 and len(components) == 4): spin = False
spin = True while spin: i += 1 components = lines[i].split(" ")
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
if components[0] == 'filename': i += 1 spin = False print num_lines_total return contributions
def lines_contributed(self, block): """ Given a block, return a hash {author: num lines contributed}. """
fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload"))
def _check_file(request): """ Check if file already exists on the server. """ from django.utils import simplejson folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) fileArray = {} if request.method == 'POST': for k,v in request.P...
fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
fb_uploadurl_re = re.compile(r'^.*(%s)' % reverse("fb_upload"))
def _upload_file(request): """ Upload file to the server. """ from django.core.files.move import file_move_safe if request.method == 'POST': folder = request.POST.get('folder') fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload")) folder = fb_uploadurl_re.sub('', folder) abs_path = os.path.join(MEDIA_ROOT, DI...
if os.path.isfile(os.path.join(MEDIA_ROOT, value)):
if os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, value))):
def get_version_path(value, version_prefix): """ Construct the PATH to an Image version. Value has to be server-path, relative to MEDIA_ROOT. version_filename = filename + version_prefix + ext Returns a path relative to MEDIA_ROOT. """ if os.path.isfile(os.path.join(MEDIA_ROOT, value)): path, filename = os.path.split...
if os.path.isfile(os.path.join(MEDIA_ROOT, path, new_filename + "_" + version_prefix + ext)):
if os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, path, new_filename + "_" + version_prefix + ext))):
def get_version_path(value, version_prefix): """ Construct the PATH to an Image version. Value has to be server-path, relative to MEDIA_ROOT. version_filename = filename + version_prefix + ext Returns a path relative to MEDIA_ROOT. """ if os.path.isfile(os.path.join(MEDIA_ROOT, value)): path, filename = os.path.split...
raise ImproperlyConfigured, _("Error finding Upload-Folder. Maybe it does not exist?")
raise ImproperlyConfigured, _("Error finding Upload-Folder (MEDIA_ROOT + FILEBROWSER_DIRECTORY). Maybe it does not exist?")
def browse(request): """ Browse Files/Directories. """ # QUERY / PATH CHECK query = request.GET.copy() path = get_path(query.get('dir', '')) directory = get_path('') if path is None: msg = _('The requested Folder does not exist.') request.user.message_set.create(message=msg) if directory is None: # The DIRECTORY does...
return self.path
return self.url_rel
def _url_relative(self): return self.path
return u"%s" % url_join(MEDIA_URL, self.path)
return u"%s" % url_join(MEDIA_URL, self.url_rel)
def _url_full(self): """ Full URL including MEDIA_URL. """ return u"%s" % url_join(MEDIA_URL, self.path)
return self.path
return self.url_rel
def _url_save(self): """ URL used for the filebrowsefield. """ if SAVE_FULL_URL: return self.url_full else: return self.path
return u"%s" % url_join(MEDIA_URL, get_version_path(self.path, 'fb_thumb'))
return u"%s" % url_join(MEDIA_URL, get_version_path(self.path, ADMIN_THUMBNAIL))
def _url_thumbnail(self): """ Thumbnail URL. """ if self.filetype == "Image": return u"%s" % url_join(MEDIA_URL, get_version_path(self.path, 'fb_thumb')) else: return ""
self.filetype = get_file_type(self.filename)
if os.path.isdir(self.path_full): self.filetype = 'Folder' else: self.filetype = get_file_type(self.filename)
def __init__(self, path): self.path = path self.url_rel = path.replace("\\","/") self.head = os.path.split(path)[0] self.filename = os.path.split(path)[1] self.filename_lower = self.filename.lower() # important for sorting self.filetype = get_file_type(self.filename)
if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)):
converted_path = smart_str(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) if not os.path.isfile(converted_path) and not os.path.isdir(converted_path):
def get_file(path, filename): """ Get File. """ if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)): return None return filename
if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)):
if not os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, version_path))):
def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: source = force_unicode(source) versi...
if not os.path.isfile(os.path.join(MEDIA_ROOT, version_path)):
if not os.path.isfile(smart_str(os.path.join(MEDIA_ROOT, version_path))):
def render(self, context): try: source = self.src.resolve(context) except VariableDoesNotExist: return None if self.version_prefix: version_prefix = self.version_prefix else: try: version_prefix = self.version_prefix_var.resolve(context) except VariableDoesNotExist: return None try: source = force_unicode(source) versi...
os.unlink(os.path.join(abs_path, filename))
os.unlink(smart_str(os.path.join(abs_path, filename)))
def delete(request): """ Delete existing File/Directory. When trying to delete a Directory, the Directory has to be empty. """ # QUERY / PATH CHECK query = request.GET path = get_path(query.get('dir', '')) filename = get_file(query.get('dir', ''), query.get('filename', '')) if path is None or filename is None: if pat...
try: version.save(absolute_version_path, quality=VERSION_QUALITY, optimize=(os.path.splitext(version_path)[1].lower() != '.gif')) except IOError: version.save(absolute_version_path, quality=VERSION_QUALITY)
if version: try: version.save(absolute_version_path, quality=VERSION_QUALITY, optimize=(os.path.splitext(version_path)[1].lower() != '.gif')) except IOError: version.save(absolute_version_path, quality=VERSION_QUALITY) else: pass
def version_generator(value, version_prefix, force=None): """ Generate Version for an Image. value has to be a serverpath relative to MEDIA_ROOT. """ # PIL's Error "Suspension not allowed here" work around: # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html if STRICT_PIL: from PIL import ImageFile...
path = self.path.encode('utf8')
path = force_unicode(self.path)
def _filesize(self): """ Filesize. """ path = self.path.encode('utf8') if os.path.isfile(os.path.join(MEDIA_ROOT, path)) or os.path.isdir(os.path.join(MEDIA_ROOT, path)): return os.path.getsize(os.path.join(MEDIA_ROOT, path)) return ""
return u"%s" % os.path.join(MEDIA_ROOT, self.path)
return os.path.join(MEDIA_ROOT, self.path)
def _path_full(self): """ Full server PATH including MEDIA_ROOT. """ return u"%s" % os.path.join(MEDIA_ROOT, self.path)
return u"%s" % self.url_save
return force_unicode(self.url_save)
def __repr__(self): return u"%s" % self.url_save
return u"%s" % self.url_save
return force_unicode(self.url_save)
def __str__(self): return u"%s" % self.url_save
return u"%s" % self.url_save
return force_unicode(self.url_save)
def __unicode__(self): return u"%s" % self.url_save
self.stdout.write('No files removed.\n\n' % len(files))
self.stdout.write('No files removed.\n\n')
def handle(self, *args, **options): media_path = "" if len(args): media_path = args[0] path = os.path.join(MEDIA_ROOT, media_path) if not os.path.isdir(path): raise CommandError('<media_path> must be a directory in MEDIA_ROOT. "%s" is no directory.' % path); self.stdout.write("\n%s\n" % self.help) self.stdout.writ...