<commit_before>import os
import io
import shutil

def strSplit(str):
    result = []
    ind1 = str.find('"')
    ind2 = str.find('"', ind1+1)
    result.append(str[ind1+1:ind2])
    ind3 = str.find('"', ind2+1)
    indLast = str.rfind('"')
    result.append(str[ind3+1:indLast])
    return result
def sortByAlphabet(inputStr):
    return inputStr.lower()

app_names = ['documenteditor', 'presentationeditor', 'spreadsheeteditor']
app_types = ['embed', 'main', 'mobile']
prefix_apps = '../apps/'
prefix_src = 'src/'
prefix_dest = 'dest/'
str_apps = []
langs = []
for i in range(len(app_names)):
    for j in range (len(app_types)):
        locale_path = prefix_apps + app_names[i] + '/' + app_types[j] + '/locale/'
        src_path = prefix_src + app_names[i] + '/' + app_types[j] + '/locale/'
        dest_path = prefix_dest + app_names[i] + '/' + app_types[j] + '/locale/'
        print(locale_path)
        if os.path.isdir(locale_path):
            langs = os.listdir(locale_path)
            if not os.path.isdir(dest_path):
                os.makedirs(dest_path)
            if len(langs)>0:
                try:
                    f = io.open(locale_path + 'en.json', mode='r', encoding='utf-8')
                except Exception:
                    continue
                lines = f.readlines()
                f.close()
                str_apps = []
                for k in range(1, len(lines)-1):
                    arr = strSplit(lines[k])
                    if len(arr) > 0:
                        str_apps.append(arr[0])
                str_apps.sort(key=sortByAlphabet)
                for l in range(len(langs)):
                    lang = langs[l].split('.')[0]
                    f = io.open(locale_path + lang+ '.json', mode='r', encoding='utf-8')
                    lines = f.readlines()
                    f.close()
                    try:
                        f = io.open(src_path + lang+ '.json', mode='r', encoding='utf-8')
                    except Exception:
                        f.close()
                        f = io.open(dest_path + lang + '.json', mode='w', encoding='utf-8')
                        f.writelines(lines)
                        f.close()
                        print('    ' + lang+ '.json - copied')
                        continue
                    d_locale = dict()
                    d_src = dict()
                    # locale
                    for k in range(1, len(lines)-1):
                        arr = strSplit(lines[k])
                        if len(arr) > 1:
                            d_locale[arr[0]] = arr[1]
                    # src
                    lines = f.readlines()
                    for k in range(1, len(lines)-1):
                        arr = strSplit(lines[k])
                        if len(arr) > 1:
                            d_src[arr[0]] = arr[1]
                    f.close()
                    f = io.open(dest_path + lang + '.json', mode='w', encoding='utf-8')
                    f.write(u'{')
                    f.write(u'\n')
                    changed = 'not changed'
                    isFirst = True
                    arr_len = len(str_apps)
                    for k in range(arr_len):
                        str = str_apps[k]
                        if str.find('del_')==0:
                            continue
                        if str in d_src:
                            changed = 'changed'
                            str = '  "' + str + '": "' + d_src[str] + '"'
                            if isFirst:
                                isFirst = False
                            else:
                                f.write(u',\n')
                            f.write(str)
                        elif str in d_locale:
                            str = '  "' + str + '": "' + d_locale[str] + '"'
                            if isFirst:
                                isFirst = False
                            else:
                                f.write(u',\n')
                            f.write(str)
                    f.write(u'\n')
                    f.write(u'}')
                    f.close()
                    print('    ' + lang + '.json - ' + changed)
            if os.path.isdir(src_path):
                add_langs = os.listdir(src_path)
                for l in range(len(langs)):
                    if add_langs.count(langs[l])>0:
			add_langs.remove(langs[l])
                for l in range(len(add_langs)):
                    lang = add_langs[l]
                    shutil.copyfile(src_path + lang, dest_path + lang)
                    print('    ' + lang + ' - ' + 'added')<commit_msg>Fix translation script (not used for mobile)<commit_after>import os
import io
import shutil

def strSplit(str):
    result = []
    ind1 = str.find('"')
    ind2 = str.find('"', ind1+1)
    result.append(str[ind1+1:ind2])
    ind3 = str.find('"', ind2+1)
    indLast = str.rfind('"')
    result.append(str[ind3+1:indLast])
    return result
def sortByAlphabet(inputStr):
    return inputStr.lower()

app_names = ['documenteditor', 'presentationeditor', 'spreadsheeteditor']
#app_types = ['embed', 'main', 'mobile']
app_types = ['embed', 'main']
prefix_apps = '../apps/'
prefix_src = 'src/'
prefix_dest = 'dest/'
str_apps = []
langs = []
for i in range(len(app_names)):
    for j in range (len(app_types)):
        locale_path = prefix_apps + app_names[i] + '/' + app_types[j] + '/locale/'
        src_path = prefix_src + app_names[i] + '/' + app_types[j] + '/locale/'
        dest_path = prefix_dest + app_names[i] + '/' + app_types[j] + '/locale/'
        print(locale_path)
        if os.path.isdir(locale_path):
            langs = os.listdir(locale_path)
            if not os.path.isdir(dest_path):
                os.makedirs(dest_path)
            if len(langs)>0:
                try:
                    f = io.open(locale_path + 'en.json', mode='r', encoding='utf-8')
                except Exception:
                    continue
                lines = f.readlines()
                f.close()
                str_apps = []
                for k in range(1, len(lines)-1):
                    arr = strSplit(lines[k])
                    if len(arr) > 0:
                        str_apps.append(arr[0])
                str_apps.sort(key=sortByAlphabet)
                for l in range(len(langs)):
                    lang = langs[l].split('.')[0]
                    f = io.open(locale_path + lang+ '.json', mode='r', encoding='utf-8')
                    lines = f.readlines()
                    f.close()
                    try:
                        f = io.open(src_path + lang+ '.json', mode='r', encoding='utf-8')
                    except Exception:
                        f.close()
                        f = io.open(dest_path + lang + '.json', mode='w', encoding='utf-8')
                        f.writelines(lines)
                        f.close()
                        print('    ' + lang+ '.json - copied')
                        continue
                    d_locale = dict()
                    d_src = dict()
                    # locale
                    for k in range(1, len(lines)-1):
                        arr = strSplit(lines[k])
                        if len(arr) > 1:
                            d_locale[arr[0]] = arr[1]
                    # src
                    lines = f.readlines()
                    for k in range(1, len(lines)-1):
                        arr = strSplit(lines[k])
                        if len(arr) > 1:
                            d_src[arr[0]] = arr[1]
                    f.close()
                    f = io.open(dest_path + lang + '.json', mode='w', encoding='utf-8')
                    f.write(u'{')
                    f.write(u'\n')
                    changed = 'not changed'
                    isFirst = True
                    arr_len = len(str_apps)
                    for k in range(arr_len):
                        str = str_apps[k]
                        if str.find('del_')==0:
                            continue
                        if str in d_src:
                            changed = 'changed'
                            str = '  "' + str + '": "' + d_src[str] + '"'
                            if isFirst:
                                isFirst = False
                            else:
                                f.write(u',\n')
                            f.write(str)
                        elif str in d_locale:
                            str = '  "' + str + '": "' + d_locale[str] + '"'
                            if isFirst:
                                isFirst = False
                            else:
                                f.write(u',\n')
                            f.write(str)
                    f.write(u'\n')
                    f.write(u'}')
                    f.close()
                    print('    ' + lang + '.json - ' + changed)
            if os.path.isdir(src_path):
                add_langs = os.listdir(src_path)
                for l in range(len(langs)):
                    if add_langs.count(langs[l])>0:
			add_langs.remove(langs[l])
                for l in range(len(add_langs)):
                    lang = add_langs[l]
                    shutil.copyfile(src_path + lang, dest_path + lang)
                    print('    ' + lang + ' - ' + 'added')<|endoftext|>


<commit_before>#!/bin/env python

"""
Apache 404 handler for mogrifying images.
"""

import os
import sys
from settings import DEBUG
from utils import process_url, Http404
from transmogrify import Transmogrify
from hashcompat import sha_constructor
from contextlib import contextmanager
import time

@contextmanager
def lock_file(lock):
    open(lock, "w")

    try:
        yield
    finally:
        # Remove lockfile
        os.remove(lock)

def handle_request():
    server = os.environ["SERVER_NAME"].split(":")[0]
    path = os.environ["REQUEST_URI"]

    # Acquire lockfile
    lock = '/tmp/%s' % sha_constructor(path).hexdigest()
    if os.path.isfile(lock):
        doRedirect(path)
        return

    with lock_file(lock):
        if DEBUG:
            import cgitb
            cgitb.enable()

        try:
            url_parts = process_url(path, server)
        except Http404, e:
            do404(e.message, DEBUG)
            return

        new_file = Transmogrify(url_parts['original_file'], url_parts['actions'])
        new_file.save()

        doRedirect(path)

def doRedirect(path):
    time.sleep(0.005)
    print "Status: 302 Found"
    print "Location: %s" % path
    print

def do404(why, debug):
    if debug:
        message = "
%s
" % why
    else:
        message = "File not found"
    print "Status: 404"
    print "Content-type: text/html"
    print
    print ERROR_404 % message

ERROR_404 = """
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>404 - Not Found</title>

404 - Not Found
%s

"""

if __name__ == '__main__':
    handle_request()
<commit_msg>apache handler is now in bin<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2009 Google Inc. All Rights Reserved.

"""Simple DNS server comparison benchmarking tool.

Designed to assist system administrators in selection and prioritization.
"""

__author__ = 'tstromberg@google.com (Thomas Stromberg)'

import csv
import datetime
import math
import operator
import optparse
import random
import sys
import charts

def CalculateListAverage(values):
  """Computes the arithmetic mean of a list of numbers."""
  return sum(values) / float(len(values))

def DrawTextBar(value, max_value, note=None, max_width=57):
  """Return a simple ASCII bar graph, making sure it fits within max_width.

  Args:
    value: integer or float representing the value of this bar.
    max_value: integer or float representing the largest bar.
    max_width: How many characters this graph can use (int)

  Returns:
    string
  """

  hash_width = max_value / max_width
  return int(math.ceil(value/hash_width)) * '#'

def WeightedDistribution(elements, count):
  """Simple exponential distribution with a mean of 10%."""
  max = len(elements) - 1
  desired_mean = max * 0.10
  lambd = 1.0 / desired_mean
  picks = []

  while len(picks) < max:
    index = int(random.expovariate(lambd))
    if index < max:
      picks.append(elements[index])
  return picks

class NameBench(object):
  """The main benchmarking class."""

  def __init__(self, test_domains_path, nameservers={}, run_count=2, test_count=30):
    """Constructor.

    Args:
      test_domains_path: Path to the list of domains to use (str)
      nameservers: a list of NameServerData objects
      run_count: How many test-runs to perform on each nameserver (int)
      test_count: How many DNS lookups to test in each test-run (int)
    """
    self.test_count = test_count
    self.run_count = run_count
    self.nameservers = nameservers
    self.results = {}
    self.domains = self.LoadDomainsList(test_domains_path)

  def LoadDomainsList(self, filename):
    """Read filename with a one-per-line list of domain names."""
    return [line.strip() for line in open(filename).readlines()]

  def GenerateTestRecords(self, domains, count):
    """Generate a set of DNS queries to test with.

    Args:
      domains: a list of domains to base the tests on.
      count: How many tests to create:

    Returns:
      list of tuples in the format of (query type, query_name)
    """
    tests = []
    domains = WeightedDistribution(domains, count)
    random.shuffle(domains)

    # Previously, we used a for loop with random.randomint() to create records,
    # but the types of records generated were too inconsistent.
    for domain in domains[0:int(round(count*0.6))]:
      tests.append(('A', 'www.%s.' % domain))

    for domain in domains[len(tests):len(tests)+int(round(count*0.3))]:
      tests.append(('A', '%s.' % domain))

    # Round rather than truncate this one since it is so small.
    for domain in domains[len(tests):len(tests)+int(round(count*0.05))]:
      tests.append(('MX', '%s.' % domain))

    # We should still have 3-5% left to work with. This means 1 per 30.
    for unused_i in range(len(tests), count):
      tests.append(('A', 'namebench_(RANDOM).com.'))
    return tests

  def BenchmarkNameServer(self, nameserver, tests):
    """Record results for a single run on a nameserver.

    Args:
      nameserver: NameServerData object
      tests: a list of tuples in the form of [(record_type, record_name)]

    Returns:
      results: list of tuples, including data for each request made.
    """
    results = []
    for (req_type, record) in tests:
      # test records can include a (RANDOM) in the string for cache busting.
      if '(RANDOM)' in record:
        record = record.replace('(RANDOM)', str(random.random() * 10))
      (response, duration, exc) = nameserver.TimedRequest(req_type, record)
      if response:
        answer_count = len(response.answer)
        if answer_count:
          ttl = response.answer[0].ttl
        else:
          ttl = -1
      else:
        answer_count = -1
        ttl = -1

      results.append((record, req_type, duration, answer_count, ttl))
    return results

  def Run(self):
    """Manage all attempts."""
    global_tests = self.GenerateTestRecords(self.domains, self.test_count)
    for attempt in range(self.run_count):
      sys.stdout.write('\n* Benchmarking %s nameservers with %s records each (%s of %s).' %
            (len(self.nameservers), self.test_count, attempt+1, self.run_count))
      for ns in self.nameservers:
        if ns not in self.results:
          self.results[ns] = []
        sys.stdout.write('.')
        sys.stdout.flush()
        self.results[ns].append(self.BenchmarkNameServer(ns, global_tests))
    sys.stdout.write('\n')
    sys.stdout.flush()

  def ComputeAverages(self):
    """Process all runs for all hosts, yielding an average for each host."""
    for ns in self.results:
      record_count = 0
      failure_count = 0
      run_averages = []

      for test_run in self.results[ns]:
        record_count += len(test_run)
        failure_count += len([x[3] for x in test_run if x[3] == -1])
        duration = sum([x[2] for x in test_run])
        run_averages.append(duration / len(test_run))

      # This appears to be a safe use of averaging averages
      overall_average = CalculateListAverage(run_averages)
      yield (ns, overall_average, run_averages, failure_count)

  def FastestNameServerResult(self):
    """Process all runs for all hosts, yielding an average for each host."""
    return [(x[0], min(x[1])) for x in self.DigestedResults()]

  def BestOverallNameServer(self):
    sorted_averages = sorted(self.ComputeAverages(), key=operator.itemgetter(1))
    return sorted_averages[0][0]

  def NearestNameServers(self, count=2):
    min_responses = sorted(self.FastestNameServerResult(),
                           key=operator.itemgetter(1))
    return [ x[0] for x in min_responses ][0:count]

  def DisplayResults(self):
    """Display all of the results in an ASCII-graph format."""
    print ''
    print 'Overall Mean Request Duration (in milliseconds):'
    print '-'* 78

    sorted_averages = sorted(self.ComputeAverages(), key=operator.itemgetter(1))

    # Figure out the largest result early on, as we use it to scale the graph.
    max_result = sorted_averages[-1][1]
    timeout_seen = False
    for result in sorted_averages:
      (ns, overall_mean, unused_run_means, failure_count) = result
      if failure_count:
        timeout_seen = True
        note = ' (%sT)' % failure_count
      else:
        note = ''

      textbar = DrawTextBar(overall_mean, max_result)
      print '%-15.15s %s %2.0f%s' % (ns.name, textbar, overall_mean, note)
    if timeout_seen:
      print '* (#T) represents the number of timeouts experienced during testing.'
    print ''
    print 'Lowest latency for an individual query (in milliseconds):'
    print '-'* 78
    min_responses = sorted(self.FastestNameServerResult(),
                           key=operator.itemgetter(1))
    slowest_result = min_responses[-1][1]
    for result in min_responses:
      (ns, duration) = result
      textbar = DrawTextBar(duration, slowest_result)
      print '%-15.15s %s %2.2f' % (ns.name, textbar, duration)
    print ''

    print 'Detailed Mean Request Duration Chart URL'
    print '-' * 78
    runs_data = [(x[0].name, x[2]) for x in sorted_averages]
    print charts.PerRunDurationBarGraph(runs_data)
    print ''
    print 'Detailed Request Duration Distribution Chart URL'
    print '-' * 78
    print charts.DistributionLineGraph(self.DigestedResults())

  def DigestedResults(self):
    """Return a tuple of nameserver and all associated durations."""
    duration_data = []
    for ns in self.results:
      durations = []
      for test_run_results in self.results[ns]:
        durations += [x[2] for x in test_run_results]
      duration_data.append((ns, durations))
    return duration_data

  def SaveResultsToCsv(self, filename):
    """Write out a CSV file with detailed results on each request.

    Args:
      filename: full path on where to save results (string)

    Sample output:
    nameserver, test_number, test, type, duration, answer_count, ttl
    """
    csv_file = open(filename, 'w')
    output = csv.writer(csv_file)
    output.writerow(['IP', 'Name', 'Notes', 'Check Duration', 'Test #', 'Record', 'Record Type', 'Duration', 'Answer Count', 'TTL'])
    for ns in self.results:
      for (test_run, test_results) in enumerate(self.results[ns]):
        for result in test_results:
          row = [ns.ip, ns.name, ns.notes, ns.check_duration, test_run]
          row.extend(result)
          output.writerow(row)
    csv_file.close()

<commit_msg>Shorten default text bar size from 57 columns to 54<commit_after>#!/usr/bin/env python
# Copyright 2009 Google Inc. All Rights Reserved.

"""Simple DNS server comparison benchmarking tool.

Designed to assist system administrators in selection and prioritization.
"""

__author__ = 'tstromberg@google.com (Thomas Stromberg)'

import csv
import datetime
import math
import operator
import optparse
import random
import sys
import charts

def CalculateListAverage(values):
  """Computes the arithmetic mean of a list of numbers."""
  return sum(values) / float(len(values))

def DrawTextBar(value, max_value, note=None, max_width=54):
  """Return a simple ASCII bar graph, making sure it fits within max_width.

  Args:
    value: integer or float representing the value of this bar.
    max_value: integer or float representing the largest bar.
    max_width: How many characters this graph can use (int)

  Returns:
    string
  """

  hash_width = max_value / max_width
  return int(math.ceil(value/hash_width)) * '#'

def WeightedDistribution(elements, count):
  """Simple exponential distribution with a mean of 10%."""
  max = len(elements) - 1
  desired_mean = max * 0.10
  lambd = 1.0 / desired_mean
  picks = []

  while len(picks) < max:
    index = int(random.expovariate(lambd))
    if index < max:
      picks.append(elements[index])
  return picks

class NameBench(object):
  """The main benchmarking class."""

  def __init__(self, test_domains_path, nameservers={}, run_count=2, test_count=30):
    """Constructor.

    Args:
      test_domains_path: Path to the list of domains to use (str)
      nameservers: a list of NameServerData objects
      run_count: How many test-runs to perform on each nameserver (int)
      test_count: How many DNS lookups to test in each test-run (int)
    """
    self.test_count = test_count
    self.run_count = run_count
    self.nameservers = nameservers
    self.results = {}
    self.domains = self.LoadDomainsList(test_domains_path)

  def LoadDomainsList(self, filename):
    """Read filename with a one-per-line list of domain names."""
    return [line.strip() for line in open(filename).readlines()]

  def GenerateTestRecords(self, domains, count):
    """Generate a set of DNS queries to test with.

    Args:
      domains: a list of domains to base the tests on.
      count: How many tests to create:

    Returns:
      list of tuples in the format of (query type, query_name)
    """
    tests = []
    domains = WeightedDistribution(domains, count)
    random.shuffle(domains)

    # Previously, we used a for loop with random.randomint() to create records,
    # but the types of records generated were too inconsistent.
    for domain in domains[0:int(round(count*0.6))]:
      tests.append(('A', 'www.%s.' % domain))

    for domain in domains[len(tests):len(tests)+int(round(count*0.3))]:
      tests.append(('A', '%s.' % domain))

    # Round rather than truncate this one since it is so small.
    for domain in domains[len(tests):len(tests)+int(round(count*0.05))]:
      tests.append(('MX', '%s.' % domain))

    # We should still have 3-5% left to work with. This means 1 per 30.
    for unused_i in range(len(tests), count):
      tests.append(('A', 'namebench_(RANDOM).com.'))
    return tests

  def BenchmarkNameServer(self, nameserver, tests):
    """Record results for a single run on a nameserver.

    Args:
      nameserver: NameServerData object
      tests: a list of tuples in the form of [(record_type, record_name)]

    Returns:
      results: list of tuples, including data for each request made.
    """
    results = []
    for (req_type, record) in tests:
      # test records can include a (RANDOM) in the string for cache busting.
      if '(RANDOM)' in record:
        record = record.replace('(RANDOM)', str(random.random() * 10))
      (response, duration, exc) = nameserver.TimedRequest(req_type, record)
      if response:
        answer_count = len(response.answer)
        if answer_count:
          ttl = response.answer[0].ttl
        else:
          ttl = -1
      else:
        answer_count = -1
        ttl = -1

      results.append((record, req_type, duration, answer_count, ttl))
    return results

  def Run(self):
    """Manage all attempts."""
    global_tests = self.GenerateTestRecords(self.domains, self.test_count)
    for attempt in range(self.run_count):
      sys.stdout.write('\n* Benchmarking %s nameservers with %s records each (%s of %s).' %
            (len(self.nameservers), self.test_count, attempt+1, self.run_count))
      for ns in self.nameservers:
        if ns not in self.results:
          self.results[ns] = []
        sys.stdout.write('.')
        sys.stdout.flush()
        self.results[ns].append(self.BenchmarkNameServer(ns, global_tests))
    sys.stdout.write('\n')
    sys.stdout.flush()

  def ComputeAverages(self):
    """Process all runs for all hosts, yielding an average for each host."""
    for ns in self.results:
      record_count = 0
      failure_count = 0
      run_averages = []

      for test_run in self.results[ns]:
        record_count += len(test_run)
        failure_count += len([x[3] for x in test_run if x[3] == -1])
        duration = sum([x[2] for x in test_run])
        run_averages.append(duration / len(test_run))

      # This appears to be a safe use of averaging averages
      overall_average = CalculateListAverage(run_averages)
      yield (ns, overall_average, run_averages, failure_count)

  def FastestNameServerResult(self):
    """Process all runs for all hosts, yielding an average for each host."""
    return [(x[0], min(x[1])) for x in self.DigestedResults()]

  def BestOverallNameServer(self):
    sorted_averages = sorted(self.ComputeAverages(), key=operator.itemgetter(1))
    return sorted_averages[0][0]

  def NearestNameServers(self, count=2):
    min_responses = sorted(self.FastestNameServerResult(),
                           key=operator.itemgetter(1))
    return [ x[0] for x in min_responses ][0:count]

  def DisplayResults(self):
    """Display all of the results in an ASCII-graph format."""
    print ''
    print 'Overall Mean Request Duration (in milliseconds):'
    print '-'* 78

    sorted_averages = sorted(self.ComputeAverages(), key=operator.itemgetter(1))

    # Figure out the largest result early on, as we use it to scale the graph.
    max_result = sorted_averages[-1][1]
    timeout_seen = False
    for result in sorted_averages:
      (ns, overall_mean, unused_run_means, failure_count) = result
      if failure_count:
        timeout_seen = True
        note = ' (%sT)' % failure_count
      else:
        note = ''

      textbar = DrawTextBar(overall_mean, max_result)
      print '%-15.15s %s %2.0f%s' % (ns.name, textbar, overall_mean, note)
    if timeout_seen:
      print '* (#T) represents the number of timeouts experienced during testing.'
    print ''
    print 'Lowest latency for an individual query (in milliseconds):'
    print '-'* 78
    min_responses = sorted(self.FastestNameServerResult(),
                           key=operator.itemgetter(1))
    slowest_result = min_responses[-1][1]
    for result in min_responses:
      (ns, duration) = result
      textbar = DrawTextBar(duration, slowest_result)
      print '%-15.15s %s %2.2f' % (ns.name, textbar, duration)
    print ''

    print 'Detailed Mean Request Duration Chart URL'
    print '-' * 78
    runs_data = [(x[0].name, x[2]) for x in sorted_averages]
    print charts.PerRunDurationBarGraph(runs_data)
    print ''
    print 'Detailed Request Duration Distribution Chart URL'
    print '-' * 78
    print charts.DistributionLineGraph(self.DigestedResults())

  def DigestedResults(self):
    """Return a tuple of nameserver and all associated durations."""
    duration_data = []
    for ns in self.results:
      durations = []
      for test_run_results in self.results[ns]:
        durations += [x[2] for x in test_run_results]
      duration_data.append((ns, durations))
    return duration_data

  def SaveResultsToCsv(self, filename):
    """Write out a CSV file with detailed results on each request.

    Args:
      filename: full path on where to save results (string)

    Sample output:
    nameserver, test_number, test, type, duration, answer_count, ttl
    """
    csv_file = open(filename, 'w')
    output = csv.writer(csv_file)
    output.writerow(['IP', 'Name', 'Notes', 'Check Duration', 'Test #', 'Record', 'Record Type', 'Duration', 'Answer Count', 'TTL'])
    for ns in self.results:
      for (test_run, test_results) in enumerate(self.results[ns]):
        for result in test_results:
          row = [ns.ip, ns.name, ns.notes, ns.check_duration, test_run]
          row.extend(result)
          output.writerow(row)
    csv_file.close()

<|endoftext|>


<commit_before># coding:UTF-8
import libvirt
import os
import re
from xml.dom import minidom
from Base import BaseReadOnly

class DomainInfo(BaseReadOnly):
    """Show VM's information"""

    def __init__(self):
        super().__init__()

    # Bridge interface's name
    def get_bridge(self, iface):
        iface_type = iface.getAttribute("type")

        if iface_type == "network":
            net_XML_info = minidom.parseString(Conn.networkLookupByName(network_info).XMLDesc(0))
            bridge = net_XML_info.getElementsByTagName("bridge")[0].getAttribute("name")
        elif iface_type == "bridge":
            bridge = iface.getElementsByTagName("source")[0].getAttribute("bridge")
        else:
            bridge = None

        return bridge

    # Network name
    def get_network(self, iface):
        iface_type = iface.getAttribute("type")

        if iface_type == "network":
            network = iface.getElementsByTagName("source")[0].getAttribute("network")
        else:
            network = None

        return network

    # Mac address
    def get_mac(self, iface):
        return iface.getElementsByTagName("mac")[0].getAttribute("address")

    # Device(nic) name
    def get_device(self, iface):
        return iface.getElementsByTagName("target")[0].getAttribute("dev")

    # Domain(VM) name
    def get_domain(self, id):
        domain = self.connection.lookupByID(id)
        return domain.name()

    # VM tatus
    def get_state(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[0]

    # VM max memory
    def get_max_memory(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[1]

    # Number of CPU
    def get_CPU_number(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[3]

    # CPU time
    def get_CPU_time(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[2]

    # Domain's XML(settings)
    def get_domain_XML(self, id):
        domain = self.connection.lookupByID(id)
        return minidom.parseString(domain.XMLDesc(0))

    # for debug
    def show_domain_info_all(self):
        for id in self.connection.listDomainsID():
            print ("-"*30)

            print ("ID = {}".format(id))
            print ("Name = {}".format(self.get_domain(id)))
            print ("State = {}".format(self.get_state(id)))
            print ("Max Memory = {}MB".format(self.get_max_memory(id)))
            print ("Number of CPUs = {}".format(self.get_CPU_number(id)))
            print ("CPU time = {}".format(self.get_CPU_time(id)))

            # Read XML file
            domain_XML = self.get_domain_XML(id)

            # Show interface's information
            for iface in domain_XML.getElementsByTagName("interface"):
                self.get_domain_network_info(iface)

            print ("*"*20)
        print ("-"*30)

    # for debug
    def get_domain_network_info(self, iface):
        print ("*"*20)
        print ("Network = {}".format(self.get_network(iface)))
        print ("Bridge = {}".format(self.get_bridge(iface)))
        print ("Mac address = {}".format(self.get_mac(iface)))
        print ("Device = {}".format(self.get_device(iface)))

# for debug
api = DomainInfo()
api.show_domain_info_all()
<commit_msg>change get_domain_network_info<commit_after># coding:UTF-8
import libvirt
import os
import re
from xml.dom import minidom
from Base import BaseReadOnly

class DomainInfo(BaseReadOnly):
    """
    Show VM's information
    """

    def __init__(self):
        super().__init__()

    # Bridge interface's name
    def get_bridge(self, iface):
        iface_type = iface.getAttribute("type")

        if iface_type == "network":
            net_XML_info = minidom.parseString(Conn.networkLookupByName(network_info).XMLDesc(0))
            bridge = net_XML_info.getElementsByTagName("bridge")[0].getAttribute("name")
        elif iface_type == "bridge":
            bridge = iface.getElementsByTagName("source")[0].getAttribute("bridge")
        else:
            bridge = None

        return bridge

    # Network name
    def get_network(self, iface):
        iface_type = iface.getAttribute("type")

        if iface_type == "network":
            network = iface.getElementsByTagName("source")[0].getAttribute("network")
        else:
            network = None

        return network

    # Mac address
    def get_mac(self, iface):
        return iface.getElementsByTagName("mac")[0].getAttribute("address")

    # Device(nic) name
    def get_device(self, iface):
        return iface.getElementsByTagName("target")[0].getAttribute("dev")

    # Domain(VM) name
    def get_domain(self, id):
        domain = self.connection.lookupByID(id)
        return domain.name()

    # VM tatus
    def get_state(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[0]

    # VM max memory
    def get_max_memory(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[1]

    # Number of CPU
    def get_CPU_number(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[3]

    # CPU time
    def get_CPU_time(self, id):
        domain = self.connection.lookupByID(id)
        return domain.info()[2]

    # Domain's XML(settings)
    def get_domain_XML(self, id):
        domain = self.connection.lookupByID(id)
        return minidom.parseString(domain.XMLDesc(0))

    # for debug
    def show_domain_info_all(self):

        for id in self.connection.listDomainsID():

            print ("ID = {}".format(id))
            print ("Name = {}".format(self.get_domain(id)))
            print ("State = {}".format(self.get_state(id)))
            print ("Max Memory = {}MB".format(self.get_max_memory(id)))
            print ("Number of CPUs = {}".format(self.get_CPU_number(id)))
            print ("CPU time = {}".format(self.get_CPU_time(id)))

            # Read XML file
            domain_XML = self.get_domain_XML(id)

            # Show interface's information
            for iface in domain_XML.getElementsByTagName("interface"):
                self.get_domain_network_info(iface)

            print ("*"*20)
        print ("-"*30)

    # for debug
    def get_domain_network_info(self, iface):
        print ("*"*20)
        print ("Network = {}".format(self.get_network(iface)))
        print ("Bridge = {}".format(self.get_bridge(iface)))
        print ("Mac address = {}".format(self.get_mac(iface)))
        print ("Device = {}".format(self.get_device(iface)))

# for debug
api = DomainInfo()
api.show_domain_info_all()
<|endoftext|>


<commit_before>#!/ms/dist/python/PROJ/core/2.6.4-64/bin/python
import sys

from ipy import ipy

sys.path.insert(0, '../../lib/python2.6')
from aquilon.aqdb.dsdb import DsdbConnection
from aquilon.aqdb.db_factory import DbFactory

dsdb = DsdbConnection()
dbf = DbFactory()

add_column = "ALTER TABLE building ADD address VARCHAR(255)"
dbf.engine.execute(add_column)

dsdb_select = "SELECT bldg_name, bldg_addr FROM bldg WHERE state >=0"

upd = """UPDATE building SET address=q'#{0}#' WHERE id=(
    SELECT id FROM location WHERE name='{1}' AND location_type='building') """

buildings = dsdb.run_query(dsdb_select)
for row in buildings.fetchall():
    try:
        dbf.engine.execute(upd.format(row[1], row[0]))
    except Exception, e:
        print e

#wipe redundant comments fields
upd = "update location set comments = NULL where location_type='building'"
try:
    dbf.engine.execute(upd)
except Exception, e:
    print e

#what about redundant fullname fields? pull the 5 character codes from FBI?
#or LDAP names?

nonnull="ALTER TABLE building MODIFY(address VARCHAR(255) NOT NULL)"
try:
    dbf.engine.execute(nonnull)
except Exception, e:
    print e

from aquilon.aqdb.utils.constraints import rename_non_null_check_constraints
rename_non_null_check_constraints(db)
<commit_msg>upgrade script checks for null building addresses.<commit_after>#!/ms/dist/python/PROJ/core/2.6.4-64/bin/python
import sys

from ipy import ipy

sys.path.insert(0, '../../lib/python2.6')
from aquilon.aqdb.dsdb import DsdbConnection
from aquilon.aqdb.db_factory import DbFactory
from aquilon.aqdb.utils.constraints import rename_non_null_check_constraints

dsdb = DsdbConnection()
dbf = DbFactory()

add_column = "ALTER TABLE building ADD address VARCHAR(255)"
dbf.engine.execute(add_column)

dsdb_select = "SELECT bldg_name, bldg_addr FROM bldg WHERE state >=0"

upd = """UPDATE building SET address=q'#{0}#' WHERE id=(
    SELECT id FROM location WHERE name='{1}' AND location_type='building') """

buildings = dsdb.run_query(dsdb_select)
for row in buildings.fetchall():
    try:
        dbf.engine.execute(upd.format(row[1], row[0]))
    except Exception, e:
        print e

#wipe redundant comments fields
upd = "update location set comments = NULL where location_type='building'"
try:
    dbf.engine.execute(upd)
except Exception, e:
    print e

#what about redundant fullname fields? pull the 5 character codes from FBI?
#or LDAP names?
null_addrs = """
SELECT L.NAME, B.ADDRESS
FROM  LOCATION L, BUILDING B
WHERE L.ID = B.ID
AND B.ADDRESS IS NULL""".lstrip()

no_addrs = dbf.engine.execute(null_addrs)
if no_addrs is None:
    nonnull="ALTER TABLE building MODIFY(address VARCHAR(255) NOT NULL)"
    dbf.engine.execute(nonnull)
    rename_non_null_check_constraints(dbf)
else:  #### If there are NULL addresses, they've probably been deleted in dsdb
    msg = "The following buildings have no address:\n%s" % no_addrs
    raise ValueError(msg)
<|endoftext|>


<commit_before>"""A basic script to store points from a cb2 robot

Basic Usage: Run the script. with commandline args. Press `c` to capture  a
point. Press `s` to save and exit.

commandline args:
    -f,--file : filename

Copyright (c) 2016 GTRC. All rights reserved.
"""

import socket
import time
import argparse
import cb2_receive
import json
import sys
from contextlib import closing

def main():
    # Parse in arguments
    parser = argparse.ArgumentParser(
        description='Save Points',
        epilog="This software is designed to save points from a cb2 robot to a"
               " file for future use. Points are saved as both joint and"
               " cartesian points to the designated file. Once the program is "
               "running, press [c] to capture a point and press [s] to save"
               " the file and exit.")

    parser.add_argument("-f", "--file", metavar="file", type=str,
                        help='The file to save data to.',
                        default="cb2points.json")

    parser.add_argument("--ip", metavar="ip", type=str,
                        help='IP address of the robot', default="192.168.1.100")

    parser.add_argument("--port", metavar="port", type=int,
                        help='IP port on the robot', default=30003)

    args = parser.parse_args()

    # Check to make sure that we can access the file
    try:
        f = open(args.file, 'w')
        print "Able to access file, closing it now until we are done with it."
    except IOError:
        print "Unable to access file, bailing out."
        sys.exit("Unable to access file")
    finally:
        f.close()

    host = args.ip    # The remote host
    port = args.port  # The same port as used by the server

    print 'trying to connect to:: {}:{}'.format(host,port)
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM))\
            as robot_socket:
        robot_socket.connect((host, port))
        with cb2_receive.URReceiver(robot_socket, False) as my_ur_receiver:
            my_ur_receiver.start()
            run = True
            point_count = 0
            json_dict = dict()
            json_dict['time'] = time.time()
            json_dict['points'] = dict()
            while run:
                try:
                    key_input = str(raw_input('Input:'))
                except ValueError:
                    print ("Input was not valid. You must input either [c] or"
                           " [s]")
                    key_input = None
                if key_input is not None:
                    if key_input in ('c', 'C'):
                        with my_ur_receiver.lock:
                            json_dict['points'][point_count] = \
                                {'cartesian': my_ur_receiver.position,
                                 'joint': my_ur_receiver.actual_joint_positions}
                            point_count += 1
                    elif key_input in ('s', 'S'):
                        run = False
                    else:
                        print ("Input was not valid. You must input either [c]"
                               " or [s]")
            with open(args.file, 'w') as f:
                json.dump(json_dict, f, indent=4)

if __name__ == "__main__":
    main()
<commit_msg>Basic reformatting and fixed file open check.<commit_after>"""A basic script to store points from a cb2 robot

Basic Usage: Run the script, with commandline args. Press `c` to capture  a
point. Press `s` to save and exit.

Copyright (c) 2016 GTRC. All rights reserved.
"""

import socket
import time
import argparse
import cb2_receive
import json
import sys
from contextlib import closing

def main():
    # Parse in arguments
    parser = argparse.ArgumentParser(
        description='Save Points',
        epilog="This software is designed to save points from a cb2 robot to a"
               " file for future use. Points are saved as both joint and"
               " cartesian points to the designated file. Once the program is "
               "running, press [c] to capture a point and press [s] to save"
               " the file and exit.")

    parser.add_argument("-f", "--file", metavar="file", type=str,
                        help='The file to save data to.',
                        default="cb2points.json")

    parser.add_argument("--ip", metavar="ip", type=str,
                        help='IP address of the robot', default="192.168.1.100")

    parser.add_argument("--port", metavar="port", type=int,
                        help='IP port on the robot', default=30003)

    args = parser.parse_args()

    # Check to make sure that we can access the file
    try:
        f = open(args.file, 'w')
        print "Able to access file, closing it now until we are ready for it."
    except IOError:
        print "Unable to access file, bailing out."
        sys.exit("Unable to access file")
    f.close()

    host = args.ip    # The remote host
    port = args.port  # The same port as used by the server

    print 'trying to connect to:    {}:{}'.format(host, port)
    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM))\
            as robot_socket:
        robot_socket.connect((host, port))
        with cb2_receive.URReceiver(robot_socket, False) as my_ur_receiver:
            my_ur_receiver.start()
            run = True
            point_count = 0
            json_dict = dict()
            json_dict['time'] = time.time()
            json_dict['points'] = dict()
            while run:
                try:
                    key_input = str(raw_input('Input:'))
                except ValueError:
                    print ("Input was not valid. You must input either [c] or"
                           " [s]")
                    key_input = None
                if key_input is not None:
                    if key_input in ('c', 'C'):
                        with my_ur_receiver.lock:
                            json_dict['points'][point_count] = \
                                {'cartesian': my_ur_receiver.position,
                                 'joint': my_ur_receiver.actual_joint_positions}
                            point_count += 1
                    elif key_input in ('s', 'S'):
                        run = False
                    else:
                        print ("Input was not valid. You must input either [c]"
                               " or [s]")
            with open(args.file, 'w') as f:
                json.dump(json_dict, f, indent=4)

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>#  Copyright 2008 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import sys
import unittest

from robot.utils.normalizing import _CASE_INSENSITIVE_FILESYSTEM

from robotide.application import DataModel
from robotide.model import cache
from robotide import context
from resources import COMPLEX_SUITE_PATH, PATH_RESOURCE_NAME

COMPLEX_MODEL = DataModel(COMPLEX_SUITE_PATH)
COMPLEX_SUITE = COMPLEX_MODEL.suite

class APPMock(object):

    def import_new_resource(self, datafile, path):
        self.datafile = datafile
        self.path = path

APP_MOCK = APPMock()
context.APP = APP_MOCK

class _ContentAssistBaseTest(unittest.TestCase):

    def _assert_contains(self, keywords, name, source):
        for kw in keywords:
            if kw.name == name:
                if kw.source == source:
                    return
                raise AssertionError("Keyword '%s' had wrong source: '%s' != '%s'"
                                     % (kw.name, kw.source, source))
        raise AssertionError("Keyword '%s' not found in suite or resource\n"
                             "Imported libs: %s\n"
                             % (name, [lib for lib in
                                       cache.LIBRARYCACHE.libraries]))

    def _assert_does_not_contain(self, keywords, name, source):
        for kw in keywords:
            if kw.name == name and kw.source == source:
                raise AssertionError("Keyword '%s' found from source %s\n" %
                                     (name, source))

    def _assert_variable(self, suite, name):
        variables = [ var.name for var in suite.get_variables_for_content_assist() ]
        if not name in variables:
            raise AssertionError("Variable '%s' not found in %s" %
                                (name, variables))

    def _assert_variable_does_not_exist(self, suite, name):
        variables = [ var.name for var in suite.get_variables_for_content_assist() ]
        if name in variables:
            raise AssertionError("Variable '%s' found in %s" %
                                (name, variables))

class TestResolvingOwnKeywords(_ContentAssistBaseTest):

    def test_own_user_keywords(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'My Test Setup', COMPLEX_SUITE.name)

    def test_own_keyword_for_content_assist(self):
        self._assert_contains(COMPLEX_SUITE.content_assist_values(),
                              'My Test Setup', '<this file>')

    def test_filtering_keywords_with_longnames(self):
        self._assert_contains(COMPLEX_SUITE.content_assist_values(name='BuiltIn.Catenate'),
                              'Catenate', 'BuiltIn')
        self._assert_contains(COMPLEX_SUITE.content_assist_values(name='Catenate'),
                              'Catenate', 'BuiltIn')

class TestResolvingKeywordsFromImports(_ContentAssistBaseTest):

    def test_keywords_from_library_imports(self):
        for name, source in [('Should Be Equal', 'BuiltIn'),
                             ('File Should Exist', 'OperatingSystem')]:
            self._assert_contains(COMPLEX_SUITE.get_keywords(), name, source)

    def test_keywords_from_imports(self):
        for name, source in [('Resource UK', 'resource.html'),
                             ('Resource2 UK', 'resource2.html'),
                             ('Resource3 UK', 'resource3.html'),
                             ('UK From Text Resource', 'resource.txt'),
                             ]:
            self._assert_contains(COMPLEX_SUITE.get_keywords(), name, source)

    def test_keywords_from_resource_in_python_path(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Path Resource UK', PATH_RESOURCE_NAME)

    def test_keywords_from_spec_resource(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Attributeless Keyword', 'Spec Resource')

    def test_keywords_from_spec_library(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Testlib Keyword', 'TestLib')

    def test_spec_file_name_is_case_sensitive(self):
        self._assert_does_not_contain(COMPLEX_SUITE.get_keywords(),
                                      'Open Browser', 'seleniumlibrary')

class TestResolvingKeywordsFromImportsWithVariables(_ContentAssistBaseTest):

    def test_libary_defined_as_variable(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'List Should Contain Value', 'Collections')

    def test_variables_from_other_imports_can_be_used(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Open Connection', 'Telnet')

    def test_variables_are_resolved_before_passed_to_libraries(self):
        self._assert_contains(COMPLEX_SUITE.content_assist_values(),
                              'Get Mandatory', 'ArgLib')

    def test_variables_are_passed_to_libraries_in_resource_files(self):
        self._assert_contains(COMPLEX_SUITE.content_assist_values(),
                              'Longest', 'AnotherArgLib')

class TestModifyingDataAffectReturnedKeywords(_ContentAssistBaseTest):

    def tearDown(self):
        COMPLEX_SUITE.keywords.pop(-1)

    def test_changing_keywords_in_suite(self):
        COMPLEX_SUITE.keywords.new_keyword('New Keyword')
        self._assert_contains(COMPLEX_SUITE.get_keywords(), 'New Keyword',
                              COMPLEX_SUITE.name)

    def test_changing_keywords_in_resource(self):
        resource = COMPLEX_SUITE.get_resources()[0]
        resource.keywords.new_keyword('New UK')
        self._assert_contains(COMPLEX_SUITE.get_keywords(), 'New UK', resource.name)

    def test_get_all_keywords(self):
        for name, source in [('My Test Setup', 'Everything'),
                             ('Resource UK', 'resource.html'),
                             ('Another Resource UK', 'another_resource.html')]:
            self._assert_contains(COMPLEX_MODEL.get_all_keywords(), name, source)
        COMPLEX_SUITE.keywords.new_keyword('New Suite UK')
        self._assert_contains(COMPLEX_MODEL.get_all_keywords(), 'New Suite UK',
                              'Everything')

class TestModifyingImportsAffectsResolvedKeywords(_ContentAssistBaseTest):
    _more_resources = '../resources/more_resources/even_more_resources.txt'

    def tearDown(self):
        COMPLEX_SUITE.settings.imports.pop(-1)

    def test_adding_resource(self):
        self._robot_2_1_1_required()
        COMPLEX_SUITE.settings.imports.new_resource(self._more_resources)
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Foo', 'even_more_resources.txt')

    def test_updating_resource(self):
        self._robot_2_1_1_required()
        COMPLEX_SUITE.settings.imports.new_resource('../resources/more_resources/resources.txt')
        self._assert_does_not_contain(COMPLEX_SUITE.get_keywords(),
                                      'Foo', 'even_more_resources.txt')
        COMPLEX_SUITE.settings.imports[-1].set_str_value(self._more_resources)
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Foo', 'even_more_resources.txt')

    def test_removing_resource(self):
        self.test_adding_resource()
        COMPLEX_SUITE.settings.imports.pop(-1)
        self._assert_does_not_contain(COMPLEX_SUITE.get_keywords(),
                                      'Foo', 'even_more_resources.txt')
        # Hack, restore global state
        self.test_adding_resource()

    def test_added_resource_path_is_normalized_in_case_insensitive_file_systems(self):
        COMPLEX_SUITE.settings.imports.new_resource('../Resources/More_ResourceS/Even_More_Resources.txt')
        if _CASE_INSENSITIVE_FILESYSTEM:
            self._assert_contains(COMPLEX_SUITE.get_keywords(),
                                  'Foo','even_more_resources.txt')
        else:
            self._assert_does_not_contain(COMPLEX_SUITE.get_keywords(),
                                          'Foo', 'even_more_resources.txt')

    def test_adding_library(self):
        COMPLEX_SUITE.settings.imports.new_library('Dialogs')
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Execute Manual Step', 'Dialogs')

    def test_updating_library(self):
        COMPLEX_SUITE.settings.imports.new_library('InvalidDialogs')
        self._assert_does_not_contain(COMPLEX_SUITE.get_keywords(),
                                      'Execute Manual Step', 'Dialogs')
        COMPLEX_SUITE.settings.imports[-1].set_str_value('Dialogs')
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'Execute Manual Step', 'Dialogs')

    def _robot_2_1_1_required(self):
        try:
            import robot.parsing.txtreader
        except ImportError:
            raise AssertionError("Robot 2.1.1 or newer required to run this test.")

class TestResolvingVariables(_ContentAssistBaseTest):

    def test_get_variables_for_suite(self):
        self._assert_variable(COMPLEX_SUITE, '${SCALAR}')

    def test_variables_for_user_keyword_contain_arguments(self):
        kw = COMPLEX_SUITE.keywords[1]
        self._assert_variable(kw, '${scalar arg}')

    def test_get_variables_from_resource_files(self):
        for name in ['${SCALAR}', '@{LIST}', '${RESOURCE var}',
                     '@{RESOURCE 2 List VARIABLE}']:
            self._assert_variable(COMPLEX_SUITE, name)

    def test_finding_variables_from_variable_file(self):
        self._assert_variable(COMPLEX_SUITE, '${var_from_file}')

    def test_finding_variables_from_variable_file_importes_in_resource(self):
        self._assert_variable(COMPLEX_SUITE, '${var_from_resource_var_file}')

    def test_variables_are_resolved_before_passed_to_variable_files(self):
        self._assert_variable(COMPLEX_SUITE, '${value}')

class TestModifyingImportsAffectResolvedVariables(_ContentAssistBaseTest):

    def tearDown(self):
        COMPLEX_SUITE.settings.imports.pop(-1)

    def test_adding_variable_file(self):
        self._add_variable_import('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def test_updating_variable_file(self):
        self._add_variable_import('invalid.py')
        self._assert_variable_does_not_exist(COMPLEX_SUITE, '${var_in_resource2}')
        COMPLEX_SUITE.settings.imports[-1].set_str_value('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def test_deleting_variable_file(self):
        self._add_variable_import('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')
        COMPLEX_SUITE.settings.imports.pop(-1)
        self._assert_variable_does_not_exist(COMPLEX_SUITE, '${var_in_resource2}')
        self._add_variable_import('../resources/more_resources/even_more_varz.py')

    def test_adding_variable_file_in_pythonpath(self):
        path = os.path.join(os.path.dirname(__file__), '..', 'resources',
                            'robotdata', 'resources', 'resources2')
        sys.path.append(path)
        self._add_variable_import('even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def _add_variable_import(self, name):
        COMPLEX_SUITE.settings.imports.new_variables(name)

if __name__ == '__main__':
    unittest.main()
<commit_msg>This suite is now an integration test<commit_after>#  Copyright 2008 Nokia Siemens Networks Oyj
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import sys
import unittest

from robot.utils.normalizing import _CASE_INSENSITIVE_FILESYSTEM

from robotide.application import DataModel
from robotide.model import cache
from robotide import context
from resources import COMPLEX_SUITE_PATH, PATH_RESOURCE_NAME

COMPLEX_MODEL = DataModel(COMPLEX_SUITE_PATH)
COMPLEX_SUITE = COMPLEX_MODEL.suite

class APPMock(object):

    def import_new_resource(self, datafile, path):
        self.datafile = datafile
        self.path = path

APP_MOCK = APPMock()
context.APP = APP_MOCK

class _ContentAssistBaseTest(unittest.TestCase):

    def _assert_contains(self, keywords, name, source):
        for kw in keywords:
            if kw.name == name:
                if kw.source == source:
                    return
                raise AssertionError("Keyword '%s' had wrong source: '%s' != '%s'"
                                     % (kw.name, kw.source, source))
        raise AssertionError("Keyword '%s' not found in suite or resource\n"
                             "Imported libs: %s\n"
                             % (name, [lib for lib in
                                       cache.LIBRARYCACHE.libraries]))

    def _assert_does_not_contain(self, keywords, name, source):
        for kw in keywords:
            if kw.name == name and kw.source == source:
                raise AssertionError("Keyword '%s' found from source %s\n" %
                                     (name, source))

    def _assert_variable(self, suite, name):
        variables = [ var.name for var in suite.get_variables_for_content_assist() ]
        if not name in variables:
            raise AssertionError("Variable '%s' not found in %s" %
                                (name, variables))

    def _assert_variable_does_not_exist(self, suite, name):
        variables = [ var.name for var in suite.get_variables_for_content_assist() ]
        if name in variables:
            raise AssertionError("Variable '%s' found in %s" %
                                (name, variables))

    def _should_contain(self, name, source):
        for item in COMPLEX_SUITE.content_assist_values():
            if item.name == name and item.source == source:
                return
        raise AssertionError('Item "%s" not found from %s' % (name, source))

class TestResolvingKeywordAndVariablesForContentAssist(_ContentAssistBaseTest):
    exp_data = [ ('Should Be Equal', 'BuiltIn'),
                 ('File Should Exist', 'OperatingSystem'),
                 ('Resource UK', 'resource.html'),
                 ('Resource2 UK', 'resource2.html'),
                 ('Resource3 UK', 'resource3.html'),
                 ('UK From Text Resource', 'resource.txt'),
                 ('Path Resource UK', PATH_RESOURCE_NAME),
                 ('Attributeless Keyword', 'LibSpecLibrary'),
                 #('Attributeless Keyword', 'Spec Resource'),
                 ('Testlib Keyword', 'TestLib'),
                 ('List Should Contain Value', 'Collections'),
                 ('Open Connection', 'Telnet'),
                 ('Get Mandatory', 'ArgLib'),
                 ('Longest', 'AnotherArgLib'),
               ]

    def test_content_assist_for(self):
        for name, source in [('My Test Setup', '<this file>')] + self.exp_data:
            self._should_contain(name, source)

class TestResolvingOwnKeywords(_ContentAssistBaseTest):

    def test_own_user_keywords(self):
        self._assert_contains(COMPLEX_SUITE.get_keywords(),
                              'My Test Setup', COMPLEX_SUITE.name)

    def test_filtering_keywords_with_longnames(self):
        self._assert_contains(COMPLEX_SUITE.content_assist_values(name='BuiltIn.Catenate'),
                              'Catenate', 'BuiltIn')
        self._assert_contains(COMPLEX_SUITE.content_assist_values(name='Catenate'),
                              'Catenate', 'BuiltIn')

class TestModifyingDataAffectReturnedKeywords(_ContentAssistBaseTest):

    def tearDown(self):
        COMPLEX_SUITE.keywords.pop(-1)

    def test_changing_keywords_in_suite(self):
        COMPLEX_SUITE.keywords.new_keyword('New Keyword')
        self._assert_contains(COMPLEX_SUITE.get_keywords(), 'New Keyword',
                              COMPLEX_SUITE.name)

    def test_changing_keywords_in_resource(self):
        resource = COMPLEX_SUITE.get_resources()[0]
        resource.keywords.new_keyword('New UK')
        self._assert_contains(COMPLEX_SUITE.get_keywords(), 'New UK', resource.name)

    def test_get_all_keywords(self):
        for name, source in [('My Test Setup', 'Everything'),
                             ('Resource UK', 'resource.html'),
                             ('Another Resource UK', 'another_resource.html')]:
            self._assert_contains(COMPLEX_MODEL.get_all_keywords(), name, source)
        COMPLEX_SUITE.keywords.new_keyword('New Suite UK')
        self._assert_contains(COMPLEX_MODEL.get_all_keywords(), 'New Suite UK',
                              'Everything')

class TestResolvingVariables(_ContentAssistBaseTest):

    def test_get_variables_for_suite(self):
        self._assert_variable(COMPLEX_SUITE, '${SCALAR}')

    def test_variables_for_user_keyword_contain_arguments(self):
        kw = COMPLEX_SUITE.keywords[1]
        self._assert_variable(kw, '${scalar arg}')

    def test_get_variables_from_resource_files(self):
        for name in ['${SCALAR}', '@{LIST}', '${RESOURCE var}',
                     '@{RESOURCE 2 List VARIABLE}']:
            self._assert_variable(COMPLEX_SUITE, name)

    def test_finding_variables_from_variable_file(self):
        self._assert_variable(COMPLEX_SUITE, '${var_from_file}')

    def test_finding_variables_from_variable_file_importes_in_resource(self):
        self._assert_variable(COMPLEX_SUITE, '${var_from_resource_var_file}')

    def test_variables_are_resolved_before_passed_to_variable_files(self):
        self._assert_variable(COMPLEX_SUITE, '${value}')

class TestModifyingImportsAffectResolvedVariables(_ContentAssistBaseTest):

    def tearDown(self):
        COMPLEX_SUITE.settings.imports.pop(-1)

    def test_adding_variable_file(self):
        self._add_variable_import('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def test_updating_variable_file(self):
        self._add_variable_import('invalid.py')
        self._assert_variable_does_not_exist(COMPLEX_SUITE, '${var_in_resource2}')
        COMPLEX_SUITE.settings.imports[-1].set_str_value('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def test_deleting_variable_file(self):
        self._add_variable_import('../resources/more_resources/even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')
        COMPLEX_SUITE.settings.imports.pop(-1)
        self._assert_variable_does_not_exist(COMPLEX_SUITE, '${var_in_resource2}')
        self._add_variable_import('../resources/more_resources/even_more_varz.py')

    def test_adding_variable_file_in_pythonpath(self):
        path = os.path.join(os.path.dirname(__file__), '..', 'resources',
                            'robotdata', 'resources', 'resources2')
        sys.path.append(path)
        self._add_variable_import('even_more_varz.py')
        self._assert_variable(COMPLEX_SUITE, '${var_in_resource2}')

    def _add_variable_import(self, name):
        COMPLEX_SUITE.settings.imports.new_variables(name)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>#source =('foo','bar/baz','bar/bing/barrow')
#target=('fib','cat/baz','cat/bing/barrow','asdf','sdfg','dfgh','fghj','ghjk','qwer','wert','erty','wewer','weert','errty')

import tensorflow as tf

from tkinter import ttk
from tkinter import filedialog
from tkinter import *
import csv
import utilities.rename_checkpoint_to_partial

class RenameGUI(object):
  def __init__(self,source=None,target=None,transform=None):
    self._target_variables=[]
    self._source_variables=[]
    self._transform_definition=[]
    self._source=None
    self.build_gui()
    if source:
      self.load_source(source)
    if target:
      self.load_target(target)
    if transform:
      self.load_transform(transform)
    self.reload_tables()

  def build_gui(self):
    self.root = Tk()
    frame=Frame(self.root)
    Grid.rowconfigure(self.root, 0, weight=1)
    Grid.columnconfigure(self.root, 0, weight=1)
    frame.grid(row=0, column=0, sticky='nsew')
    Grid.columnconfigure(frame,0,weight=1)
    Grid.columnconfigure(frame,2,weight=1)
    Grid.rowconfigure(frame,0,weight=1)
    Grid.rowconfigure(frame,1,weight=1)
    self.treeS = ttk.Treeview(frame)
    self.treeT = ttk.Treeview(frame)
    self.treeLinked = ttk.Treeview(frame)
    scrollS = ttk.Scrollbar(frame,orient="vertical",command=self.treeS.yview)
    scrollT = ttk.Scrollbar(frame,orient="vertical",command=self.treeT.yview)
    scrollLinked = ttk.Scrollbar(frame,orient="vertical",command=self.treeLinked.yview)
    self.treeS.grid(row=0,column=0,sticky='nsew')
    scrollS.grid(row=0,column=1,sticky='nsew')
    self.treeT.grid(row=0,column=2,sticky='nsew')
    scrollT.grid(row=0,column=3,sticky='nsew')
    self.treeLinked.grid(row=1,column=0,sticky='nsew',columnspan=3)
    scrollLinked.grid(row=1,column=3,sticky='nsew')
    buttonFrame = Frame(frame)
    buttonFrame.grid(row=2, column=0,columnspan=4, sticky='nsew')
    Grid.columnconfigure(buttonFrame, 0, weight=1)
    Grid.columnconfigure(buttonFrame, 1, weight=1)
    Grid.columnconfigure(buttonFrame, 2, weight=1)
    Grid.columnconfigure(buttonFrame, 3, weight=1)
    Grid.columnconfigure(buttonFrame, 4, weight=1)
    loadSourceButton = ttk.Button(buttonFrame,command=self.loadS,text='Load Source Checkpoint')
    loadSourceButton.grid(row=2,column=0,sticky='nsew')
    loadTargetButton = ttk.Button(buttonFrame,command=self.loadT,text='Load Target Checkpoint')
    loadTargetButton.grid(row=2,column=1,sticky='nsew')
    loadTransformButton = ttk.Button(buttonFrame,command=self.loadTfm,text='Load Transform')
    loadTransformButton.grid(row=2,column=2,sticky='nsew')
    saveTransformationButton = ttk.Button(buttonFrame,command=self.save,text='Save Transformation')
    saveTransformationButton.grid(row=2,column=3,sticky='nsew')
    saveCheckpointButton = ttk.Button(buttonFrame,command=self.saveC,text='Save transformed checkpoint')
    saveCheckpointButton.grid(row=2,column=4,sticky='nsew')
    self.treeS.bind("<Double-ButtonPress-1>",self.bDDown)
    self.treeT.bind("<Double-ButtonPress-1>",self.bDDown)
    self.treeLinked.bind("<Double-ButtonPress-1>",self.bDDownLinked)
  def run_gui(self):
    self.root.mainloop()
  def load_source(self,source):
    self._source=source
    self._source_variables=tf.contrib.framework.list_variables(source)
    self.reload_tables()
  def load_target(self,target):
    self._target_variables=tf.contrib.framework.list_variables(target)
    self.reload_tables()
  def load_transform(self,transform):
    with open(transform,newline='') as csvfile:
      r=csv.reader(csvfile)
      self._transform_definition=[row for row in r]
    if any(len(row)!=2 for row in self._transform_definition):
      raise ValueError('Each line must have a source and target variable name')
      return
    self.reload_tables()
  def spl(self,x):
    return [e+'/' for e in x.split('/')[:-1]]+[e for e in x.split('/')[-1:] if e]
  def clear_tree(self,tree):
    for ch in tree.get_children():
      tree.delete(ch)
  def reload_tables(self):
    self.clear_tree(self.treeS)
    self.clear_tree(self.treeT)
    self.clear_tree(self.treeLinked)
    if self._source_variables:
      self.add_to_tree(self.treeS,[self.spl(v) for v,s in self._source_variables])
    if self._target_variables:
      self.add_to_tree(self.treeT,[self.spl(v) for v,s in self._target_variables])
    [self.link(*r) for r in self._transform_definition]
  def add_to_tree(self,tree,definition):
    for parts in definition:
      for it in range(0,len(parts)):
        if not tree.exists(''.join(parts[:it+1])):
          tree.insert(''.join(parts[:it]),'end',''.join(parts[:it+1]),text=parts[it])

# events
# In top row, double-clicking when an item is selected creates a transformation link
# which moves the nodes down to the lower tree
# In bottom row, double clicking unlinks and moves variables back up to the top self.treeS
  def loadS(self):
    source = filedialog.askopenfilename(filetypes = (('Checkpoint index','*.index'),))
    if source.endswith('.index'):
       source=source[:-6]
    self.load_source(source)
  def loadT(self):
    target=filedialog.askopenfilename(filetypes = (('Checkpoint index','*.index'),))
    if target.endswith('.index'):
       target=target[:-6]
    self.load_target(target)
  def loadTfm(self):
    self.load_transform(filedialog.askopenfilename(filetypes = (('csv','*.csv'),)))
  def current_transform_as_variable_pairs(self):
    pairs=[]
    tfms = self.treeLinked.get_children('')
    for tfm in tfms:
      src,trg=tfm[:-1].split('>>')
      if src[-1]!='/':
        pairs.append((src,trg))
      else:
        ch=[c for c in self.get_family(self.treeLinked,tfm)[1:] if c[-1] != '/']
        for c in ch:
          pairs.append((c.replace(tfm,src,1),c.replace(tfm,trg,1)))
    return pairs
  def save(self):
    filename= filedialog.asksaveasfilename(defaultextension=".csv", filetypes = ( ("csv file", "*.csv"), ) )
    with open(filename,mode='w',newline='') as file:
      if file is None:
          return
      w=csv.writer(file)
      [w.writerow(r) for r in self.current_transform_as_variable_pairs()]

  def saveC(self):
    if not self._source:
      raise ValueError('Source must be set before saving checkpoint')
    filename = filedialog.asksaveasfilename(defaultextension=".partial", filetypes = ( ("partial checkpoint file", "*.partial"), ) )
    if filename:
      utilities.rename_checkpoint_to_partial.rename_checkpoint_to_partial(self._source,filename,self.current_transform_as_variable_pairs())

  def get_family(self,tree,id):
    return [id]+[j for i in tree.get_children(id) for j in self.get_family(tree,i)]

  def clear_if_empty(self,tree,id):
    if len(self.get_family(tree,id))==1:
      parent=tree.parent(id)
      tree.delete(id)
      if parent:
        self.clear_if_empty(tree,parent)

  def link(self,src,trg):
    if src[-1]=='/' and trg[-1]=='/': # link scopes
      sCh=self.get_family(self.treeS,src)[1:]
      tCh=self.get_family(self.treeT,trg)[1:]
      matches=set([c.replace(src,'',1) for c in sCh if c[-1]!='/']).intersection(set([c.replace(trg,'',1) for c in tCh if c[-1]!='/']))
      self.add_to_tree(self.treeLinked,[[src+'>>'+trg+';']+self.spl(c) for c in matches])
      for c in matches:
        self.clear_if_empty(self.treeS,src+c)
        self.clear_if_empty(self.treeT,trg+c)
    elif src[-1]!='/' and trg[-1]!='/': # link variables
      self.add_to_tree(self.treeLinked,[[src+'>>'+trg+';']])
      self.clear_if_empty(self.treeS,src)
      self.clear_if_empty(self.treeT,trg)

  def bDDown(self,event):
    idS=self.treeS.focus()
    idT=self.treeT.focus()
    if not idS or not idT:
      return
    self.link(idS,idT)

  def bDDownLinked(self,event):
    id=self.treeLinked.focus()
    tfm,path=id.split(';',1)
    src,trg=tfm.split('>>')
    nodesToUnlink=self.get_family(self.treeLinked,id)
    addToTree(self.treeS,[self.spl(i.replace(tfm+';',src,1)) for i in nodesToUnlink if i[-1]!='/'])
    addToTree(self.treeT,[self.spl(i.replace(tfm+';',trg,1)) for i in nodesToUnlink if i[-1]!='/'])
    self.treeLinked.delete(id)
def main(argv):
  gui=RenameGUI(*argv)
  gui.run_gui()

if __name__=='__main__':
  main(sys.argv[1:])

<commit_msg>Issue #156: removed unneeded utilities/rename_checkpoint_gui.py<commit_after><|endoftext|>


<commit_before>#
# Description:
#   This module implements the functions to execute condor commands
#
# Author:
#   Igor Sfiligoi (Sept 7th 2006)
#

import os
import os.path
import popen2
import string

class UnconfigError(RuntimeError):
    def __init__(self,str):
        RuntimeError.__init__(self,str)

class ExeError(RuntimeError):
    def __init__(self,str):
        RuntimeError.__init__(self,str)

#
# Configuration
#

# Set path to condor binaries, if needed
def set_path(new_condor_bin_path):
    global condor_bin_path
    condor_bin_path=new_condor_bin_path

#
# Execute an arbitrary condor command and return its output as a list of lines
#  condor_exe uses a relative path to $CONDOR_BIN
# Fails if stderr is not empty
#

# can throw UnconfigError or ExeError
def exe_cmd(condor_exe,args):
    global condor_bin_path

    if condor_bin_path==None:
        raise UnconfigError, "condor_bin_path is undefined!"
    condor_exe_path=os.path.join(condor_bin_path,condor_exe)

    cmd="%s %s" % (condor_exe_path,args)

    return iexe_cmd(cmd)

############################################################
#
# P R I V A T E, do not use
#
############################################################

# can throw ExeError
def iexe_cmd(cmd):
    child=popen2.Popen3(cmd,True)
    child.tochild.close()
    tempOut = child.fromchild.readlines()
    child.fromchild.close()
    tempErr = child.childerr.readlines()
    child.childerr.close()
    errcode=child.wait()
    if (errcode!=0):
        raise ExeError, "Error running '%s'\ncode %i:%s"%(cmd,errcode,tempErr)
    return tempOut

#
# Set condor_bin_path
#

def init():
    global condor_bin_path
    # try using condor commands to find it out
    try:
        condor_bin_path=iexe_cmd("condor_config_val BIN")[0][:-1] # remove trailing newline
    except ExeError,e:
        # try to find the RELEASE_DIR, and append bin
        try:
            release_path=iexe_cmd("condor_config_val RELEASE_DIR")
            condor_bin_path=os.path.join(release_path[0][:-1],"bin")
        except ExeError,e:
            # try condor_q in the path
            try:
                condorq_bin_path=iexe_cmd("which condor_q")
                condor_bin_path=os.path.dirname(condorq_bin_path[0][:-1])
            except ExeError,e:
                # look for condor_config in /etc
                if os.environ.has_key("CONDOR_CONFIG"):
                    condor_config=os.environ["CONDOR_CONFIG"]
                else:
                    condor_config="/etc/condor/condor_config"

                try:
                    # BIN = <path>
                    bin_def=iexe_cmd('grep "^ *BIN" %s'%condor_config)
                    condor_bin_path=string.split(bin_def[0][:-1])[2]
                except ExeError, e:
                    try:
                        # RELEASE_DIR = <path>
                        release_def=iexe_cmd('grep "^ *RELEASE_DIR" %s'%condor_config)
                        condor_bin_path=os.path.join(string.split(release_def[0][:-1])[2],"bin")
                    except ExeError, e:
                        pass # don't know what else to try

# This way we know that it is undefined
condor_bin_path=None

init()

<commit_msg>Add additional error messages<commit_after>#
# Description:
#   This module implements the functions to execute condor commands
#
# Author:
#   Igor Sfiligoi (Sept 7th 2006)
#

import os
import os.path
import popen2
import string

class UnconfigError(RuntimeError):
    def __init__(self,str):
        RuntimeError.__init__(self,str)

class ExeError(RuntimeError):
    def __init__(self,str):
        RuntimeError.__init__(self,str)

#
# Configuration
#

# Set path to condor binaries, if needed
def set_path(new_condor_bin_path):
    global condor_bin_path
    condor_bin_path=new_condor_bin_path

#
# Execute an arbitrary condor command and return its output as a list of lines
#  condor_exe uses a relative path to $CONDOR_BIN
# Fails if stderr is not empty
#

# can throw UnconfigError or ExeError
def exe_cmd(condor_exe,args):
    global condor_bin_path

    if condor_bin_path==None:
        raise UnconfigError, "condor_bin_path is undefined!"
    condor_exe_path=os.path.join(condor_bin_path,condor_exe)

    cmd="%s %s" % (condor_exe_path,args)

    return iexe_cmd(cmd)

############################################################
#
# P R I V A T E, do not use
#
############################################################

# can throw ExeError
def iexe_cmd(cmd):
    child=popen2.Popen3(cmd,True)
    child.tochild.close()
    tempOut = child.fromchild.readlines()
    child.fromchild.close()
    tempErr = child.childerr.readlines()
    child.childerr.close()
    try:
       errcode=child.wait()
    except OSError, e:
       raise ExeError, "Error running '%s'\nStderr:%s\nException: %s"%(cms,tempErr,e)
    if (errcode!=0):
        raise ExeError, "Error running '%s'\ncode %i:%s"%(cmd,errcode,tempErr)
    return tempOut

#
# Set condor_bin_path
#

def init():
    global condor_bin_path
    # try using condor commands to find it out
    try:
        condor_bin_path=iexe_cmd("condor_config_val BIN")[0][:-1] # remove trailing newline
    except ExeError,e:
        # try to find the RELEASE_DIR, and append bin
        try:
            release_path=iexe_cmd("condor_config_val RELEASE_DIR")
            condor_bin_path=os.path.join(release_path[0][:-1],"bin")
        except ExeError,e:
            # try condor_q in the path
            try:
                condorq_bin_path=iexe_cmd("which condor_q")
                condor_bin_path=os.path.dirname(condorq_bin_path[0][:-1])
            except ExeError,e:
                # look for condor_config in /etc
                if os.environ.has_key("CONDOR_CONFIG"):
                    condor_config=os.environ["CONDOR_CONFIG"]
                else:
                    condor_config="/etc/condor/condor_config"

                try:
                    # BIN = <path>
                    bin_def=iexe_cmd('grep "^ *BIN" %s'%condor_config)
                    condor_bin_path=string.split(bin_def[0][:-1])[2]
                except ExeError, e:
                    try:
                        # RELEASE_DIR = <path>
                        release_def=iexe_cmd('grep "^ *RELEASE_DIR" %s'%condor_config)
                        condor_bin_path=os.path.join(string.split(release_def[0][:-1])[2],"bin")
                    except ExeError, e:
                        pass # don't know what else to try

# This way we know that it is undefined
condor_bin_path=None

init()

<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import xbmcaddon
import xbmc

addon = xbmcaddon.Addon()
addonpath = xbmc.translatePath(addon.getAddonInfo('path')).decode("utf-8")
userdatafolder = xbmc.translatePath("special://profile/addon_data/script.service.koalanrk").decode("utf-8")
if addon.getSetting("usecustomLibPath"):
    libpath = xbmc.translatePath(addon.getSetting("LibPath")).decode("utf-8")
else:
    libpath = xbmc.translatePath("special://profile/addon_data/script.service.koalanrk/Library").decode("utf-8")

if xbmc.getCondVisibility("system.platform.linux"):
    os = "linux"
elif xbmc.getCondVisibility("system.platform.windows"):
    os = "windows"
elif xbmc.getCondVisibility("system.platform.osx"):
    os = "osx"
elif xbmc.getCondVisibility("system.platform.android"):
    os = "android"
else:
    os = "other"
<commit_msg>redundant import<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import xbmcaddon
import xbmc

addon = xbmcaddon.Addon()
addonpath = xbmc.translatePath(addon.getAddonInfo('path')).decode("utf-8")
userdatafolder = xbmc.translatePath("special://profile/addon_data/script.service.koalanrk").decode("utf-8")
if addon.getSetting("usecustomLibPath"):
    libpath = xbmc.translatePath(addon.getSetting("LibPath")).decode("utf-8")
else:
    libpath = xbmc.translatePath("special://profile/addon_data/script.service.koalanrk/Library").decode("utf-8")

if xbmc.getCondVisibility("system.platform.linux"):
    os = "linux"
elif xbmc.getCondVisibility("system.platform.windows"):
    os = "win"
elif xbmc.getCondVisibility("system.platform.osx"):
    os = "osx"
elif xbmc.getCondVisibility("system.platform.android"):
    os = "android"
else:
    os = "other"
<|endoftext|>