text:
import keyring
import os
import yaml
import json
import re
import config
import shutil
import tempfile
import string
import random
import base64
import zipfile
import time
import datetime
import threading
import sys
import re
import xmltodict
import codecs
import traceback
import plistlib
import platform
import itertools
from mm_exceptions import MMException
from jinja2 import Environment, FileSystemLoader
import jinja2.ext
import jinja2htmlcompress
from jinja2htmlcompress import HTMLCompress

TOOLING_API_EXTENSIONS = ['cls', 'trigger', 'page', 'component']

SFDC_API_VERSION = "27.0" #is overridden upon instantiation of mm_connection if plugin specifies mm_api_version

PRODUCTION_ENDPOINT = "https://www.salesforce.com/services/Soap/u/"+SFDC_API_VERSION
SANDBOX_ENDPOINT    = "https://test.salesforce.com/services/Soap/u/"+SFDC_API_VERSION
PRERELEASE_ENDPOINT = "https://prerellogin.pre.salesforce.com/services/Soap/u/"+SFDC_API_VERSION

PRODUCTION_ENDPOINT_SHORT = "https://www.salesforce.com"
SANDBOX_ENDPOINT_SHORT    = "https://test.salesforce.com"
PRERELEASE_ENDPOINT_SHORT = "https://prerellogin.pre.salesforce.com"

WSDL_PATH = config.base_path + "/lib/wsdl" #this can be overridden by client settings or request parameter

ENDPOINTS = {
    "production" : PRODUCTION_ENDPOINT,
    "developer"  : PRODUCTION_ENDPOINT,
    "sandbox"    : SANDBOX_ENDPOINT,
    "prerelease" : PRERELEASE_ENDPOINT
}

URL_TO_ENDPOINT_TYPE = {
    PRODUCTION_ENDPOINT : "production",
    SANDBOX_ENDPOINT    : "sandbox",
    PRERELEASE_ENDPOINT : "prerelease"
}

template_path = config.base_path + "/lib/templates"

env = Environment(loader=FileSystemLoader(template_path),trim_blocks=True)

def get_timestamp():
    ts = time.time()
    return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d-%H:%M:%S')

def parse_json_from_file(location):
    if not os.path.exists(location):
        return {}
    try:
        json_data = open(location)
        if json_data:
            data = json.load(json_data)
            json_data.close()
            return data
    except:
        return parse_json(location)

def parse_xml_from_file(location):
    if not os.path.exists(location):
        return {}
    try:
        xml_data = open(location)
        data = xmltodict.parse(xml_data,postprocessor=xmltodict_postprocessor)
        xml_data.close()
        return data
    except:
        return {}

def get_sfdc_endpoint(url):
    endpoint = PRODUCTION_ENDPOINT
    if "test" in url:
        endpoint = SANDBOX_ENDPOINT
    elif "prerellogin.pre.salesforce.com" in url:
        endpoint = PRERELEASE_ENDPOINT
    return endpoint

def get_endpoint_type_by_url(endpoint):
    if endpoint in URL_TO_ENDPOINT_TYPE:
        return URL_TO_ENDPOINT_TYPE[endpoint]
    else:
        return ""

def get_sfdc_endpoint_by_type(type):
    if type in ENDPOINTS:
        return ENDPOINTS[type]
    else:
        return ""

def put_project_directory_on_disk(project_name, **kwargs):
    if 'force' in kwargs and kwargs['force'] == True:
        if os.path.isdir(config.connection.workspace+"/"+project_name):
            shutil.rmtree(config.connection.workspace+"/"+project_name)
    os.makedirs(config.connection.workspace+"/"+project_name)

def put_password(project_name, password):
    keyring.set_password('MavensMate: '+project_name+'-mm', project_name+'-mm', password)

def get_password_by_project_name(project_name):
    #TODO: transition to ID-based processing
    pw = keyring.get_password('MavensMate: '+project_name+'-mm', project_name+'-mm')
    if pw == None:
        pw = keyring.get_password('MavensMate: '+project_name, project_name+'-mm')
    return pw

def put_password_by_key(key, password):
    keyring.set_password('MavensMate: '+key, key, password)

def get_password_by_key(key):
    return keyring.get_password('MavensMate: '+key, key)

def delete_password_by_key(key):
    try:
        return keyring.delete_password('MavensMate: '+key, key)
    except:
        #TODO: this has not been implemented in keyring yet :-(
        pass

def get_file_extension(path):
    return os.path.splitext(path)[1]

def get_file_as_string(file_path):
    try:
        f = codecs.open(file_path, "r", "utf8")
        file_body = f.read()
        f.close()
        return file_body
    except Exception, e:
        print "Couldn't open "+str(file_path)+" because: "+e.message
    return ""

def parse_rest_response(body):
    rjson = json.loads(body)
    return rjson

def zip_directory(directory_to_zip, where_to_put_zip_file=tempfile.gettempdir(), base64_encode=True):
    shutil.make_archive(where_to_put_zip_file+'/mm', 'zip', directory_to_zip+"/")
    if base64_encode == True:
        file_contents = open(where_to_put_zip_file+"/mm.zip", "r").read()
        base64_zip = base64.b64encode(file_contents)
        return base64_zip

def extract_base64_encoded_zip(encoded, where_to_extract):
    zip_path = os.path.join(where_to_extract,"metadata.zip")
    #write file to disk
    data = base64.b64decode(encoded)
    src = open(zip_path, "w")
    src.write(data)
    src.close()
    #extract file from disk - z.extractall(where_to_extract) fails with non ascii chars
    f = zipfile.ZipFile(zip_path, 'r')
    for fileinfo in f.infolist():
        path = where_to_extract
        directories = fileinfo.filename.decode('utf8').split('/')
        for directory in directories:
            path = os.path.join(path, directory)
            if directory == directories[-1]: break # the file
            if not os.path.exists(path):
                os.makedirs(path)
        outputfile = open(path, "wb")
        shutil.copyfileobj(f.open(fileinfo.filename), outputfile)
    #remove zip file
    os.remove(where_to_extract+"/metadata.zip")

def rename_directory(old_directory_name, new_directory_name):
    os.rename(old_directory_name, new_directory_name)

def xmltodict_postprocessor(path, key, value):
    try:
        if value == 'true':
            return key, True
        elif value == 'false':
            return key, False
        else:
            return key, value
    except (ValueError, TypeError):
        return key, value
        # >>> xmltodict.parse('12x',
        # ...                 postprocessor=postprocessor)
        # OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))])

def parse_json(filename):
    """ Parse a JSON file
        First remove comments and then use the json module package
        Comments look like :
            // ...
        or
            /*
            ...
            */
    """
    # Regular expression for comments
    comment_re = re.compile(
        '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
        re.DOTALL | re.MULTILINE
    )

    with open(filename) as f:
        content = ''.join(f.readlines())

        ## Looking for comments
        match = comment_re.search(content)
        while match:
            # single line comment
            content = content[:match.start()] + content[match.end():]
            match = comment_re.search(content)

        # Return json file
        return json.loads(content)

def put_tmp_directory_on_disk(put_unpackaged_directory=False):
    tmp_dir = tempfile.gettempdir()
    mm_tmp_directory = "{0}/.org.mavens.mavensmate.{1}".format(tmp_dir, get_random_string())
    os.makedirs(mm_tmp_directory)
    if put_unpackaged_directory == True:
        os.makedirs(mm_tmp_directory+"/unpackaged")
        return mm_tmp_directory, mm_tmp_directory+"/unpackaged"
    return mm_tmp_directory

def put_package_xml_in_directory(directory, file_contents, isDelete=False):
    file_name = 'package.xml' if isDelete == False else 'destructiveChanges.xml'
    f = open("{0}/{1}".format(directory, file_name), 'w')
    f.write(file_contents)
    f.close()

def put_empty_package_xml_in_directory(directory, file_contents):
    file_name = 'package.xml'
    f = open("{0}/{1}".format(directory, file_name), 'w')
    f.write(file_contents)
    f.close()

def get_random_string(size=8, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))

def new_mavensmate_id(size=32, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for x in range(size))

def delete_directory(directory):
    if os.path.isdir(directory):
        shutil.rmtree(directory)

#returns package.xml contents based on dict of metadata
def get_package_xml_contents(metadata_hash={}):
    #metadata_hash = {'ApexClass':['foo', 'bar'], 'ApexPage':'*'}
    #metadata_hash = {'ApexClass':'*'}
    template = env.get_template('package.html')
    return template.render(sfdc_api_version=SFDC_API_VERSION, hash=metadata_hash)

def get_empty_package_xml_contents():
    template = env.get_template('empty_package.html')
    return template.render(sfdc_api_version=SFDC_API_VERSION)

def get_default_metadata_data():
    return parse_json_from_file(config.base_path + "/lib/sforce/metadata/default_metadata.json")

def get_child_metadata_data():
    return parse_json_from_file(config.base_path + "/lib/sforce/metadata/default_child_metadata.json")

def get_meta_type_by_suffix(suffix):
    if '-meta' in suffix:
        suffix = suffix.split('-meta')[0]
    data = get_default_metadata_data()
    for item in data["metadataObjects"]:
        if 'suffix' in item and item['suffix'] == suffix:
            return item

def get_meta_type_by_dir(dir_name):
    data = get_default_metadata_data()
    for item in data["metadataObjects"]:
        if 'directoryName' in item and item['directoryName'] == dir_name:
            return item

def get_meta_type_by_name(name):
    data = get_default_metadata_data()
    child_data = get_child_metadata_data()
    for item in data["metadataObjects"]:
        if 'xmlName' in item and item['xmlName'] == name:
            return item
    for item in child_data:
        if 'xmlName' in item and item['xmlName'] == name:
            return item

def put_skeleton_files_on_disk(metadata_type, api_name, where, apex_class_type='default', apex_trigger_object_api_name=''):
    template_map = config.connection.get_plugin_client_setting('mm_default_apex_templates_map', {})
    custom_templates = config.connection.get_plugin_client_setting('mm_apex_templates_map', {})
    #merge custom and default template maps
    for apextype in template_map:
        if apextype in custom_templates:
            template_map[apextype] = dict(template_map[apextype], **custom_templates[apextype])
    #get the template name
    template_name = ''
    try:
        template_name = template_map[metadata_type][apex_class_type]
    except:
        template_name = template_map[metadata_type]['default']
    try:
        custom_template_path = config.connection.get_plugin_client_setting('mm_apex_templates_dir', config.connection.get_plugin_settings_path("User", "templates"))
        if os.path.exists(os.path.join(custom_template_path, template_name)):
            custom_env = Environment(loader=FileSystemLoader(custom_template_path),trim_blocks=True)
            #try to load custom
            template = custom_env.get_template(template_name)
        else:
            raise Exception("Template does not exist")
    except:
        #load default template
        template = env.get_template(template_name)
    file_body = template.render(api_name=api_name,object_name=apex_trigger_object_api_name)
    metadata_type = get_meta_type_by_name(metadata_type)
    os.makedirs("{0}/{1}".format(where, metadata_type['directoryName']))
    f = open("{0}/{1}/{2}".format(where, metadata_type['directoryName'], api_name+"."+metadata_type['suffix']), 'w')
    f.write(file_body)
    f.close()

    template = env.get_template('meta.html')
    file_body = template.render(api_name=api_name, sfdc_api_version=SFDC_API_VERSION,meta_type=metadata_type['xmlName'])
    f = open("{0}/{1}/{2}".format(where, metadata_type['directoryName'], api_name+"."+metadata_type['suffix'])+"-meta.xml", 'w')
    f.write(file_body)
    f.close()

def parse_manifest(location):
    return parse_json_from_file(location)

def generate_ui(operation,params={}):
    template_path = config.base_path + "/lib/ui/templates"
    env = Environment(loader=FileSystemLoader(template_path),trim_blocks=True)
    env.globals['play_sounds'] = play_sounds
    temp = tempfile.NamedTemporaryFile(delete=False, prefix="mm")
    if operation == 'new_project':
        template = env.get_template('/project/new.html')
        file_body = template.render(user_action='new',base_path=config.base_path,workspace=config.connection.workspace,client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'checkout_project':
        template = env.get_template('/project/new.html')
        file_body = template.render(user_action='checkout',base_path=config.base_path,workspace=config.connection.workspace,client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'upgrade_project':
        template = env.get_template('/project/upgrade.html')
        file_body = template.render(
            base_path=config.base_path,
            name=config.connection.project.project_name,
            project_location=config.connection.project.location,
            client=config.connection.plugin_client
        ).encode('UTF-8')
    elif operation == 'edit_project':
        tree_body = ''
        # if config.connection.project.is_metadata_indexed == True:
        #     template = env.get_template('/project/tree.html')
        #     org_metadata = config.connection.project.get_org_metadata()
        #     tree_body = template.render(metadata=org_metadata)
        template = env.get_template('/project/edit.html')
        creds = config.connection.project.get_creds()
        file_body = template.render(
            base_path=config.base_path,
            name=config.connection.project.project_name,
            username=creds['username'],
            password=creds['password'],
            org_type=creds['org_type'],
            # has_indexed_metadata=config.connection.project.is_metadata_indexed,
            project_location=config.connection.project.location,
            # tree_body=tree_body,
            client=config.connection.plugin_client
        ).encode('UTF-8')
    elif operation == 'unit_test':
        template = env.get_template('/unit_test/index.html')
        istest = re.compile(r"@istest", re.I)
        testmethod = re.compile(r"testmethod", re.I)

        apex_classes = []
        for dirname, dirnames, filenames in os.walk(config.connection.project.location+"/src/classes"):
            for f in filenames:
                if f == "." or f == ".." or '-meta.xml' in f or ".svn" in f:
                    continue
                try:
                    full_file_path = dirname+"/"+f
                    if istest.search(open(full_file_path).read()) or testmethod.search(open(full_file_path).read()):
                        apex_classes.append(f.split(".")[0])
                except:
                    continue
        if "selected" in params:
            selected = params["selected"]
        else:
            selected = []
        file_body = template.render(
            base_path=config.base_path,
            name=config.connection.project.project_name,
            classes=apex_classes,
            selected=selected,
            client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'deploy':
        tree_body = ''
        if config.connection.project.is_metadata_indexed == True:
            template = env.get_template('/project/tree.html')
            selected = params['selected'] if 'selected' in params else None
            org_metadata = config.connection.project.get_org_metadata(selected)
            tree_body = template.render(metadata=org_metadata,operation=operation)
        template = env.get_template('/deploy/index.html')
        file_body = template.render(
            base_path=config.base_path,
            name=config.connection.project.project_name,
            has_indexed_metadata=config.connection.project.is_metadata_indexed,
            project_location=config.connection.project.location,
            connections=config.connection.project.get_org_connections(False),
            tree_body=tree_body,
            operation=operation,
            client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'execute_apex':
        template = env.get_template('/execute_apex/index.html')
        file_body = template.render(
            base_path=config.base_path,
            name=config.connection.project.project_name,
            project_location=config.connection.project.location,
            client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'new_project_from_existing_directory':
        project_name = os.path.basename(params['directory'])
        template = env.get_template('/project/new_from_existing.html')
        file_body = template.render(
            base_path=config.base_path,
            project_name=project_name,
            directory=params['directory'],
            client=config.connection.plugin_client).encode('UTF-8')
    elif operation == 'debug_log':
        template = env.get_template('/debug_log/index.html')
        file_body = template.render(
            base_path=config.base_path,
            project_name=config.connection.project.project_name,
            users=config.connection.project.get_org_users_list(),
            logs=config.connection.project.get_org_logs(),
            client=config.connection.plugin_client).encode('UTF-8')
    temp.write(file_body)
    temp.close()
    return temp.name

def generate_html_response(operation, obj, params):
    template_path = config.base_path + "/lib/ui/templates"
    env = Environment(loader=FileSystemLoader(template_path),trim_blocks=True,extensions=['jinja2.ext.loopcontrols', jinja2htmlcompress.HTMLCompress])
    env.globals['get_file_lines'] = get_file_lines
    env.globals['htmlize'] = htmlize
    env.globals['does_file_exist'] = does_file_exist
    if operation == 'unit_test' or operation == 'test':
        template = env.get_template('/unit_test/result.html')
        config.logger.debug(json.dumps(obj, sort_keys=True,indent=4))
        result = process_unit_test_result(obj)
        config.logger.debug('\n\n\n\n\n')
        config.logger.debug(json.dumps(result, sort_keys=True,indent=4))
        html = template.render(result=result,results_normal={},args=params)
    elif operation == 'deploy':
        template = env.get_template('/deploy/result.html')
        deploy_results = []
        for result in obj:
            if 'messages' in result:
                for m in result['messages']:
                    if m['success'] == False:
                        result['success'] = False
                        break
            if 'runTestResult' in result and 'codeCoverage' in result['runTestResult']:
                result['parsedTestResults'] = process_unit_test_result(result['runTestResult'])
                deploy_results.append(result)
            else:
                deploy_results.append(result)
        config.logger.debug(obj)
        config.logger.debug(deploy_results)
        html = template.render(deploy_results=deploy_results,args=params)
    elif operation == 'index_metadata':
        template = env.get_template('/project/tree.html')
        org_metadata = config.connection.project.get_org_metadata()
        html = template.render(metadata=org_metadata)
    return html

def play_sounds():
    return config.connection.get_plugin_client_setting('mm_play_sounds', False)

def does_file_exist(api_name, metadata_type_name):
    metadata_type = get_meta_type_by_name(metadata_type_name)
    if os.path.isfile(config.connection.project.location+"/src/"+metadata_type['directoryName']+"/"+api_name+"."+metadata_type['suffix']):
        return True
    else:
        return False

def get_file_lines(api_name, metadata_type_name):
    try:
        metadata_type = get_meta_type_by_name(metadata_type_name)
        if os.path.isfile(config.connection.project.location+"/src/"+metadata_type['directoryName']+"/"+api_name+"."+metadata_type['suffix']):
            return open(config.connection.project.location+"/src/"+metadata_type['directoryName']+"/"+api_name+"."+metadata_type['suffix']).readlines()
        else:
            return []
    except:
        return []

def htmlize(seed):
    try:
        seed = seed.decode('utf8')
        seed = re.sub("&", "&", seed)
        seed = re.sub('"', """, seed)
        seed = re.sub("<", "<", seed)
        seed = re.sub(">", ">", seed)
        seed = re.sub("\t", "    ", seed)
        seed = re.sub(" ", " ", seed)
        seed = re.sub("\n", "
", seed)
        return seed
    except:
        return 'Not Available'

def launch_ui(tmp_html_file_location):
    os.system("open -n '"+config.base_path+"/bin/MavensMateWindowServer.app' --args -url '"+tmp_html_file_location+"'")
    threading.Thread(target=remove_tmp_html_file, args=(tmp_html_file_location,)).start()

def remove_tmp_html_file(tmp_html_file_location):
    time.sleep(1)
    os.remove(tmp_html_file_location)

def generate_response(obj):
    return json.dumps(obj)

def generate_success_response(message, type="text"):
    res = {
        "time"   : repr(time.clock() - config.mm_start),
        "success"   : True,
        "body_type" : type,
        "body"      : message
    }
    return json.dumps(res)

def generate_error_response(message):
    # hide path info from build
    try:
        trace = re.sub( r'\"/(.*?\.pyz/)', r'', traceback.format_exc()).strip()
        message = message.strip()
        if trace != None and trace != 'None' and 'raise MMException' not in trace:
            # if message = e.message just use the trace
            if len(trace):
                if trace.endswith(message):
                    message = ''
                message += '\n' + '[STACKTRACE]: ' + trace
            message += '\n'+'[ENVIRONMENT]: '
            # get OS info
            try:
                if sys.platform == 'darwin':
                    release, versioninfo, machine = platform.mac_ver()
                    message += 'MacOS ' + release
                #todo: support windows and linux
            except:
                pass
            # try to get the executable version
            try:
                dic = plistlib.readPlist('/Applications/MavensMate.app/Contents/Info.plist')
                if 'CFBundleVersion' in dic:
                    message += ', MavensMate ' + dic['CFBundleVersion']
            except:
                pass

        config.logger.exception("[MAVENSMATE CAUGHT ERROR]")
        res = {
            "success"   : False,
            "body_type" : "text",
            "body"      : message
        }
        return json.dumps(res)
    except:
        res = {
            "success"   : False,
            "body_type" : "text",
            "body"      : message
        }
        return json.dumps(res)

def get_request_payload():
    try:
        if sys.stdin.isatty():
            return {}
        return json.loads(sys.stdin.read())
    except ValueError, e:
        #sys.exit(1)
        return {}

def lower_keys(x):
    if isinstance(x, list):
        return [lower_keys(v) for v in x]
    if isinstance(x, dict):
        return dict((k.lower(), lower_keys(v)) for k, v in x.iteritems())
    return x

#prepares the unit test result for processing by the jinja template
def process_unit_test_result(result):

    config.logger.debug('>>>> RUN TEST RESULT')
    config.logger.debug(result)

    triggers = []
    classes = []

    if 'codeCoverage' in result:
        # for single results we don't get a list back
        if type(result['codeCoverage']) is not list:
            result['codeCoverage'] = [result['codeCoverage']]
        for coverage_result in result['codeCoverage']:
            if 'locationsNotCovered' in coverage_result and type(coverage_result['locationsNotCovered']) is not list:
                coverage_result['locationsNotCovered'] = [coverage_result['locationsNotCovered']]
            if 'numLocations' in coverage_result and 'numLocationsNotCovered' in coverage_result:
                locations = int(float(coverage_result['numLocations']))
                locations_not_covered = int(float(coverage_result['numLocationsNotCovered']))
                percent_covered = 0
                if locations > 0:
                    percent_covered = int(round(100 * ((float(locations) - float(locations_not_covered)) / locations)))
                coverage_result['percentCovered'] = percent_covered
                if percent_covered < 40:
                    coverage_result['coverageLevel'] = 'danger'
                elif percent_covered >= 40 and percent_covered < 75:
                    coverage_result['coverageLevel'] = 'warning'
                elif percent_covered >= 75:
                    coverage_result['coverageLevel'] = 'success'
                else:
                    coverage_result['coverageLevel'] = 'info'

            if 'type' in coverage_result:
                if coverage_result['type'] == 'Trigger':
                    triggers.append(coverage_result)
                else:
                    classes.append(coverage_result)
            elif 'id' in coverage_result:
                result_id = coverage_result['id']
                if result_id.startswith('01q'):
                    triggers.append(coverage_result)
                else:
                    classes.append(coverage_result)

    if 'codeCoverageWarnings' in result:
        # for single results we don't get a list back
        if type(result['codeCoverageWarnings']) is not list:
            result['codeCoverageWarnings'] = [result['codeCoverageWarnings']]
        for warning in result['codeCoverageWarnings']:
            if 'name' in warning and type(warning['name']) is not str and type(warning['name']) is not unicode:
               warning['name'] = None

    results_normal = {}
    #{"foo"=>[{:name = "foobar"}{:name = "something else"}], "bar"=>[]}
    pass_fail = {}
    if 'successes' in result:
        # for single results we don't get a list back
        if type(result['successes']) is not list:
            result['successes'] = [result['successes']]
        for success in result['successes']:
            if success['name'] not in pass_fail:
                pass_fail[success['name']] = {
                    'fail': 0,
                    'pass': 1
                }
            else:
                pass_fail[success['name']]['pass'] += 1
            if success['name'] not in results_normal: #key isn't there yet, put it in
                results_normal[success['name']] = [success]
            else: #key is there, let's add metadata to it
                arr = results_normal[success['name']] #get the existing array
                arr.append(success) #add the new piece of metadata
                results_normal[success['name']] = arr #replace the key

    if 'failures' in result:
        # for single results we don't get a list back
        if type(result['failures']) is not list:
            result['failures'] = [result['failures']]
        for failure in result['failures']:
            if failure['name'] not in pass_fail:
                pass_fail[failure['name']] = {
                    'fail': 1,
                    'pass': 0
                }
            else:
                pass_fail[failure['name']]['fail'] += 1
            if failure['name'] not in results_normal: #key isn't there yet, put it in
                results_normal[failure['name']] = [failure]
            else: #key is there, let's add metadata to it
                arr = results_normal[failure['name']] #get the existing array
                arr.append(failure) #add the new piece of metadata
                results_normal[failure['name']] = arr #replace the key

    result['pass_fail'] = pass_fail

    result['results_normal'] = results_normal

    result['codeCoverage'] = {
        "triggers" : triggers,
        "classes" : classes
    }
    return result

def get_file_extension_no_period(path):
    name, ext = os.path.splitext(path)
    return ext.replace(".", "")

def get_file_name_no_extension(path):
    name, ext = os.path.splitext(path)
    return name.split("/")[-1]

#returns metadata hash of selected files  #=> {"ApexClass" => ["aclass", "anotherclass"], "ApexTrigger" => ["atrigger", "anothertrigger"]}
def get_metadata_hash(selected_files=[]):
    meta_hash = {}
    for f in selected_files:
        if '-meta.xml' in f:
            continue
        name, ext = os.path.splitext(f)
        base_name_no_ext = os.path.basename(f).split(".")[0]
        ext_no_period = ext.replace(".", "")
        metadata_definition = get_meta_type_by_suffix(ext_no_period)
        meta_type = metadata_definition["xmlName"]

        if meta_type not in meta_hash: #key isn't there yet, put it in
            if metadata_definition['inFolder']:
                arr = f.split("/")
                if arr[len(arr)-2] != metadata_definition['directoryName']:
                    meta_hash[meta_type] = [arr[len(arr)-2]+"/"+base_name_no_ext] #file name with no extension
                else:
                    meta_hash[meta_type] = [base_name_no_ext]
            else:
                meta_hash[meta_type] = [base_name_no_ext]
        else: #key is there, let's add metadata to it
            meta_array = meta_hash[meta_type] #get the existing array
            if metadata_definition['inFolder']:
                arr = f.split("/")
                if arr[len(arr)-2] != metadata_definition['directoryName']:
                    meta_array.append(arr[len(arr)-2]+"/"+base_name_no_ext) #file name with no extension
                else:
                    meta_array.append(base_name_no_ext) #add the new piece of metadata
            else:
                meta_array.append(base_name_no_ext) #file name with no extension

            meta_hash[meta_type] = meta_array #replace the key

    return meta_hash

def parse_deploy_result(res):
    return_result = {
        "id"        : res["id"],
        "success"   : res["success"]
    }
    messages        = parse_deploy_messages(res)
    retrieve_result = {}
    run_test_result = {}

    if 'runTestResult' in res and type(res['runTestResult']) is not list:
        return_result['runTestResult'] = [res['runTestResult']]
    else:
        return_result['runTestResult'] = res['runTestResult']
    return return_result

def parse_deploy_messages(res):
    messages = []
    return_messages = []
    if 'messages' in res and type(res['messages']) is not list:
        messages = [res['messages']]
    else:
        messages = res['messages']
    for m in messages:
        return_messages.append({
            "changed"       : m["changed"],
            "columnNumber"  : m["columnNumber"],
            "created"       : m["created"],
            "deleted"       : m["deleted"],
            "fileName"      : m["fileName"],
            "fullName"      : m["fullName"],
            "id"            : m["id"],
            "lineNumber"    : m["lineNumber"],
            "problem"       : m["problem"],
            "problemType"   : m["problemType"],
            "success"       : m["success"]
        })
    return return_messages

def parse_run_test_result(res):
    return_result = {}
    return_run_tests = {}
    code_coverage = []
    code_coverage_return = []
    code_coverage_warnings = []
    failures = []
    successes = []
    if 'codeCoverage' in res['runTestResult'] and type(res['runTestResult']['codeCoverage']) is not list:
        code_coverage = [res['runTestResult']['codeCoverage']]
    else:
        code_coverage = res['runTestResult']['codeCoverage']
    if 'codeCoverageWarnings' in res['runTestResult'] and type(res['runTestResult']['codeCoverageWarnings']) is not list:
        code_coverage_warnings = [res['runTestResult']['codeCoverageWarnings']]
    else:
        code_coverage_warnings = res['runTestResult']['codeCoverageWarnings']
    if 'failures' in res['runTestResult'] and type(res['runTestResult']['failures']) is not list:
        failures = [res['runTestResult']['failures']]
    else:
        failures = res['runTestResult']['failures']
    if 'successes' in res['runTestResult'] and type(res['runTestResult']['successes']) is not list:
        successes = [res['runTestResult']['successes']]
    else:
        successes = res['runTestResult']['successes']

    for c in code_coverage:
        code_coverage_return.append({
            "changed"       : m["changed"],
            "columnNumber"  : m["columnNumber"],
            "created"       : m["created"],
            "deleted"       : m["deleted"],
            "fileName"      : m["fileName"],
            "fullName"      : m["fullName"],
            "id"            : m["id"],
            "lineNumber"    : m["lineNumber"],
            "problem"       : m["problem"],
            "problemType"   : m["problemType"],
            "success"       : m["success"]
        })
    return_result['codeCoverage'] = code_coverage_return
    return return_result

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

# def get_creds(project_directory):
#     f = open(project_directory + "/config/settings.yaml")
#     settings = yaml.safe_load(f)
#     f.close()
#     project_name    = settings['project_name']
#     username        = settings['username']
#     environment     = settings['environment']
#     password = get_password_by_project_name(project_name)
#     endpoint = get_sfdc_endpoint_by_type(environment)
#     return { "username" : username, "password" : password, "endpoint" : endpoint }

#returns array of selected files #=> ["/users/username/projects/foo/classes/myclass123.cls", /users/username/projects/foo/classes/myclass345.cls"]
# def get_selected_files(active_file=False):
#     if active_file:
#         return Array[ENV['TM_FILEPATH']]
#     else:
#         try:
#             selected_files = ENV["TM_SELECTED_FILES"].split(",")
#             #selected_files = Shellwords.shellwords(ENV["TM_SELECTED_FILES"])
#             for f in selected_files:
#                 if '-meta.xml' in f:
#                     continue
#                 ext = File.extname(f).gsub(".","") #=> cls
#                 mt_hash = get_meta_type_by_suffix(ext)
#                 if mt_hash == None:
#                     selected_files.delete(f) #????
#                     continue
#             if mt_hash[:meta_file]:
#                 if f + "-meta.xml" not in selected_files: #if they didn't select the meta file, select it anyway
#                     selected_files.append(f + "-meta.xml")

#             selected_files.uniq!
#             return selected_files
#     except BaseException, e:
#         return Array[ENV['TM_FILEPATH']]


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.google.cloud.tools.eclipse</groupId>
    <artifactId>plugins</artifactId>
    <version>0.1.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.google.cloud.tools.eclipse.projectselector.test</artifactId>
  <version>0.1.0-SNAPSHOT</version>
  <packaging>eclipse-test-plugin</packaging>

  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-surefire-plugin</artifactId>
        <configuration>
          <useUIHarness>true</useUIHarness>
          <useUIThread>true</useUIThread>
          <product>org.eclipse.platform.ide</product>
          <systemProperties>
            <disablePrivacyTos>true</disablePrivacyTos>
          </systemProperties>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>target-platform-configuration</artifactId>
        <configuration>
          <dependency-resolution>
            <extraRequirements>
              <!-- needed for org.eclipse.equinox.event -->
              <requirement>
                <type>eclipse-feature</type>
                <id>org.eclipse.rcp</id>
                <versionRange>0.0.0</versionRange>
              </requirement>
            </extraRequirements>
          </dependency-resolution>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
target=`getprop ro.board.platform`

#
# Function to start sensors for DSPS enabled platforms
#
start_sensors()
{
    mkdir -p /data/system/sensors
    touch /data/system/sensors/settings
    chmod 775 /data/system/sensors
    chmod 664 /data/system/sensors/settings

    mkdir -p /data/misc/sensors
    chmod 775 /data/misc/sensors

    if [ ! -s /data/system/sensors/settings ]; then
        # If the settings file is empty, enable sensors HAL
        # Otherwise leave the file with it's current contents
        echo 1 > /data/system/sensors/settings
    fi
    start sensors
}

start_battery_monitor()
{
	chown root.system /sys/module/pm8921_bms/parameters/*
	chmod 0660 /sys/module/pm8921_bms/parameters/*
	mkdir -p /data/bms
	chown root.system /data/bms
	chmod 0770 /data/bms
	start battery_monitor
}

#
# set the ro.hw_platform property for identify this board
#
setprop ro.hw_platform "`cat /sys/devices/system/soc/soc0/hw_platform`"

#
# set the ro.hw_version property for identify the verison of this board
#
hw_version=`cat /sys/devices/system/soc/soc0/platform_version`
mmc_type=`cat /sys/class/mmc_host/mmc0/mmc0:0001/name`
hw_version_ma=$(($hw_version/65536))
hw_version_mi=$(($hw_version-hw_version_ma*65536))

# Fix hw_version_mi by mmc_type
# The platform with "XINYH" flash is version 3.1
if [ $hw_version_mi -eq 0 -a $mmc_type == XINYH ];then
hw_version_mi=1
fi

setprop ro.hw_version ${hw_version_ma}.${hw_version_mi}

baseband=`getprop ro.baseband`

#
# Suppress default route installation during RA for IPV6; user space will take
# care of this
#
for file in /proc/sys/net/ipv6/conf/*
do
  echo 0 > $file/accept_ra_defrtr
done

#
# Start gpsone_daemon for SVLTE Type I & II devices
#
case "$target" in
        "msm7630_fusion")
        start gpsone_daemon
esac
case "$baseband" in
        "svlte2a")
        start gpsone_daemon
        start bridgemgrd
esac
case "$target" in
        "msm7630_surf" | "msm8660" | "msm8960")
        start quipc_igsn
esac
case "$target" in
        "msm7630_surf" | "msm8660" | "msm8960")
        start quipc_main
esac

case "$target" in
        "msm8960")
        start location_mq
        start xtwifi_inet
        start xtwifi_client
esac

case "$target" in
    "msm7630_surf" | "msm7630_1x" | "msm7630_fusion")
        value=`cat /sys/devices/system/soc/soc0/hw_platform`
        case "$value" in
            "Fluid")
             start profiler_daemon;;
        esac
        ;;
    "msm8660" )
        platformvalue=`cat /sys/devices/system/soc/soc0/hw_platform`
        case "$platformvalue" in
            "Fluid")
                start_sensors
                start profiler_daemon;;
        esac
        ;;
    "msm8960")
        start_sensors
        case "$baseband" in
            "msm")
		start_battery_monitor;;
        esac

        platformvalue=`cat /sys/devices/system/soc/soc0/hw_platform`
        case "$platformvalue" in
             "Fluid")
                 start profiler_daemon;;
             "Liquid")
                 start profiler_daemon;;
        esac
        ;;

esac


text:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class Global_config {
	private $CI;
	private $tk_config;

	function load_config() {
		$this->CI = &get_instance();
                $this->CI->template->set('global_url',site_url());
                $this->CI->template->set('base_url',base_url());
                $this->CI->template->set('current_url',current_url());
                $this->CI->template->set('home_url',"http://localhost/edbuddy-proj");

		//$this->tk_config = parse_ini_file("./config/EBD.ini");
		//$this->version = parse_ini_file("/etc/php5/fpm/version.ini");
//		if ( (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'com.android.browser' )
//		{
//                        error_log('globalconfig');
//			$this->initilize_config();
//		}
//		else
//		{
//                        error_log('19xxxx');
//
//			//$header = $this->CI->city->getHomepageHeader();
//			//$headerFromCache = $this->CI->cache->get_static('homeheader');
////			$headers = array();
////			foreach($header as $key=>$row){
////				$headers['header_url'] = $row['header_url'];
////				$headers['header_title'] = $row['header_title'];
////				$headers['header_image_path'] = $row['header_image_path'];
////			}
////			if($headers['header_image_path'] != $headerFromCache['header_image_path']){
////				$this->CI->cache->delete('homeheader');
////				$this->CI->cache->set_static('homeheader',$headers);
////			}else {
////				$headers = $this->CI->cache->get_static('homeheader');
////			}
////			$this->CI->template->set('header_image_url',$headers['header_url']);
////			$this->CI->template->set('header_image_title',$headers['header_title']);
////			$this->CI->template->set('header_image_name',$headers['header_image_path']);
//
////			$this->CI->template->set('cdn',$this->tk_config['cdn']);
////			$this->CI->template->set('logo_cdn',$this->tk_config['cdn']);
////			$this->CI->template->set('assets',$this->tk_config['bootassets']);
//			//$this->CI->template->set('dev_cdn',$this->tk_config['dev_cdn']);
//			$this->CI->template->set('global_url',site_url());
//			$this->CI->template->set('base_url',base_url());
//			$this->CI->template->set('current_url',current_url());
//			if($this->tk_config['index_site'] == 'No')
//			{
//				$this->CI->template->set('nofollow','<META NAME="ROBOTS" CONTENT="NOFOLLOW"/><META NAME="ROBOTS" CONTENT="NOARCHIVE" /><meta http-equiv="cache-control" content="max-age=0" /><meta http-equiv="cache-control" content="no-cache" /><meta http-equiv="expires" content="0" /><meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /><meta http-equiv="pragma" content="no-cache" />');
//			}
////			$this->CI->template->set('css_version',$this->CI->cache->get_css('frontend1.0'.$this->version['version'].$this->tk_config['cachekey'].'css'));
////			$this->CI->template->set('js_version',$this->CI->cache->get_js('frontend1.0'.$this->version['version'].$this->tk_config['cachekey'].'javascript'));
////			$this->CI->template->set('version',($this->version['version']) ? $this->version['version'].'/' : '');
////			$userid = 	($this->CI->session->userdata('userID')) ? $this->CI->session->userdata('userID') : $this->CI->input->cookie('tkuserid');
////			$user_key = 'frontend/user.json?user_id='.$userid;
////			if($userid != '') {
////				$apicalls [] = $user_key;
////			}
////			try {
////				$apioutput = $this->CI->apiclient->process($apicalls);
////				$this->CI->template->set('user',$apioutput[$user_key]);
////			}catch(TastyKhanaApiException $e) {
////				unset($apicalls);
////			}
		//}
		/* mobile related */
		$this->CI->load->library('user_agent');
		if ($this->CI->agent->is_mobile()) {
			$this->CI->template->set('mobile',1);
			$ua = $_SERVER['HTTP_USER_AGENT'];
			$checker = array(
					'iphone'=>preg_match('/iPhone|iPod|iPad/', $ua),
					'blackberry'=>preg_match('/BlackBerry/', $ua),
					'android'=>preg_match('/Android/', $ua),
			);
			if($checker['blackberry']) {
				$this->CI->template->set('device','BB');
			}
		}
		if ($this->CI->agent->browser() == 'Internet Explorer') {
			$this->CI->template->set('IE',$this->CI->agent->version());
		}else {
			$this->CI->template->set('IE',40);
		}
	}

	function initilize_config() {
//		$this->CI->template->set('base_url',base_url());
//// 		global $city_config_cityname;
//// 		global $city_config_cityid;
		$this->CI->load->library('session');
		$this->CI->load->helper('cookie');
//  		$this->CI->template->set('cityid',$_COOKIE['tkuserdefaultcityid']);
//  		$this->CI->template->set('cityname',$_COOKIE['tkuserdefaultcity']);
// 		$this->CI->template->set('d_cityname',$_COOKIE['tkuserdefaultcity']);
// 		$this->CI->session->set_userdata('cityid',$city_config_cityid);
// 		$this->CI->session->set_userdata('cityname',$city_config_cityname);
// 		setcookie("tkuserdefaultcityid", $city_config_cityid, time()+60*60*24*30, "/", parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain'], 0);
// 		setcookie("tkuserdefaultcity", $city_config_cityname, time()+60*60*24*30, "/", parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain'], 0);
//		$userid = ($this->CI->session->userdata('userID')) ? $this->CI->session->userdata('userID') : $this->CI->input->cookie('tkuserid');
//		$this->CI->template->set('site_url',site_url().$_COOKIE['tkuserdefaultcity'].'/');
//		$this->CI->load->library('kaptcha');
//		$this->CI->template->set('captcha',$this->CI->kaptcha->display_kaptcha());
//		$this->CI->template->set('email',$this->CI->session->userdata('email'));
//		$this->CI->template->set('mobile',$this->CI->session->userdata('mobile'));
//		$this->CI->template->set('address',$this->CI->session->userdata('address'));
//		$this->CI->template->set('username',ucfirst($this->CI->session->userdata('username')));
//		$this->CI->template->set('userid',$userid);
//		$this->CI->template->set('cart_session',$this->CI->session->userdata('cartsession'));
//		$user_area = ($this->CI->session->userdata('areaid')) ? $this->CI->session->userdata('areaid') : $this->CI->input->cookie('tkuserlocation'.$this->CI->session->userdata('cityname'));
//		$this->CI->template->set('user_area',$user_area);
//		$this->CI->template->set('cookie_location',$this->CI->input->cookie('tksearchloc'.lcfirst($this->CI->session->userdata('cityname'))));
//		$this->CI->template->set('cookie_areaid',$this->CI->input->cookie('tksearchlocid'.lcfirst($this->CI->session->userdata('cityname'))));
//
//		$this->CI->load->model('general/city_model','city');
//		$header = $this->CI->city->getHomepageHeader();
//		$headerFromCache = $this->CI->cache->get_static('homeheader');
//		$headers = array();
//		foreach($header as $key=>$row){
//			$headers['header_url'] = $row['header_url'];
//			$headers['header_title'] = $row['header_title'];
//			$headers['header_image_path'] = $row['header_image_path'];
//		}
//		if($headers['header_image_path'] != $headerFromCache['header_image_path']){
//			$this->CI->cache->delete('homeheader');
//			$this->CI->cache->set_static('homeheader',$headers);
//		}else {
//			$headers = $this->CI->cache->get_static('homeheader');
//		}
//
//		$this->CI->template->set('header_image_url',$headers['header_url']);
//		$this->CI->template->set('header_image_title',$headers['header_title']);
//		$this->CI->template->set('header_image_name',$headers['header_image_path']);
//
//		$notification = $this->CI->city->getSiteNotification();
//
//		$this->CI->template->set('login_form',form_open(site_url().'/users/auth/login',array('id'=>'login_form','name'=>'login_form')));
//		$this->CI->template->set('forgotpwd_form',form_open(site_url().'/users/auth/forgot_password',array('id'=>'global_search_form','name'=>'global_search_form')));
//		$this->CI->template->set('signup_form',form_open(site_url().'/users/member/register',array('id'=>'signup_form','name'=>'signup_form')));
//		$this->CI->template->set('new_user_address',form_open(site_url().'/users/profile/address_add',array('id'=>'new_user_address','name'=>'new_user_address')));
//		$this->CI->template->set('new_user_contact',form_open(site_url().'/users/profile/contact_add',array('id'=>'new_user_contact','name'=>'new_user_contact')));
//		$this->CI->template->set('forgot_form',form_open(site_url().'/users/member/new_password',array('id'=>'new_user_password','name'=>'new_user_password')));
//		$this->CI->template->set('username_form',form_open(site_url().'/users/auth/forgot_username',array('id'=>'get_user_name','name'=>'get_user_name')));
//		$this->CI->template->set('activate_form',form_open(site_url().'/users/auth/partial_activation',array('id'=>'new_user_activate','name'=>'new_user_activate')));
//		$this->CI->template->set('search_from_open',form_open(site_url().'',array('id'=>'global_search_form','name'=>'global_search_form')));
//		$this->CI->template->set('payment_form',form_open(site_url().'/orders/delivery/checkout',array('id'=>'payment_form','name'=>'payment_form')));
//		$this->CI->template->set('contact_form',form_open(site_url().'/site/contact',array('id'=>'contact_form','name'=>'contact_form')));
//		$this->CI->template->set('trackorder_form',form_open(site_url().'/notifications/check_status',array('id'=>'trackorder_form','name'=>'trackorder_form')));
//		if($this->tk_config['index_site'] == 'No')
//		{
//			$this->CI->template->set('nofollow','<META NAME="ROBOTS" CONTENT="NOFOLLOW"/><META NAME="ROBOTS" CONTENT="NOARCHIVE" /><meta http-equiv="cache-control" content="max-age=0" /><meta http-equiv="cache-control" content="no-cache" /><meta http-equiv="expires" content="0" /><meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /><meta http-equiv="pragma" content="no-cache" />');
//		}
//		$this->CI->template->set('live_tracking',parse_ini_file("/etc/php5/fpm/tastykhana.ini")['tracking']);
//		$this->CI->template->set('pixel_tracking',parse_ini_file("/etc/php5/fpm/tastykhana.ini")['pixel_tracking']);
//		$this->CI->template->set('remarketing',parse_ini_file("/etc/php5/fpm/tastykhana.ini")['remarketing']);
//		$this->CI->template->set('domain',parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain']);
//
//		$this->CI->template->set('cdn',$this->tk_config['cdn']);
//		$this->CI->template->set('logo_cdn',$this->tk_config['cdn']);
//		$this->CI->template->set('assets',$this->tk_config['bootassets']);
//		$this->CI->template->set('dev_cdn',$this->tk_config['dev_cdn']);
//		$this->CI->template->set('images',base_url());
//		$this->CI->template->set('message',$notification[0]['message']);
//		$url = ($this->CI->uri->uri_string() != '') ? $this->CI->uri->uri_string() : '/';
//		$this->CI->template->set('ga_uri',$url);
//
//		$this->CI->load->config('city_config');
//		$suggestions = $this->CI->config->item($_COOKIE['tkuserdefaultcity'].'_location');
//		$signup_campaign = $this->CI->config->item($_COOKIE['tkuserdefaultcityid'].'_coupon_signup');
//		$new_years = $this->CI->config->item(date('Y-m-d').'_'.$_COOKIE['tkuserdefaultcityid']);
//		if($new_years) {
//			$this->CI->template->set('block_online_payments',$new_years['online_payments']);
//			$this->CI->template->set('billing_message',$new_years['menu']);
//			$this->CI->template->set('block_coupons',$new_years['coupons']);
//			$this->CI->template->set('service_guarantee',$new_years['service_guarantee']);
//		}else{
//			$this->CI->template->set('block_online_payments',0);
//			$this->CI->template->set('billing_message',0);
//			$this->CI->template->set('block_coupons',0);
//			$this->CI->template->set('service_guarantee',1);
//		}
//
//		$this->CI->template->set('total_restaurants',$this->CI->config->item("total_restaurants"));
//		$this->CI->template->set('total_orders',$this->CI->config->item("total_orders"));
//		$this->CI->template->set('city_names',$this->CI->config->item("city_names"));
//
//		$this->CI->template->set('coupon_signup',$signup_campaign['active']);
//		$key = array_rand($suggestions);
//		$suggestloc = $suggestions[$key];
//		unset($suggestions);
//		unset($key);
//
//		//switch to actually include takeaway funnel in website.
//		$funnels = $this->CI->config->item($_COOKIE['tkuserdefaultcity'].'_funnels');
//		if( $funnels['takeaway'] === 1) {
//			$funnel = $this->CI->session->userdata('funnel');
//			if($funnel == '') {
//				$this->CI->session->set_userdata('funnel','delivery');
//				$this->CI->template->set('funnel',$funnel);
//			}else {
//				$this->CI->template->set('funnel',$funnel);
//			}
//			$this->CI->template->set('funnels',1);
//		}else {
//			$this->CI->session->set_userdata('funnel','delivery');
//			$this->CI->template->set('funnel','delivery');
//			$this->CI->template->set('funnels',0);
//		}
//
//		$apicalls = array();
//		$apicalls [] = 'city.json';
//		if($_COOKIE['tkuserdefaultcityid'] != null)
//		{
//			$apicalls [] = 'city/'.$_COOKIE['tkuserdefaultcityid'].'.json';
//// 			$apicalls [] = 'city/subzones/'.$_COOKIE['tkuserdefaultcityid'].'.json';
//		}
//		$userid = 	($this->CI->session->userdata('userID')) ? $this->CI->session->userdata('userID') : $this->CI->input->cookie('tkuserid');
//		$user_key = 'frontend/user.json?user_id='.$userid;
//		if($userid != '') {
//			$apicalls [] = $user_key;
//		}
//
//		try {
//			$apioutput = $this->CI->apiclient->process($apicalls);
//			$this->CI->template->set('user',$apioutput[$user_key]);
//			if($userid != '')
//			{
//				setcookie("esiusername", $apioutput[$user_key]['name'], time()+60*60*24, "/", parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain'], 0);
//				setcookie("esicity", lcfirst($apioutput[$user_key]['cityname']), time()+60*60*24, "/", parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain'], 0);
//				setcookie("esiuserid", $apioutput[$user_key]['id'], time()+60*60*24, "/", parse_ini_file("/etc/php5/fpm/tastykhana.ini")['domain'], 0);
//			}
//		}catch(TastyKhanaApiException $e) {
//			unset($apicalls);
//		}
//		if ($this->ssl_check()) {
//			$this->CI->template->set('ssl_global_url',str_replace('http://','https://',site_url()));
//			$this->CI->template->set('ssl_base_url',str_replace('http://','https://',base_url()));
//			$this->CI->template->set('cdn',$this->tk_config['cdn']);
//// 			$this->CI->template->set('logo_cdn','//6e259384626c6028694a-66203a3933afab3500f59dc1d1670c4e.r6.cf1.rackcdn.com/');
//			$this->CI->template->set('logo_cdn',$this->tk_config['cdn']);
//// 			$this->CI->template->set('home_images','//f6517b85b5d63540b708-d91caf00f4db2d160ad8801b5862e8dc.ssl.cf1.rackcdn.com/');
//		}else {
//			$this->CI->template->set('ssl_global_url',site_url());
//			$this->CI->template->set('ssl_base_url',base_url());
//		}
//

//		$this->CI->template->set('global_url',site_url());
//		$this->CI->template->set('base_url',base_url());
//		$this->CI->template->set('current_url',current_url());
//		$helpline = $apioutput['city/'.$_COOKIE['tkuserdefaultcityid'].'.json'];
//		$this->CI->session->set_userdata('stdcode',$helpline[0]['stdcode']);
//		$this->CI->session->set_userdata('helpline',$helpline[0]['helpline']);
//		$this->CI->template->set('suggest_loc',$suggestloc);
//		$this->CI->template->set('city',$apioutput['city.json']);
//		$this->CI->template->set('cityarea',$apioutput['city/subzones/'.$_COOKIE['tkuserdefaultcityid'].'.json']);
//		$this->CI->template->set('helpline',$helpline[0]['helpline']);
//		$this->CI->template->set('city_latitude',$helpline[0]['latitude']);
//		$this->CI->template->set('city_longitude',$helpline[0]['longitude']);
//		$this->CI->template->set('stdcode',$helpline[0]['stdcode']);
//		$this->CI->template->set('css_version',$this->CI->cache->get_css('frontend1.0'.$this->version['version'].$this->tk_config['cachekey'].'css'));
//		$this->CI->template->set('js_version',$this->CI->cache->get_js('frontend1.0'.$this->version['version'].$this->tk_config['cachekey'].'javascript'));
//		$this->CI->template->set('version',($this->version['version']) ? $this->version['version'].'/' : '');
//		$this->CI->template->set('places_api',$this->tk_config['places_api']);
//		//$this->CI->template->set('ga_tracking',1,true);//SDA 12 June 2014 for dev ga testing
//
	}
//
//	function ssl_check() {
//		$isSecure = false;
//		if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
//			$isSecure = true;
//		}
//		elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
//			$isSecure = true;
//		}
//		return $isSecure;
//	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright (c) 2016-2017, Adam <Adam@sigterm.info>
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>net.runelite</groupId>
		<artifactId>runelite-parent</artifactId>
		<version>1.4.11-SNAPSHOT</version>
	</parent>

	<groupId>net.runelite.rs</groupId>
	<artifactId>runescape-api</artifactId>
	<name>RuneScape API</name>

	<dependencies>
		<dependency>
			<groupId>net.runelite</groupId>
			<artifactId>runelite-api</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>
</project>


text:
class CreateBambooUserUserDetails < ActiveRecord::Migration
  def change
    create_table :bamboo_user_user_details do |t|
      t.integer :user_id
      #---Add other required attributes [START]----
      #like
      #t.string :first_name
      #t.string :last_name
      #---Add other required attributes [END]----
      t.timestamps
    end
  end
end


text:
package ca.uhnresearch.pughlab.tracker.resource;

import org.restlet.Request;

import com.fasterxml.jackson.databind.node.ObjectNode;

import ca.uhnresearch.pughlab.tracker.dao.CasePager;
import ca.uhnresearch.pughlab.tracker.dao.StudyCaseQuery;
import ca.uhnresearch.pughlab.tracker.dto.Attributes;
import ca.uhnresearch.pughlab.tracker.dto.Cases;
import ca.uhnresearch.pughlab.tracker.dto.Role;
import ca.uhnresearch.pughlab.tracker.dto.Study;
import ca.uhnresearch.pughlab.tracker.dto.StudyAboutResponse;
import ca.uhnresearch.pughlab.tracker.dto.User;
import ca.uhnresearch.pughlab.tracker.dto.View;

public class RequestAttributes {

	private static final String STUDY_ATTRIBUTE = "study";

	private static final String VIEW_ATTRIBUTE = "view";

	private static final String ROLE_ATTRIBUTE = "role";

	private static final String QUERY_ATTRIBUTE = "query";

	private static final String PAGER_ATTRIBUTE = "pager";

	private static final String ENTITY_ATTRIBUTE = "entity";

	private static final String ATTRIBUTE_ATTRIBUTE = "attribute";

	private static final String FILTER_ATTRIBUTE = "filter";

	private static final String ABOUT_ATTRIBUTE = "about";

	private static final String USER_ATTRIBUTE = "user";

	/**
	 * Helper method to read a study from a request attribute
	 * @param request
	 * @return the request study
	 */
	public static Study getRequestStudy(Request request) {
		return (Study) request.getAttributes().get(RequestAttributes.STUDY_ATTRIBUTE);
	}

	/**
	 * Helper method to write a study into a request attribute
	 * @param request
	 * @param s
	 */
	public static void setRequestStudy(Request request, Study s) {
		request.getAttributes().put(RequestAttributes.STUDY_ATTRIBUTE, s);
	}

	/**
	 * Helper method to read a view from a request attribute
	 * @param request
	 * @return the request view
	 */
	public static View getRequestView(Request request) {
		return (View) request.getAttributes().get(RequestAttributes.VIEW_ATTRIBUTE);
	}

	/**
	 * Helper method to write a view into a request attribute
	 * @param request
	 * @param v
	 */
	public static void setRequestView(Request request, View v) {
		request.getAttributes().put(RequestAttributes.VIEW_ATTRIBUTE, v);
	}

	/**
	 * Helper method to read a role from a request attribute
	 * @param request
	 * @return the request role
	 */
	public static Role getRequestRole(Request request) {
		return (Role) request.getAttributes().get(RequestAttributes.ROLE_ATTRIBUTE);
	}

	/**
	 * Helper method to write a role into a request attribute
	 * @param request
	 * @param r
	 */
	public static void setRequestRole(Request request, Role r) {
		request.getAttributes().put(RequestAttributes.ROLE_ATTRIBUTE, r);
	}

	/**
	 * Helper method to read a query from a request attribute
	 * @param request
	 * @return the request query
	 */
	public static StudyCaseQuery getRequestCaseQuery(Request request) {
		return (StudyCaseQuery) request.getAttributes().get(RequestAttributes.QUERY_ATTRIBUTE);
	}

	/**
	 * Helper method to write a query into a request attribute
	 * @param request
	 * @param q
	 */
	public static void setRequestCaseQuery(Request request, StudyCaseQuery q) {
		request.getAttributes().put(RequestAttributes.QUERY_ATTRIBUTE, q);
	}

	/**
	 * Helper method to read a pager from a request attribute
	 * @param request
	 * @return the request pager
	 */
	public static CasePager getRequestCasePager(Request request) {
		return (CasePager) request.getAttributes().get(RequestAttributes.PAGER_ATTRIBUTE);
	}

	/**
	 * Helper method to write a pager into a request attribute
	 * @param request
	 * @param q
	 */
	public static void setRequestCasePager(Request request, CasePager q) {
		request.getAttributes().put(RequestAttributes.PAGER_ATTRIBUTE, q);
	}

	/**
	 * Helper method to read an entity from a request attribute
	 * @param request
	 * @return the request case
	 */
	public static Cases getRequestEntity(Request request) {
		return (Cases) request.getAttributes().get(RequestAttributes.ENTITY_ATTRIBUTE);
	}

	/**
	 * Helper method to write an entity into a request attribute
	 * @param request
	 * @param c
	 */
	public static void setRequestEntity(Request request, Cases c) {
		request.getAttributes().put(RequestAttributes.ENTITY_ATTRIBUTE, c);
	}

	/**
	 * Helper method to read an attribute from a request attribute
	 * @param request
	 * @return the request attribute
	 */
	public static Attributes getRequestAttribute(Request request) {
		return (Attributes) request.getAttributes().get(RequestAttributes.ATTRIBUTE_ATTRIBUTE);
	}

	/**
	 * Helper method to write an attribute into a request attribute
	 * @param request
	 * @param a
	 */
	public static void setRequestAttribute(Request request, Attributes a) {
		request.getAttributes().put(RequestAttributes.ATTRIBUTE_ATTRIBUTE, a);
	}

	/**
	 * Helper method to read an attribute from a request attribute
	 * @param request
	 * @return the request filter
	 */
	public static ObjectNode getRequestFilter(Request request) {
		return (ObjectNode) request.getAttributes().get(RequestAttributes.FILTER_ATTRIBUTE);
	}

	/**
	 * Helper method to write an attribute into a request attribute
	 * @param request
	 * @param a
	 */
	public static void setRequestFilter(Request request, ObjectNode a) {
		request.getAttributes().put(RequestAttributes.FILTER_ATTRIBUTE, a);
	}

	/**
	 * Helper method to read an attribute from a request attribute
	 * @param request
	 * @return the request filter
	 */
	public static StudyAboutResponse getRequestStudyAbout(Request request) {
		return (StudyAboutResponse) request.getAttributes().get(RequestAttributes.ABOUT_ATTRIBUTE);
	}

	/**
	 * Helper method to write an attribute into a request attribute
	 * @param request
	 * @param a
	 */
	public static void setRequestStudyAbout(Request request, StudyAboutResponse a) {
		request.getAttributes().put(RequestAttributes.ABOUT_ATTRIBUTE, a);
	}

	/**
	 * Helper method to read a user from a request attribute
	 * @param request
	 * @return the request filter
	 */
	public static User getRequestUser(Request request) {
		return (User) request.getAttributes().get(RequestAttributes.USER_ATTRIBUTE);
	}

	/**
	 * Helper method to write a user into a request attribute
	 * @param request
	 * @param a
	 */
	public static void setRequestUser(Request request, User a) {
		request.getAttributes().put(RequestAttributes.USER_ATTRIBUTE, a);
	}
}


text:
package demoapp.dom.types.primitive.ints.holder;

import org.apache.causeway.applib.annotation.Action;
import org.apache.causeway.applib.annotation.SemanticsOf;

import lombok.RequiredArgsConstructor;

/* This file was GENERATED by the showcase generator (tooling). Do NOT edit! */
//tag::class[]
@Action(semantics = SemanticsOf.SAFE)
@RequiredArgsConstructor
public class PrimitiveIntHolder_actionReturning {

    private final PrimitiveIntHolder holder;

    public int act() {
        return holder.getReadOnlyProperty();
    }

}
//end::class[]


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.cra.MatriculaActivity"
    tools:ignore="MergeRootFrame" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="23dp"
        android:text="@string/titulo_matricula"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/matricula"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_toRightOf="@+id/textView1"
        android:ems="10"
        android:hint="@string/hint_matricula"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="56dp"
        android:text="@string/label_matricula"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/entrar_matricula"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/label_bt_matricula"
        android:width="200dp" />

</RelativeLayout>