rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
ptype = p.type(include_modifiers = False, include_namespace = True)
ptype = p.type(include_modifiers = False, include_namespace = True, remove_templates = True) qtype = p.type(include_modifiers = False, include_namespace = True)
def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x)
if modifiability_map[ptype]: updates.append('static_cast<Derived&>(*this)(x.%s())' % p.name())
if is_modifiable_type(qtype, modifiability_map): updates.append('static_cast<Derived&>(*this)(x.%s());' % p.name())
def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x)
text = re.sub('RETURN_TYPE', return_type, text)
text = re.sub('<RETURN_TYPE>', return_type, text)
def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x)
text = re.sub('CLASS_NAME', classname, text) text = re.sub('VISIT_TEXT', visit_text, text) text = re.sub('RETURN_STATEMENT', return_statement, text)
text = re.sub('<CLASS_NAME>', classname, text) text = re.sub('<VISIT_TEXT>', visit_text, text) text = re.sub('<RETURN_STATEMENT>', return_statement, text)
def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x)
type = p.type(include_modifiers = False, include_namespace = True)
type = p.type(include_modifiers = False, include_namespace = True, remove_templates = True)
def update_dependencies(all_classes, dependencies): changed = False for classname in all_classes: c = all_classes[classname] if dependencies[classname] == True: continue # check expression class dependencies if 'X' in c.modifiers(): for expr in c.expression_classes(): if dependencies[expr] == True: update_dependency(c...
if use_base_class_name and (self.classname != self.base_classname):
if self.use_base_class_name_ and (self.classname_ != self.base_classname_):
def class_definition(self, namespace = 'core', add_container_typedefs = True, add_constructor_overloads = False): classname = self.classname() superclass = self.superclass() f = self.constructor
arguments2.append('typename detail::enable_if_container<%s, %s>::type* = 0' % (template_parameter, p.type(False)[:-5])) parameters1.append('convert<%s>(%s)' % (p.type(False), p.name()))
arguments2.append('typename atermpp::detail::enable_if_container<%s, %s>::type* = 0' % (template_parameter, p.type(False)[:-5])) parameters1.append('atermpp::convert<%s>(%s)' % (p.type(False), p.name()))
def constructor_definitions(self, namespace, add_constructor_overloads = False): add_string_overload_constructor = add_constructor_overloads, add_container_overload_constructor = add_constructor_overloads classname = self.classname() arguments = self.constructor.argument_text() superclass = self.superclass() aterm = se...
make_classes('../../lps/include/mcrl2/modal_formula/state_formula.h', STATE_FORMULA_CLASSES, 'state_formula', generate_is_functions = True, superclass_aterm = 'StateFrm')
make_classes('../../lps/include/mcrl2/modal_formula/state_formula.h', STATE_FORMULA_CLASSES, 'state_formula', generate_is_functions = True)
def make_is_functions(filename, class_text, classname, namespace = 'core'): TERM_TRAITS_TEXT = r''' /// \\brief Test for a %s expression /// \\param t A term /// \\return True if it is a %s expression inline bool is_%s(const %s& t) { return %s::detail::gsIs%s(t); }
superclass_declaration = ''
superclass_declaration = ': atermpp::aterm_appl'
def class_definition(self, namespace = 'core', add_container_typedefs = True, add_constructor_overloads = False): classname = self.classname() superclass = self.superclass() f = self.constructor
text = text + atext
text = text + '\n\n' + atext
def class_definition(self, namespace = 'core', add_container_typedefs = True, add_constructor_overloads = False): classname = self.classname() superclass = self.superclass() f = self.constructor
arguments2.append('typename detail::enable_if_container<%s, %s>::type* = 0' % (template_parameter, p.type(False))) parameters1.append('convert<%s>(%s)' % (p.type(), p.name()))
arguments2.append('typename detail::enable_if_container<%s, %s>::type* = 0' % (template_parameter, p.type(False)[:-5])) parameters1.append('convert<%s>(%s)' % (re.sub('&', '', p.type()), p.name()))
def constructor_definitions(self, namespace, add_constructor_overloads = False): add_string_overload_constructor = add_constructor_overloads, add_container_overload_constructor = add_constructor_overloads classname = self.classname() arguments = self.constructor.argument_text() superclass = self.superclass() aterm = se...
fr = file(cache, 'rub')
fr = file(cache, 'r')
def _readDownloadedIds(self): cache = self.idsFilename() self.message_iid2fn = {} if not os.path.isfile(cache): for msg_fn, msg in self.iterBackups(logging=False): try: msg_iid = _getMailInternalId(msg) self.message_iid2fn[msg_iid] = msg_fn except: self.notifier.handleError(_("Error while reading MessageID from stored ...
fw = file(fn, 'wub')
fw = file(fn, 'w')
def _writeDownloadedIds(self): fn = self.idsFilename() if os.path.exists(fn): os.remove(fn) fw = file(fn, 'wub') for msg_iid, msg_fn in sorted(self.message_iid2fn.items(), key=lambda item: item[1]): try: line = '%s\t%s' % (msg_fn, msg_iid) print >> fw, line except: self.notifier.nError(_("Errorneous message in file: %s...
fr = codecs.open(fn, 'rub', 'utf-8')
fr = codecs.open(fn, 'r', 'utf-8')
def _readLabelAssignment(self): fn = self.labelFilename() self.message_iid2labels = {} if os.path.isfile(fn): fr = codecs.open(fn, 'rub', 'utf-8') for line in fr: items = line.split(None, 1) msg_fn = items[0] msg_iid = self.message_fn2iid.get(msg_fn, None) if msg_iid is not None: self.message_iid2labels[msg_iid] = self...
fw = codecs.open(fn, 'wub', 'utf-8')
fw = codecs.open(fn, 'w', 'utf-8')
def _writeLabelAssignment(self): self._backupLabelAssignment() fn = self.labelFilename() if os.path.exists(fn): os.remove(fn) fw = codecs.open(fn, 'wub', 'utf-8') for msg_iid, labels in sorted(self.message_iid2labels.items()): msg_fn = self.message_iid2fn.get(msg_iid) if msg_fn is None: # We are unable do determine the...
fr = file(stampFile, 'ru')
fr = file(stampFile, 'r')
def lastStamp(self): stampFile = self.stampFile() try: fr = file(stampFile, 'ru') for line in fr: last_time = line.strip() break fr.close() except IOError: last_time = None
fw = file(stampFile, 'wu')
fw = file(stampFile, 'w')
def updateStamp(self, last_time): if last_time is None: return
line = line.replace(match.group(), cmakeCacheVariables.get(name,""))
line = line.replace(match.group(), str(cmakeCacheVariables.get(name,"")))
def main(): """ Process any command line arguments. Query the build system to find the top-level binary directory, to find the CMakeCache.txt file. Query the CMakeCache.txt file to get a dictionary of all the cache variables. Read in the input file, make cache variable substitutions, and write the output file. """ ...
class Timings: def __init__(self): self.update = -1.0 self.configure = -1.0 self.build = -1.0 self.test = -1.0 def deepCopy(self): copyTimings = Timings() copyTimings.update = self.update copyTimings.configure = self.configure copyTimings.build = self.build copyTimings.test = self.test return copyTimings
def createConfigureFile(cmakeOptions, baseCmnd, trilinosSrcDir, configFileName): doConfigStr = "" doConfigStr += \ "EXTRA_ARGS=$@\n" \ "\n" \ +baseCmnd+ " \\\n" for opt in cmakeOptions: doConfigStr += opt + " \\\n" doConfigStr += \ "$EXTRA_ARGS" if trilinosSrcDir: doConfigStr += " \\\n"+trilinosSrcDir doConfigStr...
result = runBuildTestCase(inOptions, buildTestCase, timings.deepCopy())
result = runBuildTestCase(inOptions, buildTestCase, timings)
def runBuildTestCaseDriver(inOptions, baseTestDir, buildTestCase, timings): success = True buildTestCaseName = buildTestCase.name print "\n***" print "*** Doing build and test of "+buildTestCaseName+" ..." print "***\n" if buildTestCase.runBuildTestCase: try: echoChDir(baseTestDir) writeDefaultBuildSpecificConfigF...
createDir(basedir)
try: createDir(basedir) except: if not os.path.exists(basedir): raise
def DetectLatestCMakeBuilds(basedir, baseurl, vdir): url = ''.join([baseurl, "/", vdir, "/?C=M;O=D"]) filename = ''.join([basedir, "/CMake_", vdir, ".html"]) createDir(basedir) print "Querying " + url + "..." proxies = None # if None, use proxy from env var http_proxy if not options.httpProxy == "": proxies = {'http...
createDir(basedir)
try: createDir(basedir) except: if not os.path.exists(basedir): raise
def Download(basedir, url): cmps = url.rsplit("/", 1) href = cmps[1] filename = ''.join([basedir, "/", href]) print 'Downloading ' + href + '...' createDir(basedir) proxies = None # if None, use proxy from env var http_proxy if not options.httpProxy == "": proxies = {'http': options.httpProxy} opener = urllib.Fancy...
createDir(options.installDir)
try: createDir(options.installDir) except: if not os.path.exists(options.installDir): raise
def Install(basedir, url): cmps = url.rsplit("/", 1) href = cmps[1] if href[-4:] == ".zip": href = href[:-4] elif href[-7:] == ".tar.gz": href = href[:-7] dirname = ''.join([basedir, "/", href]) print 'Installing ' + href + '...' print ' src dir: [' + dirname + ']' print ' dst dir: [' + options.installDir + ']' i...
return "install-git"
return "install-git.py"
def getScriptName(self): return "install-git"
"\nLocal commits:" \ "\n--------------" \
"\nLocal commits (before amending the last commit):" \ "\n------------------------------------------------" \
def getLocalCommitsSummariesStr(inOptions): # Get the list of local commits other than this one rawLocalCommitsStr = getCmndOutput( "eg log --oneline "+inOptions.currentBranch+" ^origin/"+inOptions.currentBranch, True, workingDir=inOptions.trilinosSrcDir ) print \ "\nLocal commits:" \ "\n--------------" \ "\n" \ + ra...
"Local commits for this build/test group:\n" \ "----------------------------------------\n"
"Local commits for this build/test group (before amending the last commit):\n" \ "--------------------------------------------------------------------------\n"
def getLocalCommitsSummariesStr(inOptions): # Get the list of local commits other than this one rawLocalCommitsStr = getCmndOutput( "eg log --oneline "+inOptions.currentBranch+" ^origin/"+inOptions.currentBranch, True, workingDir=inOptions.trilinosSrcDir ) print \ "\nLocal commits:" \ "\n--------------" \ "\n" \ + ra...
return ("Other local commits for this build/test group: " + (", ".join(rawLocalCommitsStr.split("\n")))) + "\n"
if rawLocalCommitsStr: return ("Other local commits for this build/test group: " + (", ".join(rawLocalCommitsStr.split("\n")))) + "\n" return ""
def getLocalCommitsSHA1ListStr(inOptions): # Get the raw output from the last current commit log rawLocalCommitsStr = getCmndOutput( "eg log --pretty=format:'%h' "+inOptions.currentBranch+"^ ^origin/"+inOptions.currentBranch, True, workingDir=inOptions.trilinosSrcDir) return ("Other local commits for this build/test ...
echoRunSysCmnd("cp -r \"" + dirname + "/\" \"" + options.installDir + "\"")
echoRunSysCmnd("cp -r " + dirname + "/* " + options.installDir)
def Install(basedir, url): cmps = url.rsplit("/", 1) href = cmps[1] if href[-4:] == ".zip": href = href[:-4] elif href[-7:] == ".tar.gz": href = href[:-7] dirname = ''.join([basedir, "/", href]) print 'Installing ' + href + '...' print ' src dir: [' + dirname + ']' print ' dst dir: [' + options.installDir + ']' i...
raise Exception("Error, there must be at least one black line before the" \
raise Exception("Error, there must be at least one blank line before the" \
def getLastCommitMessageStrFromRawCommitLogStr(rawLogOutput): origLogStrList = [] pastHeader = False numBlankLines = 0 lastNumBlankLines = 0 foundStatusHeader = False for line in rawLogOutput.split('\n'): #print "\nline = '"+line+"'\n" if pastHeader: origLogStrList.append(line) if line == "": numBlankLines += 1 elif n...
buff = buff = "%d\t%d\n" % (int(currline[0])-counteroffset, int(currline[2])+offset)
buff = buff = "%d\t%d\n" % (int(currline[0])+offset, int(currline[2])+offset)
def dotranslation(infile, outfile, offset): """Translate Zoltan ordering format into Scotch format""" counteroffset = 1 - offset for line in infile: currline= re.split(' |\t',line) if (currline[0].isalpha()): continue buff = buff = "%d\t%d\n" % (int(currline[0])-counteroffset, int(currline[2])+offset) outfile.write(buf...
vertices = computevertices(file)
vertices = computevertices(file) + 1
def main(argv=None): if argv is None: argv = sys.argv try: opts, args = getopt.gnu_getopt(argv[1:], "hi:o:vn:", ["help", "output=", "input=", "verbose", "np=", "offset="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) if (len(args) != 1): # print help information and exit: usage() s...
clp.add_option( "--extra-configure-options", dest="extraConfigureOptions", type="string", default="", help="Extra options to add to the 'configure' cmmand for "+self.getProductName()+"." \ +" Note: This does not override the hard-coded configure options." ) clp.add_option( "--embed-rpath", dest="embedRPath", action="s...
def injectExtraCmndLineOptions(self, clp): clp.add_option( "--checkout-cmnd", dest="checkoutCmnd", type="string", default="git clone software.sandia.gov:/space/git/TrilinosToolset/gcc.BASE "+\ self.getBaseDirName(), help="Command used to check out "+self.getProductName()+" and dependent source tarball(s)." )
cmndLine += " --checkout-cmnd='" + inOptions.checkoutCmnd + "' \\\n"
cmndLine += " --checkout-cmnd='"+inOptions.checkoutCmnd+"' \\\n" if inOptions.extraConfigureOptions: cmndLine += " --extra-configure-options='"+inOptions.extraConfigureOptions+"' \\\n"
def echoExtraCmndLineOptions(self, inOptions): cmndLine = "" cmndLine += " --checkout-cmnd='" + inOptions.checkoutCmnd + "' \\\n" return cmndLine
echoRunSysCmnd("../"+gccSrcDir+"/configure --enable-languages='c,c++,fortran'"+\ " --disable-gnu-unique-object --prefix="+self.inOptions.installDir)
echoRunSysCmnd( "../"+gccSrcDir+"/configure --enable-languages='c,c++,fortran'"+\ " "+self.inOptions.extraConfigureOptions+\ " --prefix="+self.inOptions.installDir)
def doConfigure(self): echoChDir(self.gccSrcBaseDir) echoRunSysCmnd("ln -sf ../"+gmpSrcDir+" gmp") echoRunSysCmnd("ln -sf ../"+mpfrSrcDir+" mpfr") echoRunSysCmnd("ln -sf ../"+mpcSrcDir+" mpc") createDir(self.gccBuildBaseDir, True, True) echoRunSysCmnd("../"+gccSrcDir+"/configure --enable-languages='c,c++,fortran'"+\ " ...
echoRunSysCmnd("make "+self.inOptions.makeOptions + " install")
echoRunSysCmnd("make "+self.inOptions.makeOptions+" install") if self.inOptions.embedRPath: print "\nSet up rpath for GCC versions so that you don't need to set LD_LIBRARY_PATH ...\n" self.updateSpecsFile()
def doInstall(self): echoChDir(self.gccBuildBaseDir) echoRunSysCmnd("make "+self.inOptions.makeOptions + " install")
conn.send_frame('SUBSCRIBE', frame)
user.send_frame('SUBSCRIBE', frame)
def subscribe(self, user, conn=None, needs_auth=True):
def create_channel(self, conn, channel_name, options={}, needs_auth=False):
def create_channel(self, conn, channel_name, options={}, needs_auth=True):
def create_channel(self, conn, channel_name, options={}, needs_auth=False): if channel_name in self.channels: raise ExpectedException("Channel already exists") if needs_auth: cookie_string = conn and conn.get_cookie() or None form = { 'channel_name': channel_name, } success, callback_options = self.http_request('create...
self.unsubscribe(user, needs_auth=False)
self.unsubscribe(user, needs_auth=True, force_auth=True)
def user_disconnected(self, user): # TODO: remove this pointless check, it should never happen, right? if user not in self.subscribers: return self.unsubscribe(user, needs_auth=False)
def unsubscribe(self, user, conn=None, needs_auth=True):
def unsubscribe(self, user, conn=None, needs_auth=True, force_auth=False):
def unsubscribe(self, user, conn=None, needs_auth=True): if user not in self.subscribers: return if needs_auth and (self.moderated or self.moderated_unsubscribe): form = { 'channel_name': self.name, "user": user.get_name() } success, options = self.server.http_request('unsubscribe', user.get_cookie(conn), form) if not ...
if not success:
if not success or force_auth:
def unsubscribe(self, user, conn=None, needs_auth=True): if user not in self.subscribers: return if needs_auth and (self.moderated or self.moderated_unsubscribe): form = { 'channel_name': self.name, "user": user.get_name() } success, options = self.server.http_request('unsubscribe', user.get_cookie(conn), form) if not ...
os.path.join('hookbox', 'admin', 'static')
os.path.join('hookbox', 'admin', 'static'), os.path.join('hookbox', 'js_src')
def find_package_data(): targets = [ os.path.join('hookbox', 'static'), os.path.join('hookbox', 'admin', 'static') ] package_data = {'': reduce(list.__add__, [ '.git' not in d and [ os.path.join(d[len('hookbox/'):], e) for e in static_types ] or [] for (d, s, f) in reduce(list.__add__, [ [ i for i in os.walk(target) ] ...
form = { 'channel_name': self.name, 'payload': encoded_payload }
form = { 'channel_name': self.name, 'payload': json.dumps(encoded_payload) }
def publish(self, user, payload, needs_auth=True, conn=None, **kwargs): try: encoded_payload = json.loads(payload) except: raise ExpectedException("Invalid json for payload") payload = encoded_payload if needs_auth and (self.moderated or self.moderated_publish): form = { 'channel_name': self.name, 'payload': encoded_pa...
print 'DISCONNECTED! user', self.name
def remove_connection(self, conn): self.connections.remove(conn) if not self.connections: print 'DISCONNECTED! user', self.name # each call to user_disconnected might result in an immediate call # to self.channel_unsubscribed, thus modifying self.channels and # messing up our loop. So we loop over a copy of self.chann...
channel.update_options(**args)
channel.update_options(**options)
def frame_SET_CHANNEL_INFO(self, id, args): channel_name = args.pop('channel_name', None) channel = self.hookbox.get_channel(None, channel_name) channel.update_options(**args)
raise ExpectedException("Invalid json value for form key '%s'", % (key,)) for key in form
raise ExpectedException("Invalid json value for form key '%s'" % (key,)) for key in form:
def render_set_config(self, form, start_response): for key in form: try: form[key] = json.loads(form[key]) except: raise ExpectedException("Invalid json value for form key '%s'", % (key,)) for key in form if key in self._config_vars: self.server.config[key] = form.get(key) start_response('200 Ok', []) return json.dumps...
url += ":" + str(port or self.base_port) url += path
url = urlparse.urlunparse((scheme,host + ":" + str(port), '','','')) else: url = urlparse.urlunparse((scheme,host, '','',''))
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None, conn=None): if not full_path and self.config['cb_single_url']: full_path = self.config['cb_single_url'] if full_path: u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query...
response = self.http.request(method='POST', path=None, payload=form_body, headers=headers)
response = self.http.request(method='POST', path=path, payload=form_body, headers=headers)
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None, conn=None): if not full_path and self.config['cb_single_url']: full_path = self.config['cb_single_url'] if full_path: u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query...
form = { 'channel_name': self.name, 'payload': payload }
form = { 'channel_name': self.name, 'payload': json.dumps(payload) }
def publish(self, user, payload, needs_auth=True, conn=None, **kwargs): try: encoded_payload = json.loads(payload) except: raise ExpectedException("Invalid json for payload") payload = encoded_payload if needs_auth and (self.moderated or self.moderated_publish): form = { 'channel_name': self.name, 'payload': payload } ...
if (api_port, main_port) != (api_host, api_port):
if (main_host, main_port) != (api_host, api_port):
def run(self): if not self._bound_socket: self._bound_socket = eventlet.listen((self.config.interface, self.config.port)) eventlet.spawn(eventlet.wsgi.server, self._bound_socket, self._root_wsgi_app, log=EmptyLogShim()) # We can't get the main interface host, port from config, in case it # was passed in directly to th...
channel = self.server.get_channel(channel_name)
channel = self.server.get_channel(None, channel_name)
def render_publish(self, environ, start_response): form = get_form(environ) channel_name = form.get('channel_name', None) if not channel_name: raise Exception("Missing channel_name") payload = form.get('payload', 'null') originator = form.get('originator', None) channel = self.server.get_channel(channel_name) channel.p...
channel = self.server.get_channel(channel_name)
channel = self.server.get_channel(None, channel_name)
def render_set_channel_options(self, environ, start_response): form = get_form(environ) channel_name = form.get('channel_name', None) if not channel_name: raise Exception("Missing channel_name") del form['channel_name'] channel = self.server.get_channel(channel_name) channel.update_options(**form) start_response('200 O...
for key, val in form.items(): del form[key] form[key.encode('utf8')] = val.encode('utf8')
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if not full_path and self.config['cb_single_url']: full_path = self.config['cb_single_url'] if full_path: u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query else:
defaults._cookie_identifier = NoDefault defaults._secret = NoDefault
defaults._cookie_identifier = NoDefault() defaults._secret = NoDefault()
def _add_admin_options(self, parser, defaults): parser.add_option("-r", "--rest-secret", dest="rest_secret", type="string", default=defaults._rest_secret, metavar="SECRET", help="The SECRET token that must be in present in all rest api calls as the form variable \"secret\".") parser.add_option("-a", "--admin-password",...
defaults._cb_single_url = NoDefault defaults._rest_secret = NoDefault defaults._admin_password = NoDefault
defaults._cb_single_url = NoDefault() defaults._rest_secret = NoDefault() defaults._admin_password = NoDefault()
def _add_admin_options(self, parser, defaults): parser.add_option("-r", "--rest-secret", dest="rest_secret", type="string", default=defaults._rest_secret, metavar="SECRET", help="The SECRET token that must be in present in all rest api calls as the form variable \"secret\".") parser.add_option("-a", "--admin-password",...
if config['cb_single_url']: import urlparse u = urlparse.urlparse(config['cb_single_url']) self.base_host = u.hostname self.base_port = u.port or 80 self.base_path = u.path
def __init__(self, bound_socket, config, outputter): self.config = config self.interface = config['interface'] self.port = config['port'] self._bound_socket = bound_socket self._rtjp_server = rtjp_eventlet.RTJPServer()
path = full_path
u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if full_path: path = full_path else: if self.config.get('cb_single_url'): path = self.base_path else: path = self.base_path + '/' + self.config.get('cb_' + path_name) form['action'] = path_name if self.config['secret']: form['secret'] ...
if self.config.get('cb_single_url'): path = self.base_path else: path = self.base_path + '/' + self.config.get('cb_' + path_name)
path = self.base_path + '/' + self.config.get('cb_' + path_name) host = self.config["cbhost"] port = self.config["cbport"] if path_name:
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if full_path: path = full_path else: if self.config.get('cb_single_url'): path = self.base_path else: path = self.base_path + '/' + self.config.get('cb_' + path_name) form['action'] = path_name if self.config['secret']: form['secret'] ...
if self.config['secret']: form['secret'] = self.config['secret']
if self.config['webhook_secret']: form['secret'] = self.config['webhook_secret']
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if full_path: path = full_path else: if self.config.get('cb_single_url'): path = self.base_path else: path = self.base_path + '/' + self.config.get('cb_' + path_name) form['action'] = path_name if self.config['secret']: form['secret'] ...
http = httplib.HTTPConnection(self.base_host, self.base_port) url = "http://" + self.base_host if self.base_port != 80:
http = httplib.HTTPConnection(host, port) url = "http://" + host if port != 80:
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if full_path: path = full_path else: if self.config.get('cb_single_url'): path = self.base_path else: path = self.base_path + '/' + self.config.get('cb_' + path_name) form['action'] = path_name if self.config['secret']: form['secret'] ...
for channel in self.channels:
for (channel, channel_connections) in self.channels.items():
def _send_initial_subscriptions(self, conn): for channel in self.channels: frame = channel._build_subscribe_frame(self) conn.send_frame('SUBSCRIBE', frame)
form = { 'channel_name': self.name, 'payload': payload }
form = { 'channel_name': self.name, 'payload': encoded_payload }
def publish(self, user, payload, needs_auth=True, conn=None, **kwargs): try: encoded_payload = json.loads(payload) except: raise ExpectedException("Invalid json for payload") payload = encoded_payload if needs_auth and (self.moderated or self.moderated_publish): form = { 'channel_name': self.name, 'payload': payload } ...
for key, val in form.items(): del form[key] form[key.encode('utf8')] = val.encode('utf8')
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None): if not full_path and self.config['cb_single_url']: full_path = self.config['cb_single_url'] if full_path: u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query else:
payload = encoded_payload
def publish(self, user, payload, needs_auth=True, conn=None, **kwargs): try: encoded_payload = json.loads(payload) except: raise ExpectedException("Invalid json for payload")
payload = options.get('override_payload', encoded_payload)
payload = options.get('override_payload', payload)
def publish(self, user, payload, needs_auth=True, conn=None, **kwargs): try: encoded_payload = json.loads(payload) except: raise ExpectedException("Invalid json for payload")
if conn: set_cookie = response.getheader('Set-Cookie', '') conn.send_frame('SET_COOKIE', {'cookie': set_cookie})
if conn: set_cookie = response.getheader('Set-Cookie', '') if set_cookie: conn.send_frame('SET_COOKIE', {'cookie': set_cookie})
def http_request(self, path_name=None, cookie_string=None, form={}, full_path=None, conn=None): if not full_path and self.config['cb_single_url']: full_path = self.config['cb_single_url'] if full_path: u = urlparse.urlparse(full_path) host = u.hostname port = u.port or 80 path = u.path if u.query: path += '?' + u.query...
self.errors.append(e)
self.errors.append(e.message)
def _validate(self): if self.is_readonly(): return True
if self.model and type(self.model) != type(model): raise ValueError('You can only bind to another object of the same type you originally bound to (%s), not %s' % (type(self.model), type(model)))
if (self.model and type(self.model) != type(model) and not issubclass(model.__class__, self.original_cls)): raise ValueError('You can only bind to another object of the same type or subclass you originally bound to (%s), not %s' % (type(self.model), type(model)))
def rebind(self, model=None, session=None, data=None): """ Like `bind`, but acts on this instance. No return value. Not all parameters are treated the same; specifically, what happens if they are NOT specified is different: * if `model` is not specified, the old model is used * if `session` is not specified, FA tries ...
for k, v in self.doc().iteritems(): if not k.startswith('_'):
values = self.doc._properties.values() values.sort(lambda a, b: cmp(a.creation_counter, b.creation_counter)) for v in values: if getattr(v, 'name'): k = v.name
def __init__(self, model, session=None, data=None, prefix=None): self._fields = OrderedDict() self._render_fields = OrderedDict() self.model = self.session = None if model is not None and isinstance(model, schema.Document): BaseFieldSet.rebind(self, model.__class__, data=data) self.doc = model.__class__ self._bound_pk ...
raise NotImplementedError('%s is not mapped to a type' % v.__class__)
raise NotImplementedError('%s is not mapped to a type for field %s (%s)' % (v.__class__, k, v.__class__.__name__))
def __init__(self, model, session=None, data=None, prefix=None): self._fields = OrderedDict() self._render_fields = OrderedDict() self.model = self.session = None if model is not None and isinstance(model, schema.Document): BaseFieldSet.rebind(self, model.__class__, data=data) self.doc = model.__class__ self._bound_pk ...
if not isinstance(field, fields.Field): raise ValueError('Can only add Field objects; got %s instead' % field)
if not isinstance(field, fields.Field) and not isinstance(field, fields.AttributeField): raise ValueError('Can only add Field or AttributeField objects; got %s instead' % field)
def append(self, field): """Add a form Field. By default, this Field will be included in the rendered form or table.""" if not isinstance(field, fields.Field): raise ValueError('Can only add Field objects; got %s instead' % field) field.parent = self _fields = self._render_fields or self._fields _fields[field.name] = f...
except AttributeError:
except (AttributeError, UnmappedInstanceError):
def rebind(self, model=None, session=None, data=None): """ Like `bind`, but acts on this instance. No return value. Not all parameters are treated the same; specifically, what happens if they are NOT specified is different: * if `model` is not specified, the old model is used * if `session` is not specified, FA tries ...
and not isinstance(attr.impl, DynamicAttributeImpl)):
and not isinstance(attr.impl, DynamicAttributeImpl) and p not in discs):
def __init__(self, model, session=None, data=None, prefix=None): """ - `model`: a SQLAlchemy mapped class or instance. New object creation should be done by passing the class, which will need a default (no-parameter) constructor. After construction or binding of the :class:`~formalchemy.forms.FieldSet`, the instantia...
print '@'*8, token, stack
def balance(html, limit_words=None, ellipsis=' ...'): word_count = 0 tokens = tag_re.split(html) out = [] stack = [] for token in tokens: print '@'*8, token, stack if not token.startswith('<'): if limit_words and word_count > limit_words: break words = token.split() word_count += len(words) if limit_words and word_coun...
if element in block and stack:
if element in block and stack and stack[-1] not in block:
def balance(html, limit_words=None, ellipsis=' ...'): word_count = 0 tokens = tag_re.split(html) out = [] stack = [] for token in tokens: if not token.startswith('<'): if limit_words and word_count > limit_words: break words = token.split() word_count += len(words) if limit_words and word_count > limit_words: crop = li...
tag_re = re.compile('(<.*?>)', re.DOTALL)
tag_re = re.compile(r'(<>|<[^!].*?>|<!\[CDATA\[|\]\]>)', re.DOTALL | re.MULTILINE)
def get_words(s): return set([ word for word in lower(unicode(strip_tags_re.sub('', unicode(s))) ).translate(punct_map).split() if word not in stop_words])
tag_re = re.compile('(<.*?>)')
tag_re = re.compile('(<.*?>)', re.DOTALL)
def get_words(s): return set([ word for word in lower(unicode(strip_tags_re.sub('', unicode(s))) ).translate(punct_map).split() if word not in stop_words])
def redirect_to(request):
def redirect_url(request):
def redirect_to(request): return HttpResponseRedirect('/coco/home.html')
json_subcat = serializers.serialize("json", screenings, relations=('fieldofficer', 'animator','village',))
json_subcat = serializers.serialize("json", screenings, relations=('village',))
def get_screenings_online(request, offset, limit): if request.method == 'POST': return redirect('screenings') else: villages = get_user_villages(request) screenings = Screening.objects.filter(village__in = villages).distinct().order_by("-id")[offset:limit] if(screenings): json_subcat = serializers.serialize("json", scr...
sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID')
sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, SCREENING scr')
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.district_id = D.id AND D.state_id = '+str(args['id']) )
sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.screening_id = scr.id AND scr.village_id = VIL.id AND VIL.block_id = B.id AND B.district_id = D.id AND D.state_id = '+str(args['id']) )
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
sql.append(r""",VILLAGE VIL,BLOCK B WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.district_id = """+str(args['id']) )
sql.append(r""",VILLAGE VIL,BLOCK B WHERE SC.screening_id = scr.id AND scr.village_id = VIL.id AND VIL.block_id = B.id AND B.district_id = """+str(args['id']) )
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
sql.append(r""" ,VILLAGE VIL WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = """+str(args['id']) )
sql.append(r""" ,VILLAGE VIL WHERE SC.screening_id = scr.id AND scr.village_id = VIL.id AND VIL.block_id = """+str(args['id']) )
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
sql.append(r""" WHERE SC.video_id =VID.id AND VID.village_id = """+str(args['id']) )
sql.append(r""" WHERE SC.screening_id = scr.id AND scr.village_id = """+str(args['id']) )
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
sql.append(' WHERE SC.video_id = VID.id AND VID.VIDEO_PRODUCTION_END_DATE BETWEEN \''+args['from_date']+'\' AND \''+args['to_date']+ ' \' ') else: sql.append(' AND VID.VIDEO_PRODUCTION_END_DATE BETWEEN \''+args['from_date']+'\' AND \''+args['to_date']+ ' \' ')
sql.append(' WHERE SC.screening_id = scr.id AND scr.DATE BETWEEN \''+args['from_date']+'\' AND \''+args['to_date']+ ' \' ') else: sql.append(' AND scr.DATE BETWEEN \''+args['from_date']+'\' AND \''+args['to_date']+ ' \' ')
def video_tot_scr(**args): sql = [] sql.append(r' SELECT COUNT(DISTINCT SC.video_id) AS count FROM SCREENING_videoes_screened SC, VIDEO VID') if 'geog' in args: if args['geog'] == 'state': sql.append(r',VILLAGE VIL,BLOCK B, DISTRICT D WHERE SC.video_id =VID.id AND VID.village_id = VIL.id AND VIL.block_id = B.id AND B.d...
user = UserPermission.objects.get(username_id=user.id)
user = UserPermission.objects.get(username=user.id)
def login_view(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: # Correct password, and the user is marked "active" #auth.login(request, us...
PersonFormSet = inlineformset_factory(PersonGroups, Person,extra=3, exclude=('equipmentholder','relations','adopted_agricultural_practices',)) if request.method == 'POST': form = PersonGroupsForm(request.POST)
PersonFormSet = inlineformset_factory(PersonGroups, Person,extra=3, exclude=('equipmentholder','relations','adopted_agricultural_practices',)) if request.method == 'POST': form = PersonGroupsForm(request.POST) formset = PersonFormSet(request.POST, request.FILES) if form.is_valid(): saved_persongroup = form.save() pers...
def add_person_group(request): PersonFormSet = inlineformset_factory(PersonGroups, Person,extra=3, exclude=('equipmentholder','relations','adopted_agricultural_practices',)) if request.method == 'POST': form = PersonGroupsForm(request.POST) formset = PersonFormSet(request.POST, request.FILES) if form.is_valid(): saved...
if form.is_valid(): saved_persongroup = form.save() persongroup = PersonGroups.objects.get(pk=saved_persongroup.id) formset = PersonFormSet(request.POST, request.FILES, instance=persongroup) if formset.is_valid(): personformset = formset.save(commit=False) return HttpResponseRedirect('/admin/dashboard/persongroups/') e...
if formset.is_valid(): formset.save() return HttpResponseRedirect('/admin/dashboard/persongroups/') else: return render_to_response('add_person_group.html', {'form':form, 'formset':formset}) else: return render_to_response('add_person_group.html', {'form':form, 'formset':formset}) else: form = PersonGroupsForm() forms...
def add_person_group(request): PersonFormSet = inlineformset_factory(PersonGroups, Person,extra=3, exclude=('equipmentholder','relations','adopted_agricultural_practices',)) if request.method == 'POST': form = PersonGroupsForm(request.POST) formset = PersonFormSet(request.POST, request.FILES) if form.is_valid(): saved...
user = UserPermission.objects.get(id=user.id)
user = UserPermission.objects.get(username_id=user.id)
def login_view(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: # Correct password, and the user is marked "active" #auth.login(request, us...
JOIN VILLAGE V ON V.id = vid.village_id
JOIN VILLAGE V ON V.id = VID.village_id
def rule4(): rule = Rule.objects.get(pk=4) sql = """SELECT VID.id as content_object1, B.district_id FROM VIDEO VID JOIN VILLAGE V ON V.id = vid.village_id JOIN BLOCK B ON B.id = V.block_id WHERE DATEDIFF(VIDEO_PRODUCTION_END_DATE , VIDEO_PRODUCTION_START_DATE) > 12""" new_errors = [] if cursor.execute(sql): rows = cur...
form.fields['videoes_screened'].queryset = Video.objects.filter(village__block__district__state = states).distinct().order_by('title')
form.fields['videoes_screened'].queryset = Video.objects.filter(village__block__district__state__in = states).distinct().order_by('title')
def save_screening_online(request,id): PersonMeetingAttendanceInlineFormSet = inlineformset_factory(Screening, PersonMeetingAttendance, extra=1) if request.method == 'POST': if(id): screening = Screening.objects.get(id = id) form = ScreeningForm(request.POST, instance = screening) formset = PersonMeetingAttendanceInlin...
user = UserPermission.objects.get(username=user.id) return HttpResponse(user.role)
user = UserPermission.objects.filter(username=user.id) return HttpResponse(user[0].role)
def login_view(request): if request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: # Correct password, and the user is marked "active" #auth.login(request, us...
season = request.GET.get('season')
season = request.GET.getlist('season')
def video_search(request): video_suitable_for = request.GET.get('videosuitable') video_uploaded = request.GET.get('videouploaded') season = request.GET.get('season') lang = request.GET.get('lang') prac_arr = request.GET.getlist('prac') query = request.GET.get('query') page = request.GET.get('page') geog = request.GET.g...
vids = vids.filter(related_agricultural_practices__seasonality = season);
vids = vids.filter(related_agricultural_practices__seasonality__in = season);
def video_search(request): video_suitable_for = request.GET.get('videosuitable') video_uploaded = request.GET.get('videouploaded') season = request.GET.get('season') lang = request.GET.get('lang') prac_arr = request.GET.getlist('prac') query = request.GET.get('query') page = request.GET.get('page') geog = request.GET.g...
vids = vids.filter(related_agricultural_practices__id__in = [int(i) for i in prac_arr])
vids = vids.filter(related_agricultural_practices__id__in = map(int,prac_arr))
def video_search(request): video_suitable_for = request.GET.get('videosuitable') video_uploaded = request.GET.get('videouploaded') season = request.GET.get('season') lang = request.GET.get('lang') prac_arr = request.GET.getlist('prac') query = request.GET.get('query') page = request.GET.get('page') geog = request.GET.g...
tot_pages = int(math.ceil(float(vid_count)/15))
vid_per_page = 10 tot_pages = int(math.ceil(float(vid_count)/vid_per_page))
def video_search(request): video_suitable_for = request.GET.get('videosuitable') video_uploaded = request.GET.get('videouploaded') season = request.GET.get('season') lang = request.GET.get('lang') prac_arr = request.GET.getlist('prac') query = request.GET.get('query') page = request.GET.get('page') geog = request.GET.g...
vid_per_page = 10
def video_search(request): video_suitable_for = request.GET.get('videosuitable') video_uploaded = request.GET.get('videouploaded') season = request.GET.get('season') lang = request.GET.get('lang') prac_arr = request.GET.getlist('prac') query = request.GET.get('query') page = request.GET.get('page') geog = request.GET.g...
settings.append(r'<graph><type/><title>'+str(year)+'</title></graph>')
settings.append(r'<graph><type/><title>'+str(year)+'</title><balloon_text>{series}: Video Production = {value}</balloon_text></graph>')
def video_monthwise_bar_settings(request,geog,id): id = int(id) if 'from_date' in request.GET and request.GET['from_date'] \ and 'to_date' in request.GET and request.GET['to_date']: from_year = int(from_date.split('-')[0]) to_year = int(to_date.split('-')[0]); else: rs = run_query(database.video_month_bar(dict(geog =...
form.fields['animator'].queryset = Animator.objects.filter(home_village_id__in = villages).distinct().order_by('name')
form.fields['animator'].queryset = Animator.objects.filter(village__in = villages).distinct().order_by('name')
def save_animatorassignedvillage_online(request,id): if request.method == 'POST': if id: animatorassignedvillage = AnimatorAssignedVillage.objects.get(id=id) form = AnimatorAssignedVillageForm(request.POST, instance = animatorassignedvillage) else: form = AnimatorAssignedVillageForm(request.POST) if form.is_valid(): fo...
districts = District.objects.filter(state__in = states)
districts = districts | District.objects.filter(state__in = states)
def get_user_districts(request): #print request.session.get('username') #print request.session.get('user_id') user_permissions = UserPermission.objects.filter(username = request.session.get('user_id')) districts = District.objects.none() for user_permission in user_permissions: if(user_permission.role=='A'): districts ...
states = State.objects.filter(region = user_permission.region_operated) districts = District.objects.filter(state__in = states)
districts = districts | District.objects.filter(district_name = user_permission.district_operated)
def get_user_districts(request): #print request.session.get('username') #print request.session.get('user_id') user_permissions = UserPermission.objects.filter(username = request.session.get('user_id')) districts = District.objects.none() for user_permission in user_permissions: if(user_permission.role=='A'): districts ...