コード例 #1
0
def import_template():
    if os.path.isfile("./Resources/template.json"):
        with open('./Resources/template.json') as data_file:
            temp = json.load(data_file)
    else:
        temp = {}
        id = visuals.get_text_input("Template ID",
                                    "Please paste the ID of a sample file")
        if not id:
            exit()
        sheets = Info.get_sheets(id)
        temp['sheets'] = []
        for title in sheets:
            row_num = visuals.get_number_input(
                "Header Row",
                "What is the header row for sheet '{0}'".format(title))
            row = Info.get_row(id, title, row_num)
            rows = []
            if row_num > 1:
                rows = Info.get_first_col(id, title, row_num)
            temp['sheets'].append({
                'title': title,
                'header_row': row_num,
                'header_columns': row,
                'rows': rows
            })
    Template.set_template(temp)
コード例 #2
0
def main():
    pic_dir, nginx_dir = gen_pic_dir(pic_dir_prefix)
    get_word(get_word_loc, word_file)

    index = 1
    report_content = ""
    mail_title = Template.html_h3_title("如下查询结果可能有乱码,请确认")
    mail_title = Template.html_h3_title("本次运行的截图目录为:%s" % nginx_dir)
    mail_res = ""

    for word in word_list:
        print("process %d word" % index)
        try:
            # ready screenshot
            tmp_list = word.split()
            query = tmp_list[0]
            vrid = tmp_list[1]
            _craw_url = url_prefix + quote(query)
            vrstr = 'div.vrResult[id*="sogou_vr_' + vrid + '"],div.vrResult[id*="sogou_vr_kmap_' + vrid + '"]'
            vrstr = quote(vrstr)
            picname = pic_dir + "/" + "_".join(
                [str(index), quote(query), vrid + ".png"])
            nodejs_scrpit = 'spec-selector.js'
            path = '/search/odin/yinjingjing/python/garbled_detector/'


            child = subprocess.Popen(['/bin/node', nodejs_scrpit, \
                                      '-t', 'android', '-m', 'css', \
                                      '-k', vrstr, '-n', picname, \
                                      '-u', quote(_craw_url)], shell=False, \
                                      cwd = path, stdout=subprocess.PIPE)
            nodejs_res = child.stdout.read()
            if nodejs_res != b'0\n':
                utf8stdout("pupppeter ERROR. query:%s, vrid:%s, error:%s" %
                           (query, vrid, nodejs_res))
                continue
            else:
                garble, res = check_garbled(query, picname)
                utf8stdout(
                    "query:%s, vrid:%s, gDetect-api result:%s, is_garble:%s" %
                    (query, vrid, res, garble))
                if garble:
                    mail_info = "index:%d, query:%s, vrid:%s, gDetect-api result:%s" % (
                        index, query, vrid, res)
                    mail_res += "<p>" + mail_info + "</p>\n"

            child.wait()

            index = index + 1

        except Exception as err:
            print(err)
            index = index + 1
            continue
    #当检测有乱码结果时才发邮件
    #if mail_res:
    # utf8stdout("mail_res is not null, Send mail")
    report_content = mail_title + mail_res
    DataFile.write_full_file(report_tmp_path, report_content)
    Mail.sendMail("立知&图谱结果乱码检测", report_tmp_path, mail_to)
コード例 #3
0
ファイル: OLP.py プロジェクト: diogenes1991/Madisqe
    def WriteOLPClass(self):
        RECOLA_DICT = { 'Define Channels' : ''}

        TAB4  = '    '
        TAB8  = TAB4 + '    '
        TAB12 = TAB8 + '    '

        ORDER = {'Virt':'NLO','Real':'LO','Born':'LO'}

        ChannelCount = 1
        for Ch in self.Channels:
            ThisChannel = self.Channels[Ch]['Channel']
            
            ChannelName = ''
            
            Count = 1
            for Particle in ThisChannel.Initial:
                ChannelName += self.RECOLA_NAME[Particle.nam]+(' ' if Count < len(ThisChannel.Initial) else '')
                Count += 1
            
            Count = 1
            ChannelName += ' -> '
            for Particle in ThisChannel.Final:
                ChannelName += self.RECOLA_NAME[Particle.nam]+(' ' if Count < len(ThisChannel.Final) else '')
                Count += 1
            
            RECOLA_DICT['Define Channels'] += TAB12+'Recola::define_process_rcl('+str(ChannelCount)+',"'+ChannelName+'","'+ORDER[self.Channels[Ch]['Type']]+'");\n'
            RECOLA_DICT['Define Channels'] += TAB12+'ChannelIndex.insert({"'+str(ThisChannel)+'",'+str(ChannelCount)+'});\n'
            
            ChannelCount += 1

        RECOLA_OLP = Template(self.Templ,self.Path+'/Code/RECOLA_OLP.h',RECOLA_DICT)
        RECOLA_OLP.Write()
コード例 #4
0
ファイル: Scene.py プロジェクト: wingtofree/BLHX
 def __init__(self, game):
     super().__init__(game)
     self.enterAmbushTarget = Template.Target(game, (330, 252), (87, 64))
     self.leaveAmbushTarget = Template.Target(game, (238, 252), (83, 64))
     self.meet = Template.Template(game, "迎击", "./Subchapter/Meet.png")
     self.weighAnchor = Template.Template(game, "出击",
                                          "./Subchapter/WeighAnchor.png")
コード例 #5
0
ファイル: Translate.py プロジェクト: calandoa/zxite
def Translate():

    RegistryGen.GenerateAll()

    print "%s:" % root
    os.chdir(os.path.join(root, "base"))
    print "%s:" % os.getcwd()
    for e in exts:
        templateFile = os.path.join(root, "base",
                                    "SplitVector" + templateExts[e])
        for n in sizes:
            name = os.path.join(root, "base", "SplitVector_" + n + e)
            argv = [templateFile, name, "N=" + n, "T=" + type[n], "L=C~"]
            Template.expand(argv)

    os.chdir(os.path.join(root, "java"))
    print "%s:" % os.getcwd()
    XLang.translateArg(os.path.join(root, "base"), ".java")
    XLang.translateArg(os.path.join(root, "lexers"), ".java")

    os.chdir(os.path.join(root, "csharp"))
    print "%s:" % os.getcwd()
    XLang.translateArg(os.path.join(root, "base"), ".cs")
    XLang.translateArg(os.path.join(root, "lexers"), ".cs")

    os.chdir(os.path.join(root, "tentacle", "java"))
    print "%s:" % os.getcwd()
    XLang.translateArg(os.path.join(root, "tentacle", "cxx"), ".java")

    os.chdir(os.path.join(root, "tentacle", "csharp"))
    print "%s:" % os.getcwd()
    XLang.translateArg(os.path.join(root, "tentacle", "cxx"), ".cs")
コード例 #6
0
ファイル: Translate.py プロジェクト: calandoa/zite
def Translate():
	
	RegistryGen.GenerateAll()
	
	print "%s:" % root
	os.chdir(os.path.join(root, "base"))
	print "%s:" % os.getcwd()
	for e in exts:
		templateFile = os.path.join(root, "base", "SplitVector" + templateExts[e])
		for n in sizes:
			name = os.path.join(root, "base", "SplitVector_" + n + e)
			argv = [templateFile, name, "N=" + n, "T="+type[n], "L=C~"]
			Template.expand(argv)
			
	os.chdir(os.path.join(root, "java"))
	print "%s:" % os.getcwd()
	XLang.translateArg(os.path.join(root, "base"), ".java")
	XLang.translateArg(os.path.join(root, "lexers"), ".java")
	
	os.chdir(os.path.join(root, "csharp"))
	print "%s:" % os.getcwd()
	XLang.translateArg(os.path.join(root, "base"), ".cs")
	XLang.translateArg(os.path.join(root, "lexers"), ".cs")

	os.chdir(os.path.join(root, "tentacle", "java"))
	print "%s:" % os.getcwd()
	XLang.translateArg(os.path.join(root, "tentacle", "cxx"), ".java")

	os.chdir(os.path.join(root, "tentacle", "csharp"))
	print "%s:" % os.getcwd()
	XLang.translateArg(os.path.join(root, "tentacle", "cxx"), ".cs")
コード例 #7
0
ファイル: OLP.py プロジェクト: diogenes1991/Madisqe
 def WriteSeeds(self):
     Count = 1
     for Ch in self.ReducedChannels:
         Dictionary = self.ReducedChannels[Ch]['Dictionary']
         FileName=self.Path+'/NLOX_Process/'+Ch+'.in'
         ChannelSeed = Template(self.Seed,FileName,Dictionary)
         ChannelSeed.Write()
         Count += 1  
コード例 #8
0
def add_sheet():
    title = visuals.get_app().getEntry("title")
    cols = visuals.get_app().getTextArea("cols").split('\n')
    index = int(visuals.get_app().getSpinBox("Location in file"))
    Bulk.addSheet(title, cols, index)
    Template.add_sheet(title, cols, index)
    visuals.get_app().setEntry("title", "")
    visuals.get_app().clearTextArea("cols")
コード例 #9
0
def delete_sheet():
    title = visuals.get_app().getTabbedFrameSelectedTab("SheetFrame")
    if visuals.get_app().yesNoBox(
            "Confirm Delete",
            "Are you sure you delete sheet '{0}'?".format(title)):
        Bulk.deleteSheet(title)
        Template.delete_sheet(title)
        Info.deleteSheet(title)
        visuals.edit_files()
コード例 #10
0
    def __init__(self):
        self.templater = Template()
        self.template_setup = "C:\\Users\\enrique.nieto\\Documents\\develops\\omas\\build_system\\py_setup.py"
        self.build_path = "C:\\Users\\enrique.nieto\\Documents\\develops\\Node\\ticker\\dist\\"
        self.build_script = "open_server.py"
        self.build_script_lib = "lib"

        self.dependences_path = self.build_path + "depend\\"
        self.build_dist = self.build_script.split(".")[0] + "_dist"
コード例 #11
0
def add_row():
    sheet = visuals.get_app().getLabel("title").split("'")[1]
    new_row = visuals.get_app().textBox(
        "Add Row",
        "Please enter a name for the new row in sheet '{0}':".format(sheet))
    if new_row:
        Bulk.add_row(sheet, new_row)
        Template.add_row(sheet, new_row)
        visuals.get_app().changeOptionBox("rows", Template.get_rows(sheet), 0)
コード例 #12
0
    def __init__(self, game):
        super().__init__(game)
        self.enterAmbushRect = gc.Rect(330, 252, 87, 64)
        self.leaveAmbushRect = gc.Rect(238, 252, 83, 64)

        self.meetAct = Action.ClickAction(
            game, Template.Template("迎击", "./Subchapter/Meet.png"))
        self.weighAnchorAct = Action.ClickAction(
            game, Template.Template("出击", "./Subchapter/WeighAnchor.png"))
コード例 #13
0
ファイル: DoDoc_styles.py プロジェクト: peterdemin/DoDoc
 def startElement(self, name, attrs):
     self.putCurrent_text()
     if not self.node:
         self.node = self.doc.createElement(name)
         self.doc.appendChild(self.node)
     else:
         elem = self.doc.createElement(name)
         self.node = self.node.appendChild(elem)
     Template.setAttributes(self.doc, self.node, attrs)
     self.cur_text = []
コード例 #14
0
ファイル: Clang-TidyFormat.py プロジェクト: WattsUp/Pancake
def fixTidyFiles(applyReplacements, tmpdir, quiet):
    if not quiet:
        print("Applying tidy fixes...")

    try:
        cmd = [applyReplacements, "-format", "-style=file", tmpdir]
        Template.call(cmd)
    except Exception:
        print("Error applying fixes.\n", file=sys.stderr)
        traceback.print_exc()
コード例 #15
0
def rename_sheet():
    title = visuals.get_app().getTabbedFrameSelectedTab("SheetFrame")
    new_title = visuals.get_app().textBox(
        "Rename " + title,
        "Please enter a new name for sheet '{0}':".format(title))
    if new_title:
        Bulk.renameSheet(title, new_title)
        Template.rename_sheet(title, new_title)
        Info.rename_sheet(title, new_title)
        visuals.edit_files()
コード例 #16
0
ファイル: Scene.py プロジェクト: wingtofree/BLHX
 def __init__(self, game):
     super().__init__(game)
     self.back1 = Template.Template(game, "返回", "./Exercise/Back.png")
     self.operation = Template.Template(game, "演习",
                                        "./Exercise/Operation.png")
     self.firstOne = Template.Target(game, (50, 128), (160, 228))
     self.startExercise = Template.Template(game, "开始演习",
                                            "./Exercise/StartExercise.png")
     self.weighAnchor = Template.Template(game, "出击",
                                          "./Exercise/WeighAnchor.png")
コード例 #17
0
ファイル: __init__.py プロジェクト: navyTensor/HamiltonianPy
def init(directory, project, authors, email, readme, license, gitignore):
    '''
    Initialize a project.

    Parameters
    ----------
    directory : str
        The directory where to store the project.
    project : str
        The project name.
    authors : str
        The authors, separated by commas, of the project.
    email : str
        The contact email.
    readme : str
        The description of the project.
    license : 'T','t','F','f'
        'T'/'t' for adding a GNU GPL v3.0 LICENSE file and 'F'/'f' for not.
    gitignore : 'T','t','F','f'
        'T'/'t' for adding a gitignore file and 'F'/'f' for not.
    '''
    pdir = '%s/%s' % (directory, project)
    ddir, rdir, sdir, ldir = '%s/data' % pdir, '%s/result' % pdir, '%s/source' % pdir, '%s/log' % pdir
    dirs = [pdir, ddir, rdir, sdir, ldir]
    for folder in dirs:
        if not os.path.exists(folder): os.makedirs(folder)
    with open('%s/README.md' % pdir, 'w') as fout:
        fout.write('# %s' % project)
        fout.write('\n')
        if readme:
            fout.write(readme)
            fout.write('\n')
        if authors != 'Anonymous':
            fout.write('\nAuthors\n')
            fout.write('-------\n')
            fout.write('\n'.join('* %s' % author.lstrip()
                                 for author in authors.split(',')))
            fout.write('\n')
        if email:
            fout.write('\nContact\n')
            fout.write('-------\n')
            fout.write('%s\n' % email)
            fout.write('\n')
    if license.upper() == 'T':
        with open('%s/LICENSE' % pdir, 'w') as fout:
            fout.write(Template.license(authors))
    if gitignore.upper() == 'T':
        with open('%s/.gitignore' % pdir, 'w') as fout:
            fout.write(Template.gitignore())
    with open('%s/manager.py' % pdir, 'w') as fout:
        fout.write(Template.manager())
    with open('%s/config.py' % sdir, 'w') as fout:
        fout.write(Template.config())
    with open('%s/__init__.py' % sdir, 'w') as fout:
        fout.write('from config import *\n')
コード例 #18
0
def add_col():
    sheet = visuals.get_app().getLabel("title").split("'")[1]
    new_col = visuals.get_app().textBox(
        "Add Column",
        "Please enter a name for the new columns in sheet '{0}':".format(
            sheet))
    if new_col:
        Bulk.add_column(sheet, new_col)
        Template.add_column(sheet, new_col)
        visuals.get_app().changeOptionBox("cols", Template.get_columns(sheet),
                                          0)
コード例 #19
0
ファイル: DoDoc_styles.py プロジェクト: peterdemin/DoDoc
def test():
    from DoXML import DoXML
    doc = DoXML()
    s = Stylesheet_default()
    doc.table('a')
    doc.row()
    doc.text('test', u'Text of <red>Red</red> color')
    #raw_xml = '<test></test>'
    source = xml.dom.minidom.parseString(doc.doc.toxml().encode('utf8'))
    Template.iterNode(source, source.firstChild, s)
    print s.doc.toprettyxml()
コード例 #20
0
def delete_col():
    sheet = visuals.get_app().getLabel("title").split("'")[1]
    col = visuals.get_app().getOptionBox("cols")
    if visuals.get_app().yesNoBox(
            "Confirm Delete",
            "Are you sure you delete column '{0}' from sheet '{1}'?".format(
                col, sheet)):
        Bulk.delete_column(sheet, col)
        Template.delete_column(sheet, col)
        Info.delete_columns(sheet)
        visuals.get_app().changeOptionBox("cols", Template.get_columns(sheet),
                                          0)
コード例 #21
0
def Show():
    "Edit filter."

    # Load the display template
    if Form["cmd"].value == "incoming":
        T = Template.Template("incoming.html")
        T["FilePath"] = Filename = CgiUtil.ExpandUser(Defaults.FILTER_INCOMING)
    else:
        T = Template.Template("outgoing.html")
        T["FilePath"] = Filename = CgiUtil.ExpandUser(Defaults.FILTER_OUTGOING)

    # Get file
    if CgiUtil.TestTextFilePath(Filename):
        try:
            F = open(Filename)
            T["FileContents"] = F.read()
            F.close()
        except IOError:
            T["FileContents"] = ""
    else:
        T["FileContents"] = "(File is not accessible.)"

    # Are we allowed to save?
    if PVars[("NoOverride", "MayEditFilters")][0].lower() == "n":
        T["SaveButton"]
    else:
        # Did they try to save?
        if Form.has_key("subcmd"):

            # Make sure the list is properly formatted
            if Form.has_key("filter"):
                Contents = Form["filter"].value
            else:
                Contents = ""
            Contents = re.sub("\r\n", "\n", Contents)
            Contents = re.sub("\n*$", "", Contents)
            Contents += "\n"

            if CgiUtil.TestTextFilePath(Filename):
                try:
                    F = open(Filename, "w")
                    F.write(Contents)
                    F.close()
                    T["FileContents"] = Contents
                except IOError, ErrStr:
                    CgiUtil.TermError(
                        "Unable to save filter.", "Insufficient privileges",
                        "save filter", "%s<br>%s" %
                        (ErrStr, CgiUtil.FileDetails("Filter", Filename)),
                        "Change file permissions on <tt>%s</tt>" % Filename)
            else:
                FileContents = "(File is not accessible.)"
コード例 #22
0
def rename_col():
    sheet = visuals.get_app().getLabel("title").split("'")[1]
    col = visuals.get_app().getOptionBox("cols")
    new_col = visuals.get_app().textBox(
        "Rename Column",
        "Please enter a new name for column '{0}' in sheet '{1}':".format(
            col, sheet))
    if new_col:
        Bulk.rename_column(sheet, col, new_col)
        Template.rename_column(sheet, col, new_col)
        Info.rename_column(sheet, col, new_col)
        visuals.get_app().changeOptionBox("cols", Template.get_columns(sheet),
                                          0)
コード例 #23
0
ファイル: HueControl.py プロジェクト: Dragor2/HueControl
 def index(self):
     # for debug purposes:
     #HueBridge.update()
     template = mako.template.Template(filename='plugins/HueControl/HueControl.tmpl')
     try:
         # Check the authentication with the bridge
         HueBridge.authenticate()
         HueBridge.update()
     except ConnectionException as e:
         return Template.render_template("", error="Bridge is not authenticated! Press the link button and <a href=\"\"> try again</a>!")
         
     rendered_template = template.render(lights=HueBridge.lights, groups=HueBridge.groups)
     return Template.render_template(rendered_template)
コード例 #24
0
def send_mail(task_id):
    try:
        report_content = ""
        url = "http://fs.sogou/lizhi_accu_compare/mission_list/" + str(
            task_id) + "/"
        mail_title = Template.html_h3_title("立知结果精度对比运行完毕,请对结果进行标注:")
        mail_content = Template.html_p(url)

        report_content = mail_title + mail_content
        DataFile.write_full_file(report_tmp_path, report_content)
        Mail.sendMail("立知结果精度对比运行完毕,请对结果进行标注", report_tmp_path, mail_to)
    except Exception as err:
        print("[send_mail]:%s" % err)
コード例 #25
0
To import a class from a module, use from module import class.

Code:
# Import Template
from string import Template


Instructions 2/3
Complete the template using $tool and $description identifiers.

Hint
Remember that the syntax for writing a template is Template("$identifier1 text $indentifier2").

Code:
# Import Template
from string import Template

# Create a template
wikipedia = Template("$tool is a $description")


Instructions 3/3
Substitute identifiers with the correct tool and description variables in the template and print out the results.

Hint
To substitute the identifier1 and identifier2 in the template string created, use string.substitute(). 
Don't forget to specify identifier1=name and identifier2=description inside each call.

Code:
# Import Template
from string import Template

# Create a template
wikipedia = Template("$tool is a $description")

# Substitute variables in template
print(wikipedia.substitute(tool=tool1, description=description1))
print(wikipedia.substitute(tool=tool2, description=description2))
print(wikipedia.substitute(tool=tool3, description=description3))

Template strings are a simpler string substitution mechanism and even though it's less powerful, 
it's the right choice when you are not sure about the source of strings.


2.11. Identifying prices
After you showed your report to your boss, he came up with the idea of offering courses to the company's users on some of the tools you studied. 
In order to make a pilot test, you will send an email offering a course about one of the tools, randomly chosen from your dataset. 
You also mention that the estimated fee needs to be paid on a monthly basis.

For writing the email, you will use Template strings. 
You remember that you need to be careful when you use the dollar sign since it is used for identifiers in this case.
コード例 #26
0
def move_col():
    sheet = visuals.get_app().getLabel("title").split("'")[1]
    col = visuals.get_app().getOptionBox("cols")
    loc = visuals.get_app().textBox(
        "Move Column",
        "Please enter the location (A, B, etc) to which you would like to move column "
        "'{0}' in sheet '{1}':".format(col, sheet))
    if loc:
        index = Info.col_to_index(loc)
        Bulk.move_column(sheet, col, index)
        Template.move_column(sheet, col, index)
        Info.delete_columns(sheet)
        visuals.get_app().changeOptionBox("cols", Template.get_columns(sheet),
                                          0)
コード例 #27
0
ファイル: OLP.py プロジェクト: diogenes1991/Madisqe
    def WriteOLPClass(self):
        OLPDICT = {'Define Channels':''}

        TAB4='    '
        TAB8=TAB4+TAB4
        TAB12=TAB8+TAB4
        ChannelCount = 0
        for Ch in self.ReducedChannels:
            ThisChannel = self.ReducedChannels[Ch]['Channel']
            OLPDICT['Define Channels'] += TAB12+'ChannelIndex.insert({"'+str(ThisChannel)+'",'+str(ChannelCount)+'});\n'
            ChannelCount += 1

        NLOX_OLP = Template(self.Templ,self.Path+'/Code/NLOX_OLP.h',OLPDICT)
        NLOX_OLP.Write()
コード例 #28
0
 def __init__(self, game):
     super().__init__(game)
     self.ttcAct = Action.ClickAction(
         game,
         Template.Template("点击继续", "./Battle/TTC.png"),
         0.85,
         specifiedRect=gc.Rect(50, 420, 850, 130))
     self.ttcAct2 = Action.ClickAction(
         game,
         Template.Template("点击继续2", "./Battle/TTC2.png"),
         specifiedRect=gc.Rect(50, 420, 850, 130))
     self.performanceAct = Action.ClickAction(
         game, Template.Template("性能", "./Battle/Performance.png"))
     self.confirmAct = Action.ClickAction(
         game, Template.Template("确认", "./Battle/Confirm.png"))
コード例 #29
0
def move_sheet():
    title = visuals.get_app().getTabbedFrameSelectedTab("SheetFrame")
    max = len(Template.get_sheets())
    index = visuals.get_app().numberBox(
        "New Index",
        "Please pick a new index, min of 1, max of {0}:".format(max))
    if index and 0 < index <= max:
        Bulk.moveSheet(title, index)
        Template.moveSheet(title, index)
        Info.invalidate_indexes()
        visuals.edit_files()
    elif index and (index < 0 or index > max):
        visuals.get_app().errorBox(
            "Number Error",
            "The index you entered was outside the acceptable range")
コード例 #30
0
 def __init__(self, params, calib_data, hourly_data, daily_data,
              monthly_data):
     self.logger = logging.getLogger('pywws.Tasks.RegularTasks')
     self.params = params
     self.calib_data = calib_data
     self.hourly_data = hourly_data
     self.daily_data = daily_data
     self.monthly_data = monthly_data
     # get directories
     self.work_dir = self.params.get('paths', 'work', '/tmp/weather')
     self.template_dir = self.params.get(
         'paths', 'templates', os.path.expanduser('~/weather/templates/'))
     self.graph_template_dir = self.params.get(
         'paths', 'graph_templates',
         os.path.expanduser('~/weather/graph_templates/'))
     # create calibration object
     self.calibrator = Calib(self.params)
     # create templater object
     self.templater = Template.Template(self.params, self.calib_data,
                                        self.hourly_data, self.daily_data,
                                        self.monthly_data)
     # create plotter objects
     self.plotter = Plot.GraphPlotter(self.params, self.calib_data,
                                      self.hourly_data, self.daily_data,
                                      self.monthly_data, self.work_dir)
     self.roseplotter = WindRose.RosePlotter(self.params, self.calib_data,
                                             self.hourly_data,
                                             self.daily_data,
                                             self.monthly_data,
                                             self.work_dir)
     # directory of service uploaders
     self.services = dict()
     # create a YoWindow object
     self.yowindow = YoWindow.YoWindow(self.calib_data)
     # get local time's offset from UTC, without DST
     now = self.calib_data.before(datetime.max)
     if not now:
         now = datetime.now()  # was kenmc utcnow
     time_offset = Local.utcoffset(now) - Local.dst(now)
     print "Time Offset = %s" % time_offset
     # get daytime end hour, in UTC
     self.day_end_hour = eval(params.get('config', 'day end hour', '21'))
     self.day_end_hour = (self.day_end_hour -
                          (time_offset.seconds / 3600)) % 24
     # convert config from underground/metoffice to new services
     for section in ('live', 'logged', 'hourly', '12 hourly', 'daily'):
         services = eval(self.params.get(section, 'services', '[]'))
         for svc in ('underground', 'metoffice'):
             if self.params.get(section, svc) == 'True':
                 if svc not in services:
                     services.append(svc)
             self.params._config.remove_option(section, svc)
         self.params.set(section, 'services', str(services))
     # create service uploader objects
     for section in ('live', 'logged', 'hourly', '12 hourly', 'daily'):
         for service in eval(self.params.get(section, 'services', '[]')):
             if service not in self.services:
                 self.services[service] = ToService(self.params,
                                                    self.calib_data,
                                                    service_name=service)
コード例 #31
0
    def BecomeUser(self):
        "Set up everything to *BE* the user."
        Match = re.search("(.+)/$", self.Vars["HOME"])
        if Match:
            self.Vars["HOME"] = Match.group(1)
        os.environ["HOME"] = self.Vars["HOME"]
        self.__suid__("user")
        self.Valid = 1

        # Now that we know who we are, get our defaults
        from TMDA import Errors
        try:
            from TMDA import Defaults
        except Errors.ConfigError, (ErrStr):
            if self[("NoOverride", "MayInstall")][0].lower() == "y":
                if (os.environ["TMDA_CGI_MODE"] == "no-su"):
                    CgiUtil.TermError(
                        "Install failed", "Install not allowed in no-su mode",
                        "install", "",
                        "Either recompile in another mode or install TMDA manually."
                    )
                raise CgiUtil.NotInstalled, (ErrStr, self)
            T = Template.Template("no-install.html")
            T["ErrMsg"] = ErrStr
            print T
            sys.exit()
コード例 #32
0
ファイル: Clang-TidyFormat.py プロジェクト: WattsUp/Pancake
def tidyFiles(clangTidy, compilationDatabase, tmpdir, maxTasks, files, quiet,
              verbose):
    with open(compilationDatabase, "r") as file:
        database = json.load(file)
    compileCommandFiles = [
        Template.makeAbsolute(entry["file"], entry["directory"])
        for entry in database
    ]

    taskQueue = queue.Queue(maxTasks)
    failedCommands = []
    lock = threading.Lock()
    anyNotTidy = False
    for _ in range(maxTasks):
        t = threading.Thread(target=runTidy,
                             args=(clangTidy, taskQueue, lock, failedCommands,
                                   compilationDatabase, tmpdir, quiet, verbose,
                                   anyNotTidy))
        t.daemon = True
        t.start()

    # Fill the queue with files.
    for name in files:
        if name in compileCommandFiles:
            taskQueue.put(name)

    # Wait for all threads to be done.
    taskQueue.join()
    if len(failedCommands) != 0:
        print("Failed executing commands:", file=sys.stderr)
        for cmd in failedCommands:
            print(cmd, file=sys.stderr)
        return False
    return not anyNotTidy
コード例 #33
0
    def run(self, script, vars=None, runtemplate=False):
        if not vars:
            vars = {}

        if isinstance(script, (str, unicode)):
            f = file(script)
        else:
            f = script

        self.oldworkpath = os.getcwd().replace('\\', '/')

        vars['_workpath'] = self.oldworkpath

        if runtemplate:
            from StringIO import StringIO
            buf = StringIO()
            template = Template.Template()
            template.load(f, 'text')
            buf.write(template.value(values=vars))
            buf.seek(0)
            f = buf

        try:
            lines = csv.reader(f, delimiter=' ')
            for v in lines:
                if v:
                    self._do(vars, *v)
        finally:
            os.chdir(self.oldworkpath)
コード例 #34
0
ファイル: Package.py プロジェクト: wubaihua/JADE-NAMD
    def run(self):
        """
        raise the calc. code.
        """
        # load interface file
        interface = tools.load_data(self.files['interface'])
        it = int(interface['parm']['i_time'])
 
        qm_method = int(self.dyn['quantum']['qm_method'])
        print "QM_METHOD: ", qm_method
        
        config = self.config
        # 
        # make template
        Template(self.config)
        # Start the QC calculations
        if it == 0:
            firstStep(config)
            buildSOC(config)
            buildNAC(config)
        elif it > 0:
            nextStep(config)
            buildSOC(config)
            buildNAC(config)
        else:
            print "Error: keyword 'it':", it
            sys.exit(0)                
        
        return
コード例 #35
0
ファイル: pyCompilerWin.py プロジェクト: ennima/omas
	def __init__(self):
		self.templater = Template()
		self.template_setup = "C:\\Users\\enrique.nieto\\Documents\\develops\\omas\\build_system\\py_setup.py"
		self.build_path = "C:\\Users\\enrique.nieto\\Documents\\develops\\Node\\ticker\\dist\\"
		self.build_script = "open_server.py"
		self.build_script_lib ="lib"
		
		self.dependences_path = self.build_path + "depend\\"
		self.build_dist = self.build_script.split(".")[0]+"_dist"
コード例 #36
0
 def setUp(self):
     self.template = Template('''Returns one or more subgroups of the match. 
         If there is a single argument, the result is a single string; 
         if there are multiple arguments, the result is a tuple with one item per argument. 
         Without arguments, group1 defaults to zero (the whole match is returned).
         ${onezzzzzzzzzzz}, ${twozzzzzzzzzzz}, ${threezzzzzzzzz}, ${fourzzzzzzzzzz}, ${fivezzzzzzzzzz}''')
     self.template.set('onezzzzzzzzzzz', '1')
     self.template.set('twozzzzzzzzzzz', '2')
     self.template.set('threezzzzzzzzz', '3')
     self.template.set('fourzzzzzzzzzz', '4')
     self.template.set('fivezzzzzzzzzz', '5')
コード例 #37
0
	def canvasTemplate(self, action):
		[width, height] = Template.getTemplateData()
		filename = 'reference_images/player.png'
		grid_locations = action_grid_map[action]
		self.image_names = inverse_action_grid_map[action]
		images = []
		
		#Gets all the images for each action
		for location in grid_locations:
			image_location = SaveToPlayerFile.getImagePosition(location[0], location[1])
			box = (image_location[0], image_location[1], image_location[0] + width, image_location[1] + height)
			tempIm = Image.open(filename)
			tempIm = tempIm.crop(box)
			images.append(tempIm)
		
		#Puts all the possible pictures in a new folder and opens them	
		[possibleIms, self.possible_names] = custom_utils.find_action_images(action)
				
		y = 0
		#Puts a picture of each step in the action for the user to drag onto
		for i in range(len(self.image_names)):
			self.canvas.create_text(200, y,
				text = self.image_names[i])
			y = y + 5
			
			im = ImageTk.PhotoImage(images[i])
			label = Tkinter.Label(image = im)
			label.image = im
			
			self.canvas.create_image(200, y,
				image = label.image,
				anchor = "nw")
			y = y + 100
		
		y = 0
		#Puts a picture for the possible images
		for i in range(len(self.possible_names)):
			self.canvas.create_text(0, y,
				text = self.possible_names[i])
			y = height + 5
			
			im = ImageTk.PhotoImage(possibleIms[i])
			label = Tkinter.Label(image = im)
			label.image = im
			
			self.canvas.create_image(0, y,
				image = label.image,
				anchor = "nw")
			y = y + 100
			
		#Updates the canvas
		self.canvas.resizescrollregion()
コード例 #38
0
def Run():
	print 'running the inserter'

	[width, height] = Template.getTemplateData()

	for sprite in custom_utils.get_working_sprites():
		sprite.image = finalImage = Scaling.scale(sprite.image, width, height)
		sprite.image = finalImage = Bitify.bitify(sprite.image)
		SaveToPlayerFile.saveSprite(sprite)
		custom_utils.save_working_sprite(sprite)
	
	print 'save to player file'

	SaveToPlayerFile.savePlayerFile()
コード例 #39
0
class TemplatePerformanceTest(unittest.TestCase):
    def setUp(self):
        self.template = Template('''Returns one or more subgroups of the match. 
            If there is a single argument, the result is a single string; 
            if there are multiple arguments, the result is a tuple with one item per argument. 
            Without arguments, group1 defaults to zero (the whole match is returned).
            ${onezzzzzzzzzzz}, ${twozzzzzzzzzzz}, ${threezzzzzzzzz}, ${fourzzzzzzzzzz}, ${fivezzzzzzzzzz}''')
        self.template.set('onezzzzzzzzzzz', '1')
        self.template.set('twozzzzzzzzzzz', '2')
        self.template.set('threezzzzzzzzz', '3')
        self.template.set('fourzzzzzzzzzz', '4')
        self.template.set('fivezzzzzzzzzz', '5')

    def testTemplateWith100WordsAnd5Variables(self):
        self.template.evaluate()
        expectedTimeGap = 0.2
        actualTimeGap = time.clock()
        self.assertLess(actualTimeGap, 0.2)
コード例 #40
0
ファイル: TestTemplate.py プロジェクト: iambus/PyLoad
	def assertSubst(self, source, target):
		self.assertEqual(Template.subst(source, self.variables), target)
コード例 #41
0
ファイル: TestTemplate.py プロジェクト: iambus/PyLoad
	def assertBad(self, source):
		self.assertRaises((ValueError, KeyError), lambda:Template.subst(source, self.variables))
コード例 #42
0
import os
import Image

import custom_utils
import Template


# make duplicate of player file
playerFile = Image.open('reference_images/player.png')

templateData = Template.getTemplateData()

blockWidth = templateData[0]
blockHeight = templateData[1]

grid_map = {
	'standing1' : (0,0),
	'standing2' : (1,0),
	'standing_footup' : (2,0),
	'standing_eyesup' : (3,0),
	'standing_eyesup2' : (4,0),

	'crouch' : (0, 1),
	'low_crouch' : (1,1),
	'jump1' : (2,1),
	'jump2' : (3,1),
	'jump3' : (4,1),

	'falling1' : (0,2),
	'falling2' : (1,2),
	'shoot_up' : (2,2),
コード例 #43
0
class TemplateTest(unittest.TestCase):
    def setUp(self):
        self.template = Template('${one}, ${two}, ${three}')
        self.template.set('one', '1')
        self.template.set('two', '2')
        self.template.set('three', '3')

    def tearDown(self):
        pass

    def testMultipleVariables(self):
        self.assertTemplateEvaluatesTo("1, 2, 3")

    def testUnknownVariableAreIgnored(self):
        self.template.set('doesnotexitst', 'Hi')
        self.assertTemplateEvaluatesTo("1, 2, 3")

    def testVariableGetProcessedJustOnce(self):
        self.template.set('one', '${one}')
        self.template.set('two', '${three}')
        self.template.set('three', '${two}')
        self.assertTemplateEvaluatesTo("${one}, ${three}, ${two}")

    def testMissingValueRaisesException(self):
        with self.assertRaises(MissingValueException) as cm:
            Template('${foo}').evaluate()
        self.assertEqual('No value for ${foo}', cm.exception.message)


    def assertTemplateEvaluatesTo(self, expected):
        self.assertEqual(expected, self.template.evaluate())        
コード例 #44
0
ファイル: pyCompilerWin.py プロジェクト: ennima/omas
class pyCompilerWin():

	def __init__(self):
		self.templater = Template()
		self.template_setup = "C:\\Users\\enrique.nieto\\Documents\\develops\\omas\\build_system\\py_setup.py"
		self.build_path = "C:\\Users\\enrique.nieto\\Documents\\develops\\Node\\ticker\\dist\\"
		self.build_script = "open_server.py"
		self.build_script_lib ="lib"
		
		self.dependences_path = self.build_path + "depend\\"
		self.build_dist = self.build_script.split(".")[0]+"_dist"

	def copy_to_dist(self):
		print("Copy files of "+self.build_script+" to",self.build_path+self.build_dist)
		with open(self.build_path+self.build_script) as script:
			line_count = 0
			in_lib = False
			for line in script:
				print(line_count,line)
				line_count += 1
				if(("sys.path.append('"+self.build_script_lib+"')") in line):
					print("##### Dentro de lib")
					in_lib = True
				elif("#end "+self.build_script_lib+" imports" in line):
					print("##### Fuera de lib ")
					in_lib = False
					break
				elif(in_lib):
					if(line.startswith("from")):
						print("class lib")
						lineSplit = line.split(" ")
						src = self.build_path+self.build_script_lib+"\\"+lineSplit[1]+".py"
						dest = self.build_path+self.build_dist+"\\"+lineSplit[1]+".py"
						dest_path = self.build_path+self.build_dist
						print(src,"to",dest)
						if(os.path.exists(dest_path)):
							copyfile(src,dest)
						else:
							print("Making dest: ", dest_path)
							os.mkdir(dest_path)
							copyfile(src,dest)
					elif(line.startswith("import")):
						print("is ordinary lib")

		src = self.build_path + self.build_script
		dest = self.build_path + self.build_dist + "\\"+ self.build_script
		copyfile(src,dest)

	def make_setup(self,build_path):

		self.templater.vars_change=[{"var":"program_py","val":self.build_script}]
		os.chdir(build_path)
		if(self.templater.load(self.template_setup)):
			print("Cargado")
			self.templater.change()
			self.templater.save(build_path+"setup.py")

			
			print(os.getcwd())
			os.system("python setup.py py2exe")
			
		else:
			print("Error al cargar el template: ",os.getcwd()," -> ",self.template_setup)

	def load_config(self,config_file):
		with open(config_file,"r") as load_data:
			json_conf = json.load(load_data)

			print(json_conf["dependences_path"])

			self.template_setup = json_conf["template_setup"]
			self.build_path = json_conf["build_path"]
			self.build_script = json_conf["build_script"]
			self.build_script_lib = json_conf["build_script_lib"]

			self.dependences_path = self.build_path + json_conf["dependences_path"] + "\\"
コード例 #45
0
ファイル: sql_injection.py プロジェクト: Wizmann/Utils
+----+------+----------+
| id | user | password |
+----+------+----------+
|  1 | user | password |
+----+------+----------+
1 row in set (0.00 sec)
'''


if __name__ == '__main__':
    conn = MySQLdb.connect(host='localhost',
                           port=3306,
                           user='******',
                           passwd='123456',
                           db='buggy_db')

    cursor = conn.cursor()

    form = cgi.FieldStorage()
    user = form['user'].value
    password = form['password'].value

    cursor.execute(
        "SELECT * FROM `user_table` WHERE `user`='%s' and `password`='%s'" % (user, password))
    record = cursor.fetchone()

    if record:
        print Template.load('login_success.html')
    else:
        print Template.load('login_failed.html')
コード例 #46
0
ファイル: AutoOn.py プロジェクト: Dragor2/HueControl
 def index(self):
     template = mako.template.Template(filename='plugins/AutoOn/AutoOn.tmpl')
     rendered_template = template.render(config=self.config, groups=HueBridge.groups)
     return Template.render_template(rendered_template)
コード例 #47
0
ファイル: symbol_filter.py プロジェクト: Wizmann/Utils
#!/usr/bin/env python
# coding=utf-8
import sys
import re
import os
import MySQLdb
import cgi
import Template  # My own template module

if __name__ == '__main__':
    form = cgi.FieldStorage()
    symbols = form['symbols'].value
    symbols = MySQLdb.escape_string(symbols)
    print Template.load("symbol_filter.html",{'safe-symbol': symbols})
コード例 #48
0
ファイル: TemplateTest.py プロジェクト: ennima/omas
	def test_it_should_be_able_when_template_is_loaded(self):
		templater = Template()
		self.assertTrue(templater.load(filesPath+"src\\templater.txt"))
コード例 #49
0
ファイル: TemplateTest.py プロジェクト: ennima/omas
	def test_it_should_be_able_when_template_is_not_loaded(self):
		templater = Template()
		self.assertFalse(templater.load("templater.txt"))
コード例 #50
0
ファイル: TestTemplate.py プロジェクト: iambus/PyLoad
	def testUnicode(self):
		self.assertEqual(Template.escape('x'), u'x')
		self.assertEqual(Template.escape(u'x'), 'x')
		self.assertEqual(Template.escape(u'x'), u'x')

		self.assertEqual(Template.escape('$x'), u'$$x')
		self.assertEqual(Template.escape(u'$x'), '$$x')
		self.assertEqual(Template.escape(u'$x'), u'$$x')

		variables = {'x':u'1', u'y':'2', u'z':u'3'}
		self.assertEqual(Template.subst('$x', variables), '1')
		self.assertEqual(Template.subst('$y', variables), '2')
		self.assertEqual(Template.subst('$z', variables), '3')

		self.assertEqual(Template.subst(u'$x', variables), '1')
		self.assertEqual(Template.subst(u'$y', variables), '2')
		self.assertEqual(Template.subst(u'$z', variables), '3')

		self.assertEqual(Template.subst('$x', variables), u'1')
		self.assertEqual(Template.subst('$y', variables), u'2')
		self.assertEqual(Template.subst('$z', variables), u'3')

		self.assertEqual(Template.subst(u'$x', variables), u'1')
		self.assertEqual(Template.subst(u'$y', variables), u'2')
		self.assertEqual(Template.subst(u'$z', variables), u'3')
コード例 #51
0
ファイル: TestTemplate.py プロジェクト: iambus/PyLoad
	def testEscape(self):
		self.assertEqual(Template.escape('x'), 'x')
		self.assertEqual(Template.escape('$x'), '$$x')
		self.assertEqual(Template.escape('$$x'), '$$$$x')
		self.assertEqual(Template.escape('${x}'), '$${x}')
コード例 #52
0
 def setUp(self):
     self.template = Template('${one}, ${two}, ${three}')
     self.template.set('one', '1')
     self.template.set('two', '2')
     self.template.set('three', '3')
コード例 #53
0
ファイル: TemplateTest.py プロジェクト: ennima/omas
	def test_it_should_be_able_when_template_is_modified(self):
		templater = Template()
		if(templater.load(filesPath+"templater.txt")):
			self.assertTrue(templater.change())
コード例 #54
0
ファイル: TemplateTest.py プロジェクト: ennima/omas
	def test_it_make_new_file_var_changed(self):
		templater = Template()
		templater.load(filesPath+"src\\templater.txt")
		templater.change()
		self.assertTrue(templater.save(filesPath+"render\\templateado.txt"))