rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
raise ValueError('did not find HDF5 headers and libraries')
raise ValueError('did not find HDF5 headers')
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
hdf5_version = check_hdf5version(HDF5_dir)
if HDF5_includedir is None: HDF5_includedir = os.path.join(HDF5_dir, 'include') hdf5_version = check_hdf5version(HDF5_includedir)
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
raise ValueError('did not find HDF5 headers and libraries in %s' % HDF5_dir)
raise ValueError('did not find HDF5 headers in %s' % HDF5_includedir)
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
if netCDF4_dir is None:
if netCDF4_includedir is None and netCDF4_dir is None:
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
isnetcdf4 = check_ifnetcdf4(direc)
isnetcdf4 = check_ifnetcdf4(os.path.join(direc, 'include'))
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
raise ValueError('did not find netCDF version 4 headers and libs')
raise ValueError('did not find netCDF version 4 headers')
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
isnetcdf4 = check_ifnetcdf4(netCDF4_dir)
if netCDF4_includedir is None: netCDF4_includedir = os.path.join(netCDF4_dir, 'include') isnetcdf4 = check_ifnetcdf4(netCDF4_includedir)
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
raise ValueError('did not find netCDF version 4 headers and libs in %s' % netCDF4_dir)
raise ValueError('did not find netCDF version 4 headers %s' % netCDF4_includedir) if HDF5_libdir is None and HDF5_dir is not None: HDF5_libdir = os.path.join(HDF5_dir, 'lib') if netCDF4_libdir is None and netCDF4_dir is not None: netCDF4_libdir = os.path.join(netCDF4_dir, 'lib')
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
lib_dirs = [os.path.join(netCDF4_dir,'lib'),os.path.join(HDF5_dir,'lib')] inc_dirs = [os.path.join(netCDF4_dir,'include'),os.path.join(HDF5_dir,'include')]
lib_dirs = [netCDF4_libdir,HDF5_libdir] inc_dirs = [netCDF4_includedir,HDF5_includedir]
def check_ifnetcdf4(netcdf4_dir): try: f = open(os.path.join(netcdf4_dir,'include/netcdf.h')) except IOError: return False isnetcdf4 = False for line in f: if line.startswith('nc_inq_compound'): isnetcdf4 = True return isnetcdf4
mutant.fitness.invalidate()
mutant.fitness.valid = False
def mutShuffleIndexes(individual, indpb): """Shuffle the attributes of the input individual and return the mutant. The *individual* is left intact and the mutant is an independant copy. The *individual* is expected to be iterable. The *shuffleIndxPb* argument is the probability of each attribute to be moved. This func...
return sorted(individuals, key=lambda ind : ind.fitness, reverse=True)[:n]
return sorted(individuals, key=attrgetter("fitness"), reverse=True)[:n]
def selBest(individuals, n): """Select the *n* best individuals among the input *individuals*. The list returned contains shallow copies of the input *individuals*. """ return sorted(individuals, key=lambda ind : ind.fitness, reverse=True)[:n]
return sorted(individuals, key=lambda ind : ind.mFitness)[:n]
return sorted(individuals, key=attrgetter("fitness"))[:n]
def selWorst(individuals, n): """Select the *n* worst individuals among the input *individuals*. The list returned contains shallow copies of the input *individuals*. """ return sorted(individuals, key=lambda ind : ind.mFitness)[:n]
child1[i], child2[i] = childe2[i], child1[i]
child1[i], child2[i] = child2[i], child1[i]
def cxUniform(ind1, ind2, indpb): """Uniform crossover""" child1, child2 = copy.deepcopy(ind1), copy.deepcopy(ind2) size = min(len(ind1), len(ind2)) for i in xrange(size): if random.random() < indpb: child1[i], child2[i] = childe2[i], child1[i] try: child1.fitness.valid = False child2.fitness.valid = False except Att...
type = subtree.root.ret subtree = base.Tree(expr(type=type))
type_ = subtree.root.ret subtree = base.Tree(expr(type=type_))
def mutTypedTreeUniform(ind, expr): """ The mutation of strongly typed GP expression is pretty easy. First, it finds a subtree. Second, it has to identify the return type of the root of this subtree. Third, it generates a new subtree with a root's type corresponding to the original subtree root's type. Finally, the old...
def __getSubTree(tree, index): total = 0 if index == 0: return tree for child in tree: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return __getNode(child, index-total) else: total += nbrChild except: total += 1 return __getSubTree(self, index)
total = 0 if index == 0: return self for child in self: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return getSubTree(child, index-total) else: total += nbrChild except: total += 1
def __getSubTree(tree, index): total = 0 if index == 0: return tree for child in tree: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return __getNode(child, index-total) else: total += nbrChild except: total += 1
def __setSubTree(tree, index, subTree): total = 0 for i, child in enumerate(tree): if total == index: tree[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: __setSubTree(child, index-total, subTree) else: total += nbrChild except: total += 1 __setSubTree(self, index, subTr...
total = 0 for i, child in enumerate(self): if total == index: self[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: setSubTree(child, index-total, subTree) else: total += nbrChild except: total += 1
def __setSubTree(tree, index, subTree): total = 0 for i, child in enumerate(tree): if total == index: tree[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: __setSubTree(child, index-total, subTree) else: total += nbrChild except: total += 1
termset_ratio = len(pset.terminals) / \ (len(pset.terminals)+len(pset.primitives))
termset_ratio = float(len(pset.terminals)) / \ float(len(pset.terminals)+len(pset.primitives))
def generate_grow(pset, min, max): termset_ratio = len(pset.terminals) / \ (len(pset.terminals)+len(pset.primitives)) def condition(max_depth): return max_depth == 0 or random.random() < termset_ratio return _generate(pset, min, max, condition)
self.resultsLock = threading.Lock() self.results = {}
def __init__(self): self.sTime = time.time()
if self.commThread.isRootWorker:
if self.exitSetHere:
def _doCleanUp(self): """ Fonction charge de faire le clean up a la fin """ #if self.commThread.isRootWorker: msgT = "Rank " + str(self.workerId) + " ("+str(threading.currentThread().name)+" / " + str(threading.currentThread().ident) + ")\n" for target,times in self.tasksStats.items(): msgT += "\t" + str(target) + " : ...
self.resultsLock.acquire() self.results[tidParent][result[2]] = result[4] self.resultsLock.release()
def _dispatchResult(self, result): tidParent = result[1]
del self.waitingThreads[tidParent]
def _dispatchResult(self, result): tidParent = result[1]
self.nodesStatus[self.workerId] = [self.execQueue.qsize(), self.waitingForRestartQueue.qsize(), len(self.waitingThreads), time.time(), time.time()]
def _main(self): # Cette fonction est la boucle principale du thread de controle while True: # On update notre etat self.nodesStatus[self.workerId] = [self.execQueue.qsize(), self.waitingForRestartQueue.qsize(), len(self.waitingThreads), time.time(), time.time()]
self.nodesStatus[self.workerId] = [self.execQueue.qsize(), self.waitingForRestartQueue.qsize(), len(self.waitingThreads), time.time(), time.time()]
def _main(self): # Cette fonction est la boucle principale du thread de controle while True: # On update notre etat self.nodesStatus[self.workerId] = [self.execQueue.qsize(), self.waitingForRestartQueue.qsize(), len(self.waitingThreads), time.time(), time.time()]
self.resultsLock.acquire() self.results[currentId] = [None for i in xrange(0, len(iterable))] self.resultsLock.release()
listResults = [None for i in xrange(0, len(iterable))]
def map(self, function, iterable): # Pour l'instant, map() ne supporte pas plusieurs iterables # En concordance avec l'API de multiprocessing # A discuter... listTid = [] currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
self.waitingThreads[currentId] = (conditionObject, listTid, time.time())
self.waitingThreads[currentId] = (conditionObject, listTid, time.time(), listResults)
def map(self, function, iterable): # Pour l'instant, map() ne supporte pas plusieurs iterables # En concordance avec l'API de multiprocessing # A discuter... listTid = [] currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
self.resultsLock.acquire() ret = self.results[currentId] del self.results[currentId] self.resultsLock.release()
self.waitingThreadsLock.acquire() ret = self.waitingThreads[currentId][3] del self.waitingThreads[currentId] self.waitingThreadsLock.release()
def map(self, function, iterable): # Pour l'instant, map() ne supporte pas plusieurs iterables # En concordance avec l'API de multiprocessing # A discuter... listTid = [] currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
self.resultsLock.acquire() self.results[currentId] = [None] self.resultsLock.release()
def _apply(self, function, args, kwargs): # Fonction qui permet de regrouper apply() et apply_async() currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
self.waitingThreads[currentId] = (conditionObject, listTid, time.time())
self.waitingThreads[currentId] = (conditionObject, listTid, time.time(), [None])
def _apply(self, function, args, kwargs): # Fonction qui permet de regrouper apply() et apply_async() currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
self.resultsLock.acquire() ret = self.results[currentId] del self.results[currentId] self.resultsLock.release()
self.waitingThreadsLock.acquire() ret = self.waitingThreads[currentId][3] del self.waitingThreads[currentId] self.waitingThreadsLock.release()
def _apply(self, function, args, kwargs): # Fonction qui permet de regrouper apply() et apply_async() currentId = threading.currentThread().tid conditionObject = threading.currentThread().waitingCondition
return expr[0](*expr[1]) except : values = [evaluateExpr(value) for value in expr[1]] return evaluateExpr([expr[0],values])
func = expr[0] try: return func(*[evaluateExpr(value) for value in expr[1:]]) except: return func(*expr[1:]) except: return expr
def evaluateExpr(expr): try: return expr[0](*expr[1]) except : values = [evaluateExpr(value) for value in expr[1]] return evaluateExpr([expr[0],values])
self.iter = iter(self.func())
self.iter = None
def __init__(self, func): self.func = func self.iter = iter(self.func())
type1 = subtree1.root.ret
def cxTypedTreeOnePoint(ind1, ind2): """ Randomly select in each individual and exchange each subtree with the point as root between each individual. Since the node are strongly typed, the operator then make sure the the type of second node correspond to the type of the first node. It it doesn't it randomly select anot...
type2 = subtree2.root.ret
try: type1 = subtree1.root.ret except AttributeError: type1 = subtree1.ret try: type2 = subtree2.root.ret except AttributeError: type2 = subtree2.ret
def cxTypedTreeOnePoint(ind1, ind2): """ Randomly select in each individual and exchange each subtree with the point as root between each individual. Since the node are strongly typed, the operator then make sure the the type of second node correspond to the type of the first node. It it doesn't it randomly select anot...
type2 = subtree2.root.ret
try: type2 = subtree2.root.ret except AttributeError: type2 = subtree2.ret
def cxTypedTreeOnePoint(ind1, ind2): """ Randomly select in each individual and exchange each subtree with the point as root between each individual. Since the node are strongly typed, the operator then make sure the the type of second node correspond to the type of the first node. It it doesn't it randomly select anot...
mutant.set_subtree_dfs(index, expr(pset=mutant.pset, type=subtree.root.ret))
try: type_ = subtree.root.ret except AttributeError: type_ = subtree.ret mutant.set_subtree_dfs(index, expr(pset=mutant.pset, type=type_))
def mutTypedTreeUniform(ind, expr): """ The mutation of strongly typed GP expression is pretty easy. First, it finds a subtree. Second, it has to identify the return type of the root of this subtree. Third, it generates a new subtree with a root's type corresponding to the original subtree root's type. Finally, the old...
index = random.randint(1, mutant.size-1)
index = random.randint(0, mutant.size-1)
def mutTreeUniform(ind, expr): mutant = copy.deepcopy(ind) index = random.randint(1, mutant.size-1) subtree = base.Tree(expr()) mutant.set_subtree_dfs(index, subtree) try: mutant.fitness.valid = False except AttributeError: pass return mutant
index = random.randint(1, mutant.size-1)
index = random.randint(0, mutant.size-1)
def mutTypedTreeUniform(ind, expr): """ The mutation of strongly typed GP expression is pretty easy. First, it finds a subtree. Second, it has to identify the return type of the root of this subtree. Third, it generates a new subtree with a root's type corresponding to the original subtree root's type. Finally, the old...
return max(elem.height for elem in self)+1
try: return max(elem.height for elem in self[1:])+1 except ValueError: return 0
def height(self): """Return the height of the tree.""" return max(elem.height for elem in self)+1
return func(*[_stringify(value) for value in expr[1:]])
return str(func(*[_stringify(value) for value in expr[1:]]))
def _stringify(expr): try: func = expr[0] return func(*[_stringify(value) for value in expr[1:]]) except TypeError: return expr
return expr
return str(expr)
def _stringify(expr): try: func = expr[0] return func(*[_stringify(value) for value in expr[1:]]) except TypeError: return expr
Terminal.__init__(self, self.func(), self.ret)
Terminal.__init__(self, self.func(), ret)
def __init__(self, func, ret = __type__): self.func = func Terminal.__init__(self, self.func(), self.ret)
lToolBox = toolbox.SimpleGAToolBox()
lToolBox = toolbox.SimpleGAToolbox()
def evalOneMax(individual): if not individual.mFitness.isValid(): individual.mFitness.append(individual.count(True))
lPop.suscribe('stats', stats.statistics)
def evalOneMax(individual): if not individual.mFitness.isValid(): individual.mFitness.append(individual.count(True))
lPop.emit()
popFitStats = stats.Statistics(lPop, 'mFitness[0]') popFitStats.add('mean', stats.mean) popFitStats.add('variance', stats.variance)
def evalOneMax(individual): if not individual.mFitness.isValid(): individual.mFitness.append(individual.count(True))
lPop.emit()
def evalOneMax(individual): if not individual.mFitness.isValid(): individual.mFitness.append(individual.count(True))
print '\tMinimum :', stats.getStats('stats')[0] print '\tMaximum :', stats.getStats('stats')[1] print '\tAverage :', stats.getStats('stats')[2]
popFitStats.compute() print '\tAverage :', popFitStats.get('mean') print '\tStdev :', popFitStats.get('variance')**0.5
def evalOneMax(individual): if not individual.mFitness.isValid(): individual.mFitness.append(individual.count(True))
value = 0 for node in tree: try: value += count(node) except: value += 1 return value
if isinstance(tree, list): value = 0 for node in tree: value += IndividualTree.count(node) return value else: return 1
def count(tree): value = 0 for node in tree: try: value += count(node) except: value += 1 return value
except:
except TypeError:
def evaluateExpr(expr): try: func = expr[0] try: return func(*[IndividualTree.evaluateExpr(value) for value in expr[1:]]) except: return func(*expr[1:]) except : try: return expr() except: return expr
total = 0 if index == 0: return self for child in self: if total == index: return child try:
def __getSubTree(tree, index): total = 0 if index == 0: return tree for child in tree: if total == index: return child
def getSubTree(self, index): total = 0 if index == 0: return self for child in self: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return getSubTree(child, index-total) else: total += nbrChild except: total += 1
return getSubTree(child, index-total)
return __getSubTree(child, index-total)
def getSubTree(self, index): total = 0 if index == 0: return self for child in self: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return getSubTree(child, index-total) else: total += nbrChild except: total += 1
except: total += 1
return __getSubTree(self, index)
def getSubTree(self, index): total = 0 if index == 0: return self for child in self: if total == index: return child try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: return getSubTree(child, index-total) else: total += nbrChild except: total += 1
total = 0 for i, child in enumerate(self): if total == index: self[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: setSubTree(child, index-total, subTree)
def __setSubTree(tree, index, subTree): total = 0 for i, child in enumerate(tree): if total == index: tree[i] = subTree return if IndividualTree.count(child) + total > index: __setSubTree(child, index-total, subTree) return
def setSubTree(self, index, subTree): total = 0 for i, child in enumerate(self): if total == index: self[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: setSubTree(child, index-total, subTree) else: total += nbrChild except: total += 1
total += nbrChild except: total += 1
total += IndividualTree.count(child) __setSubTree(self, index, subTree)
def setSubTree(self, index, subTree): total = 0 for i, child in enumerate(self): if total == index: self[i] = copy.copy(subTree) try: nbrChild = IndividualTree.count(child) if nbrChild + total > index: setSubTree(child, index-total, subTree) else: total += nbrChild except: total += 1
return error('No such directory')
files_info = error('No such directory')
def getfolder(self): path = get_path(self.request.GET.get('path', None)) getsize = self.request.GET.get('getsize', None)
files_info = {}
files_info = OrderedDict()
def getfolder(self): requested_path = self.request.GET.get('path', None) real_path = get_path(requested_path) getsize = self.request.GET.get('getsize', None)
for filename in os.listdir(real_path):
for filename in sorted(os.listdir(real_path), key=unicode.lower):
def getfolder(self): requested_path = self.request.GET.get('path', None) real_path = get_path(requested_path) getsize = self.request.GET.get('getsize', None)
files_info['/' + filename] = create_file_info_for( requested_file_path, real_file_path)
files_info[filename] = create_file_info_for( requested_file_path, real_file_path)
def getfolder(self): requested_path = self.request.GET.get('path', None) real_path = get_path(requested_path) getsize = self.request.GET.get('getsize', None)
'Preview': '/media/upload/path/to/file.png',
'Preview': '/path/to/file.png',
def test_create_file_info_for_png(self): """Test information creation for a png file.""" expected_result = { 'Code': 0, 'Error': '', 'File Type': 'png', 'Filename': 'file.png', 'Path': '/path/to/file.png', 'Preview': '/media/upload/path/to/file.png', 'Properties': {'Date Created': '1982/02/08 - 10:10:10', 'Date Modifie...
response = self.client.get('', {'path': '/',
response = self.client.get('', {'path': '/static/upload/',
def test_getfolder_success(self): """Test succesful retrieving of a directory.""" # ?path=/&mode=getfolder&showThumbs=true response = self.client.get('', {'path': '/', 'mode': 'getfolder', 'showThumbs': 'true'}) self.failUnlessEqual(response.status_code, 200)
@patch('os.path.exists', exists_mock)
def mockify(self, exists_mock=Mock(), move_mock=Mock()): @patch('shutil.move', move_mock) @patch('os.path.exists', exists_mock) def patching(): #?mode=addfolder&path=/&name=new_directory self.response = self.client.get('', {'mode': 'rename', 'old': 'oldfile.txt', 'new': 'newfile.txt'}) patching()
'old': 'oldfile.txt', 'new': 'newfile.txt'})
'old': '/static/upload/oldfile.txt', 'new': '/static/upload/newfile.txt'})
def patching(): #?mode=addfolder&path=/&name=new_directory self.response = self.client.get('', {'mode': 'rename', 'old': 'oldfile.txt', 'new': 'newfile.txt'})
path='/file-to-be-deleted.txt')
path='/static/upload/file-to-be-deleted.txt')
def test_delete_file_success(self): """Test succesful deletion of a file.""" self.exists_mock.return_value = True self.isdir_mock.return_value = False self.mockify(exists_mock=self.exists_mock, isdir_mock=self.isdir_mock, remove_mock=self.remove_mock, path='/file-to-be-deleted.txt')
'Path': '/file-to-be-deleted.txt'}
'Path': '/static/upload/file-to-be-deleted.txt'}
def test_delete_file_success(self): """Test succesful deletion of a file.""" self.exists_mock.return_value = True self.isdir_mock.return_value = False self.mockify(exists_mock=self.exists_mock, isdir_mock=self.isdir_mock, remove_mock=self.remove_mock, path='/file-to-be-deleted.txt')
path='/directory-to-be-deleted/')
path='/static/upload/directory-to-be-deleted/')
def test_delete_directory_success(self): """Test succesful deletion of a directory.""" self.exists_mock.return_value = True self.isdir_mock.return_value = True self.mockify(exists_mock=self.exists_mock, isdir_mock=self.isdir_mock, rmdir_mock=self.rmdir_mock, path='/directory-to-be-deleted/')
'Path': '/directory-to-be-deleted/'}
'Path': '/static/upload/directory-to-be-deleted/'}
def test_delete_directory_success(self): """Test succesful deletion of a directory.""" self.exists_mock.return_value = True self.isdir_mock.return_value = True self.mockify(exists_mock=self.exists_mock, isdir_mock=self.isdir_mock, rmdir_mock=self.rmdir_mock, path='/directory-to-be-deleted/')
path='/nofile-or-directory-to-be-deleted')
path='/static/upload/nofile-or-directory-to-be-deleted')
def test_delete_file_or_directory_not_existent(self): """Test deletion of a not existent file or directory.""" self.exists_mock.return_value = False self.mockify(exists_mock=self.exists_mock, path='/nofile-or-directory-to-be-deleted')
'path': '/',
'path': '/static/upload/new/',
def patching(): self.mkdir_mock = mock_hook #?mode=addfolder&path=/&name=new_directory self.response = self.client.get('', {'mode': 'addfolder', 'path': '/', 'name': 'new_directory'})
'Parent': '/'}
'Parent': '/static/upload/new/'}
def test_addfolder_success(self): """Test succesful creation of a new directory.""" self.failUnlessEqual(self.response.status_code, 200) self.failUnless(self.mkdir_mock.called)
file_info['Properties']['Date Created'] = os.path.getctime(real_path) file_info['Properties']['Date Modified'] = os.path.getmtime(real_path)
file_info['Properties']['Date Created'] = time.strftime(TIME_FORMAT, time.localtime(os.path.getctime(real_path))) file_info['Properties']['Date Modified'] = time.strftime(TIME_FORMAT, time.localtime(os.path.getmtime(real_path)))
def create_file_info_for(requested_path, real_path): """Fills proper file information needed by Code Five Filemanager.""" file_info = { 'Path': '', 'Return': '', 'Filename': '', 'File Type': '', 'Preview': '', 'Properties': { 'Date Created': '', 'Date Modified': '', 'Height': '', 'Width': '', 'Size': '' }, 'Error': ''...
expected_content = {'Code': -1, 'Error': 'No such file or directory'}
expected_content = {'Code': -1, 'Error': 'No such file or directory.'}
def test_rename_fail(self): """Test unsuccesful rename of a file (or directory).""" self.failUnlessEqual(self.response.status_code, 200)
expected_content = {'Code': -1, 'Error': 'No such file or directory'}
expected_content = {'Code': -1, 'Error': 'No such file or directory.'}
def test_delete_file_or_directory_not_existent(self): """Test deletion of a not existent file or directory.""" self.exists_mock.return_value = False self.mockify(exists_mock=self.exists_mock, path='/static/upload/nofile-or-directory-to-be-deleted')
expected_content = {'Code': -1, 'Error': 'No such file!'}
expected_content = {'Code': -1, 'Error': 'Can\'t add newfile.txt.'}
def test_add_fail(self): """Test unsuccesful upload of a file.""" self.failUnlessEqual(self.response.status_code, 200)
expected_content = {'Code': -1, 'Error': 'File exists'} self.failUnlessEqual(self.response.content, simplejson.dumps(expected_content))
expected_content = {'Code': -1, 'Error': 'Can\'t create ' '/static/upload/new/new_directory.'} self.failUnlessEqual(self.response.content, simplejson.dumps(expected_content))
def test_addfolder_fail(self): """Test unsuccessful creation of a new directory.""" # Raise an OSError exception during directory creation. self.failUnlessEqual(self.response.status_code, 200)
settings.C5FILEMANAGER_DIR,
settings.UPLOAD_DIRECTORY,
def test_rename_success(self): """Test succesful rename of a file (or directory).""" self.failUnlessEqual(self.response.status_code, 200) self.failUnless(self.move_mock.called)
url='http://mornie.org/projects/django-c5filemanager/'
url='http://mornie.org/projects/django-c5filemanager/',
def read(filename): """Small tool function to read README.""" return open(os.path.join(os.path.dirname(__file__), filename)).read()
get_version())
get_version()),
def read(filename): """Small tool function to read README.""" return open(os.path.join(os.path.dirname(__file__), filename)).read()
def setUp(self): self.mockify()
def setUp(self, auto_mockify=True): self.user = User.objects.create_superuser('eriol', 'eriol@mornie.org', 'secret') self.client.login(username='eriol', password='secret') if auto_mockify: self.mockify() def tearDown(self): self.user.delete()
def setUp(self): self.mockify()
self.strings[node.getAttribute("name")]=node.firstChild.data
self.strings[node.getAttribute("name")]=node.firstChild.data.replace('\n','').replace('\t','')
def load_strings(self): self.strings={} for node in self.xml.getElementsByTagName("string"): self.strings[node.getAttribute("name")]=node.firstChild.data
print tempdir()
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
if self.aspectratio: overview += "\n%sAspect Ratio:%s " % format + self.aspectratio
def overview(self, bbcode=False): """Provides a short overview of the film or TV series. Optional argument turns on BBCode formatting. """ overview = "" if bbcode: format = ("[b]","[/b]") else: format = ("","") overview += "%sIMDB url:%s " % format + self.url if self.title: overview += "\n%sTitle:%s " % format + self...
match = re.findall(conf.strings["imdb_plot_re"], page, re.MULTILINE) if match: self.plot = match[0] self.__setitem__("plot", self.plot)
def __parsePage(self, page):
self.plotkeywords = map(decode, re.findall(conf.strings["imdb_plotkeywords_re"],page, re.MULTILINE)) self.__setitem__("plotkeywords", self.plotkeywords)
def __parsePage(self, page):
match = re.findall(conf.strings["imdb_awards_re"], page, re.MULTILINE) if match: self.awards = decode(match[0].replace('\n',' ').strip()) self.__setitem__("awards", self.awards)
def __parsePage(self, page):
castsearch = re.compile(conf.strings["imdb_castsearch_re"], re.DOTALL) self.cast = re.findall( castsearch, page) x = 0 for member in self.cast: if not member[2]: self.cast[x] = tuple(map(decode,member[0:2])) x=x+1 self.__setitem__("cast", self.cast)
def __parsePage(self, page):
match = map(decode, re.findall(conf.strings["imdb_mpaa_re"], page, re.MULTILINE)) if match: self.mpaa = decode(match[0]) self.__setitem__("mpaa", self.mpaa)
def __parsePage(self, page):
match = re.findall(conf.strings["imdb_alsoknownas_re"], page, re.MULTILINE) if match: templist = decode(match[0]).split('<br>') for i in templist: if i.strip(): self.alsoknownas.append(i.strip()) self.__setitem__("alsoknownas", self.alsoknownas)
def __parsePage(self, page):
match = re.findall(conf.strings["imdb_color_re"], page, re.MULTILINE) if match: self.color = match[0] self.__setitem__("color", self.color)
def __parsePage(self, page):
match = re.findall(conf.strings["imdb_aspectratio_re"], page, re.MULTILINE) if match: self.aspectratio = match[0].strip() self.__setitem__("aspectratio", self.aspectratio)
def __parsePage(self, page):
self.soundmix = re.findall(conf.strings["imdb_soundmix_re"], page, re.MULTILINE) self.__setitem__("soundmix", self.soundmix)
def __parsePage(self, page):
self.company = map(decode, re.findall(conf.strings["imdb_company_re"], page, re.MULTILINE)) self.__setitem__("company", self.company)
def __parsePage(self, page):
match = re.findall(conf.strings["imdb_trivia_re"], page, re.DOTALL) if match: self.trivia = decode(re.sub(conf.strings["imdb_trivia_more_re"],'', match[0], re.DOTALL).replace("\n","").strip()) self.__setitem__("trivia", self.trivia)
def __parsePage(self, page):
if(options.update): try: conf = pythonbits_config() conf.set_location("config.xml") conf.read() update_url = conf.strings["update_url"] except: update_url = "https://github.com/Ichabond/Pythonbits/raw/master/config.xml" del conf opener = _MyOpener() newconf = opener.open(update_url) if (newconf.info()["Status"]=="200 O...
if(options.update): try: conf = pythonbits_config() conf.set_location(tempdir()+"config.xml") conf.read() update_url = conf.strings["update_url"] except: update_url = "https://github.com/Ichabond/Pythonbits/raw/master/config.xml" del conf opener = _MyOpener() newconf = opener.open(update_url) if (newconf.info()["Status...
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
conf.set_location("config.xml")
conf.set_location(tempdir()+"config.xml")
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
conf.read() except: __logerror("Cannot open config file") exit(1)
conf.read() except: update_url = "https://github.com/Ichabond/Pythonbits/raw/master/config.xml" del conf opener = _MyOpener() newconf = opener.open(update_url) if (newconf.info()["Status"]=="200 OK"): open(tempdir()+"config.xml", "w").write(newconf.read()) else: __logerror("Cannot update config file.")
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
print "[b]Description:[/b]"
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
print "[b]Information:[/b]"
print "[b]Information:[/b]" print "[quote]"
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
print "[quote]Wikipedia url: %s" % movie.wikiurl
print "Wikipedia url: %s" % movie.wikiurl
def upload(self): self.getDuration() try: subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait() subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "...
def handle_noargs(self, **options):
def handle(self, *args, **options):
def handle_noargs(self, **options): if options['clear']: log.info('Clearing all saved boundaries.') Boundary.objects.all().delete() BoundarySet.objects.all().delete()
sources = [s for s in SHAPEFILES if s in only]
sources = [s for s in SHAPEFILES if s.replace(' ', '') in only]
def handle_noargs(self, **options): if options['clear']: log.info('Clearing all saved boundaries.') Boundary.objects.all().delete() BoundarySet.objects.all().delete()
sources = [s for s in SHAPEFILES if s not in exceptions]
sources = [s for s in SHAPEFILES if s.replace(' ', '') not in exceptions]
def handle_noargs(self, **options): if options['clear']: log.info('Clearing all saved boundaries.') Boundary.objects.all().delete() BoundarySet.objects.all().delete()